diff --git a/Icon-padded.png b/Icon-padded.png new file mode 100644 index 00000000..71c4a620 Binary files /dev/null and b/Icon-padded.png differ diff --git a/app.json b/app.json index 15b1ee5f..edb95f89 100644 --- a/app.json +++ b/app.json @@ -12,6 +12,10 @@ }, "android": { "package": "com.schnappix", + "adaptiveIcon": { + "backgroundColor": "#050510", + "foregroundImage": "./Icon-padded.png" + }, "permissions": [ "android.permission.CAMERA", "android.permission.RECORD_AUDIO", diff --git a/node_modules/.bin/pixelmatch b/node_modules/.bin/pixelmatch new file mode 100644 index 00000000..209ce5c2 --- /dev/null +++ b/node_modules/.bin/pixelmatch @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../pixelmatch/bin/pixelmatch" "$@" +else + exec node "$basedir/../pixelmatch/bin/pixelmatch" "$@" +fi diff --git a/node_modules/.bin/pixelmatch.cmd b/node_modules/.bin/pixelmatch.cmd new file mode 100644 index 00000000..b9bbe6f7 --- /dev/null +++ b/node_modules/.bin/pixelmatch.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%\..\pixelmatch\bin\pixelmatch" %* diff --git a/node_modules/.bin/pixelmatch.ps1 b/node_modules/.bin/pixelmatch.ps1 new file mode 100644 index 00000000..bf755993 --- /dev/null +++ b/node_modules/.bin/pixelmatch.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/../pixelmatch/bin/pixelmatch" $args + } else { + & "$basedir/node$exe" "$basedir/../pixelmatch/bin/pixelmatch" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../pixelmatch/bin/pixelmatch" $args + } else { + & "node$exe" "$basedir/../pixelmatch/bin/pixelmatch" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 3cee3361..af20b2e3 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -2441,6 +2441,458 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/@jimp/bmp": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/bmp/-/bmp-0.22.12.tgz", + "integrity": "sha512-aeI64HD0npropd+AR76MCcvvRaa+Qck6loCOS03CkkxGHN5/r336qTM5HPUdHKMDOGzqknuVPA8+kK1t03z12g==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "bmp-js": "^0.1.0" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/core": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/core/-/core-0.22.12.tgz", + "integrity": "sha512-l0RR0dOPyzMKfjUW1uebzueFEDtCOj9fN6pyTYWWOM/VS4BciXQ1VVrJs8pO3kycGYZxncRKhCoygbNr8eEZQA==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "any-base": "^1.1.0", + "buffer": "^5.2.0", + "exif-parser": "^0.1.12", + "file-type": "^16.5.4", + "isomorphic-fetch": "^3.0.0", + "pixelmatch": "^4.0.2", + "tinycolor2": "^1.6.0" + } + }, + "node_modules/@jimp/core/node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/@jimp/custom": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/custom/-/custom-0.22.12.tgz", + "integrity": "sha512-xcmww1O/JFP2MrlGUMd3Q78S3Qu6W3mYTXYuIqFq33EorgYHV/HqymHfXy9GjiCJ7OI+7lWx6nYFOzU7M4rd1Q==", + "license": "MIT", + "dependencies": { + "@jimp/core": "^0.22.12" + } + }, + "node_modules/@jimp/gif": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/gif/-/gif-0.22.12.tgz", + "integrity": "sha512-y6BFTJgch9mbor2H234VSjd9iwAhaNf/t3US5qpYIs0TSbAvM02Fbc28IaDETj9+4YB4676sz4RcN/zwhfu1pg==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "gifwrap": "^0.10.1", + "omggif": "^1.0.9" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/jpeg": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/jpeg/-/jpeg-0.22.12.tgz", + "integrity": "sha512-Rq26XC/uQWaQKyb/5lksCTCxXhtY01NJeBN+dQv5yNYedN0i7iYu+fXEoRsfaJ8xZzjoANH8sns7rVP4GE7d/Q==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "jpeg-js": "^0.4.4" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-blit": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-blit/-/plugin-blit-0.22.12.tgz", + "integrity": "sha512-xslz2ZoFZOPLY8EZ4dC29m168BtDx95D6K80TzgUi8gqT7LY6CsajWO0FAxDwHz6h0eomHMfyGX0stspBrTKnQ==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-blur": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-blur/-/plugin-blur-0.22.12.tgz", + "integrity": "sha512-S0vJADTuh1Q9F+cXAwFPlrKWzDj2F9t/9JAbUvaaDuivpyWuImEKXVz5PUZw2NbpuSHjwssbTpOZ8F13iJX4uw==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-circle": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-circle/-/plugin-circle-0.22.12.tgz", + "integrity": "sha512-SWVXx1yiuj5jZtMijqUfvVOJBwOifFn0918ou4ftoHgegc5aHWW5dZbYPjvC9fLpvz7oSlptNl2Sxr1zwofjTg==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-color": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-color/-/plugin-color-0.22.12.tgz", + "integrity": "sha512-xImhTE5BpS8xa+mAN6j4sMRWaUgUDLoaGHhJhpC+r7SKKErYDR0WQV4yCE4gP+N0gozD0F3Ka1LUSaMXrn7ZIA==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "tinycolor2": "^1.6.0" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-contain": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-contain/-/plugin-contain-0.22.12.tgz", + "integrity": "sha512-Eo3DmfixJw3N79lWk8q/0SDYbqmKt1xSTJ69yy8XLYQj9svoBbyRpSnHR+n9hOw5pKXytHwUW6nU4u1wegHNoQ==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-blit": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5", + "@jimp/plugin-scale": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-cover": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-cover/-/plugin-cover-0.22.12.tgz", + "integrity": "sha512-z0w/1xH/v/knZkpTNx+E8a7fnasQ2wHG5ze6y5oL2dhH1UufNua8gLQXlv8/W56+4nJ1brhSd233HBJCo01BXA==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-crop": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5", + "@jimp/plugin-scale": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-crop": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-crop/-/plugin-crop-0.22.12.tgz", + "integrity": "sha512-FNuUN0OVzRCozx8XSgP9MyLGMxNHHJMFt+LJuFjn1mu3k0VQxrzqbN06yIl46TVejhyAhcq5gLzqmSCHvlcBVw==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-displace": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-displace/-/plugin-displace-0.22.12.tgz", + "integrity": "sha512-qpRM8JRicxfK6aPPqKZA6+GzBwUIitiHaZw0QrJ64Ygd3+AsTc7BXr+37k2x7QcyCvmKXY4haUrSIsBug4S3CA==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-dither": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-dither/-/plugin-dither-0.22.12.tgz", + "integrity": "sha512-jYgGdSdSKl1UUEanX8A85v4+QUm+PE8vHFwlamaKk89s+PXQe7eVE3eNeSZX4inCq63EHL7cX580dMqkoC3ZLw==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-fisheye": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-fisheye/-/plugin-fisheye-0.22.12.tgz", + "integrity": "sha512-LGuUTsFg+fOp6KBKrmLkX4LfyCy8IIsROwoUvsUPKzutSqMJnsm3JGDW2eOmWIS/jJpPaeaishjlxvczjgII+Q==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-flip": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-flip/-/plugin-flip-0.22.12.tgz", + "integrity": "sha512-m251Rop7GN8W0Yo/rF9LWk6kNclngyjIJs/VXHToGQ6EGveOSTSQaX2Isi9f9lCDLxt+inBIb7nlaLLxnvHX8Q==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-rotate": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-gaussian": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-gaussian/-/plugin-gaussian-0.22.12.tgz", + "integrity": "sha512-sBfbzoOmJ6FczfG2PquiK84NtVGeScw97JsCC3rpQv1PHVWyW+uqWFF53+n3c8Y0P2HWlUjflEla2h/vWShvhg==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-invert": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-invert/-/plugin-invert-0.22.12.tgz", + "integrity": "sha512-N+6rwxdB+7OCR6PYijaA/iizXXodpxOGvT/smd/lxeXsZ/empHmFFFJ/FaXcYh19Tm04dGDaXcNF/dN5nm6+xQ==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-mask": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-mask/-/plugin-mask-0.22.12.tgz", + "integrity": "sha512-4AWZg+DomtpUA099jRV8IEZUfn1wLv6+nem4NRJC7L/82vxzLCgXKTxvNvBcNmJjT9yS1LAAmiJGdWKXG63/NA==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-normalize": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-normalize/-/plugin-normalize-0.22.12.tgz", + "integrity": "sha512-0So0rexQivnWgnhacX4cfkM2223YdExnJTTy6d06WbkfZk5alHUx8MM3yEzwoCN0ErO7oyqEWRnEkGC+As1FtA==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-print": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-print/-/plugin-print-0.22.12.tgz", + "integrity": "sha512-c7TnhHlxm87DJeSnwr/XOLjJU/whoiKYY7r21SbuJ5nuH+7a78EW1teOaj5gEr2wYEd7QtkFqGlmyGXY/YclyQ==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "load-bmfont": "^1.4.1" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-blit": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-resize": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-resize/-/plugin-resize-0.22.12.tgz", + "integrity": "sha512-3NyTPlPbTnGKDIbaBgQ3HbE6wXbAlFfxHVERmrbqAi8R3r6fQPxpCauA8UVDnieg5eo04D0T8nnnNIX//i/sXg==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-rotate": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-rotate/-/plugin-rotate-0.22.12.tgz", + "integrity": "sha512-9YNEt7BPAFfTls2FGfKBVgwwLUuKqy+E8bDGGEsOqHtbuhbshVGxN2WMZaD4gh5IDWvR+emmmPPWGgaYNYt1gA==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-blit": ">=0.3.5", + "@jimp/plugin-crop": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-scale": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-scale/-/plugin-scale-0.22.12.tgz", + "integrity": "sha512-dghs92qM6MhHj0HrV2qAwKPMklQtjNpoYgAB94ysYpsXslhRTiPisueSIELRwZGEr0J0VUxpUY7HgJwlSIgGZw==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-shadow": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-shadow/-/plugin-shadow-0.22.12.tgz", + "integrity": "sha512-FX8mTJuCt7/3zXVoeD/qHlm4YH2bVqBuWQHXSuBK054e7wFRnRnbSLPUqAwSeYP3lWqpuQzJtgiiBxV3+WWwTg==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-blur": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5" + } + }, + "node_modules/@jimp/plugin-threshold": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugin-threshold/-/plugin-threshold-0.22.12.tgz", + "integrity": "sha512-4x5GrQr1a/9L0paBC/MZZJjjgjxLYrqSmWd+e+QfAEPvmRxdRoQ5uKEuNgXnm9/weHQBTnQBQsOY2iFja+XGAw==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-color": ">=0.8.0", + "@jimp/plugin-resize": ">=0.8.0" + } + }, + "node_modules/@jimp/plugins": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/plugins/-/plugins-0.22.12.tgz", + "integrity": "sha512-yBJ8vQrDkBbTgQZLty9k4+KtUQdRjsIDJSPjuI21YdVeqZxYywifHl4/XWILoTZsjTUASQcGoH0TuC0N7xm3ww==", + "license": "MIT", + "dependencies": { + "@jimp/plugin-blit": "^0.22.12", + "@jimp/plugin-blur": "^0.22.12", + "@jimp/plugin-circle": "^0.22.12", + "@jimp/plugin-color": "^0.22.12", + "@jimp/plugin-contain": "^0.22.12", + "@jimp/plugin-cover": "^0.22.12", + "@jimp/plugin-crop": "^0.22.12", + "@jimp/plugin-displace": "^0.22.12", + "@jimp/plugin-dither": "^0.22.12", + "@jimp/plugin-fisheye": "^0.22.12", + "@jimp/plugin-flip": "^0.22.12", + "@jimp/plugin-gaussian": "^0.22.12", + "@jimp/plugin-invert": "^0.22.12", + "@jimp/plugin-mask": "^0.22.12", + "@jimp/plugin-normalize": "^0.22.12", + "@jimp/plugin-print": "^0.22.12", + "@jimp/plugin-resize": "^0.22.12", + "@jimp/plugin-rotate": "^0.22.12", + "@jimp/plugin-scale": "^0.22.12", + "@jimp/plugin-shadow": "^0.22.12", + "@jimp/plugin-threshold": "^0.22.12", + "timm": "^1.6.1" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/png": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/png/-/png-0.22.12.tgz", + "integrity": "sha512-Mrp6dr3UTn+aLK8ty/dSKELz+Otdz1v4aAXzV5q53UDD2rbB5joKVJ/ChY310B+eRzNxIovbUF1KVrUsYdE8Hg==", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "pngjs": "^6.0.0" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/png/node_modules/pngjs": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-6.0.0.tgz", + "integrity": "sha512-TRzzuFRRmEoSW/p1KVAmiOgPco2Irlah+bGFCeNfJXxxYGwSw7YwAOAcd7X28K/m5bjBWKsC29KyoMfHbypayg==", + "license": "MIT", + "engines": { + "node": ">=12.13.0" + } + }, + "node_modules/@jimp/tiff": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/tiff/-/tiff-0.22.12.tgz", + "integrity": "sha512-E1LtMh4RyJsoCAfAkBRVSYyZDTtLq9p9LUiiYP0vPtXyxX4BiYBUYihTLSBlCQg5nF2e4OpQg7SPrLdJ66u7jg==", + "license": "MIT", + "dependencies": { + "utif2": "^4.0.1" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/types": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/types/-/types-0.22.12.tgz", + "integrity": "sha512-wwKYzRdElE1MBXFREvCto5s699izFHNVvALUv79GXNbsOVqlwlOxlWJ8DuyOGIXoLP4JW/m30YyuTtfUJgMRMA==", + "license": "MIT", + "dependencies": { + "@jimp/bmp": "^0.22.12", + "@jimp/gif": "^0.22.12", + "@jimp/jpeg": "^0.22.12", + "@jimp/png": "^0.22.12", + "@jimp/tiff": "^0.22.12", + "timm": "^1.6.1" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + } + }, + "node_modules/@jimp/utils": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/@jimp/utils/-/utils-0.22.12.tgz", + "integrity": "sha512-yJ5cWUknGnilBq97ZXOyOS0HhsHOyAyjHwYfHxGbSyMTohgQI6sVyE8KPgDwH8HHW/nMKXk8TrSwAE71zt716Q==", + "license": "MIT", + "dependencies": { + "regenerator-runtime": "^0.13.3" + } + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -2808,6 +3260,12 @@ "node": ">=10" } }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "license": "MIT" + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -3125,6 +3583,12 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/any-base": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/any-base/-/any-base-1.1.0.tgz", + "integrity": "sha512-uMgjozySS8adZZYePpaWs8cxB9/kdzmpX6SgJZ+wbz1K5eYk5QMYDVJaZKhxyIHUdnnJkfR7SVgStgH7LkGUyg==", + "license": "MIT" + }, "node_modules/any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", @@ -3483,6 +3947,12 @@ "node": ">=0.6" } }, + "node_modules/bmp-js": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/bmp-js/-/bmp-js-0.1.0.tgz", + "integrity": "sha512-vHdS19CnY3hwiNdkaqk93DvjVLfbEcI8mys4UjuWrlX1haDmroo8o4xCzh4wD6DGV6HxRCyauwhHRqMTfERtjw==", + "license": "MIT" + }, "node_modules/boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -3597,6 +4067,15 @@ "ieee754": "^1.2.1" } }, + "node_modules/buffer-equal": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-0.0.1.tgz", + "integrity": "sha512-RgSV6InVQ9ODPdLWJ5UAqBqJBOg370Nz6ZQtRzpt6nUjc8v0St97uJ4PYC6NztqIScrAXafKM3mZPMygSe1ggA==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -3673,6 +4152,15 @@ ], "license": "CC-BY-4.0" }, + "node_modules/centra": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/centra/-/centra-2.7.0.tgz", + "integrity": "sha512-PbFMgMSrmgx6uxCdm57RUos9Tc3fclMvhLSATYN39XsDV29B89zZ3KA89jmY0vwSGazyU+uerqwa6t+KaodPcg==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -4170,6 +4658,11 @@ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" } }, + "node_modules/dom-walk": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/dom-walk/-/dom-walk-0.1.2.tgz", + "integrity": "sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w==" + }, "node_modules/domelementtype": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", @@ -4372,6 +4865,20 @@ "node": ">=6" } }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/exif-parser": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/exif-parser/-/exif-parser-0.1.12.tgz", + "integrity": "sha512-c2bQfLNbMzLPmzQuOr8fy0csy84WmwnER81W88DzTp9CYNPJ6yzOj2EZAh9pywYpqHnshVLHQJ8WzldAyfY+Iw==" + }, "node_modules/expo": { "version": "54.0.35", "resolved": "https://registry.npmjs.org/expo/-/expo-54.0.35.tgz", @@ -4652,6 +5159,23 @@ } } }, + "node_modules/file-type": { + "version": "16.5.4", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-16.5.4.tgz", + "integrity": "sha512-/yFHK0aGjFEgDJjEKP0pWCplsPFPhwyfwevf/pVxiN0tmE4L9LmwWxWukdJSHdoCli4VgQLehjJtwQBnqmsKcw==", + "license": "MIT", + "dependencies": { + "readable-web-to-node-stream": "^3.0.0", + "strtok3": "^6.2.4", + "token-types": "^4.1.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", @@ -4716,6 +5240,26 @@ "integrity": "sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw==", "license": "MIT" }, + "node_modules/follow-redirects": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/fontfaceobserver": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/fontfaceobserver/-/fontfaceobserver-2.3.0.tgz", @@ -4807,6 +5351,16 @@ "node": ">=6" } }, + "node_modules/gifwrap": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/gifwrap/-/gifwrap-0.10.1.tgz", + "integrity": "sha512-2760b1vpJHNmLzZ/ubTtNnEx5WApN/PYWJvXvgS+tL1egTTthayFYIQQNi136FLEDcN/IyEY2EcGpIITD6eYUw==", + "license": "MIT", + "dependencies": { + "image-q": "^4.0.0", + "omggif": "^1.0.10" + } + }, "node_modules/glob": { "version": "13.0.6", "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", @@ -4860,6 +5414,16 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/global": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/global/-/global-4.4.0.tgz", + "integrity": "sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w==", + "license": "MIT", + "dependencies": { + "min-document": "^2.19.0", + "process": "^0.11.10" + } + }, "node_modules/got": { "version": "11.8.6", "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz", @@ -5072,6 +5636,21 @@ "node": ">= 4" } }, + "node_modules/image-q": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/image-q/-/image-q-4.0.0.tgz", + "integrity": "sha512-PfJGVgIfKQJuq3s0tTDOKtztksibuUEbJQIYT3by6wctQo+Rdlh7ef4evJ5NCdxY4CfMbvFkocEwbl4BF8RlJw==", + "license": "MIT", + "dependencies": { + "@types/node": "16.9.1" + } + }, + "node_modules/image-q/node_modules/@types/node": { + "version": "16.9.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.9.1.tgz", + "integrity": "sha512-QpLcX9ZSsq3YYUUnD3nFDY8H7wctAhQj/TFKL8Ya8v5fMm3CFXxo8zStsLAl780ltoYoo1WvKUVGBQK+1ifr7g==", + "license": "MIT" + }, "node_modules/image-size": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.1.tgz", @@ -5173,6 +5752,12 @@ "node": ">=8" } }, + "node_modules/is-function": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-function/-/is-function-1.0.2.tgz", + "integrity": "sha512-lw7DUp0aWXYg+CBCN+JKkcE0Q2RayZnSvnZBlwgxHBQhqt5pZNVy4Ri7H9GmmXkdu7LUthszM+Tor1u/2iBcpQ==", + "license": "MIT" + }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -5200,6 +5785,16 @@ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "license": "ISC" }, + "node_modules/isomorphic-fetch": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-3.0.0.tgz", + "integrity": "sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.6.1", + "whatwg-fetch": "^3.4.1" + } + }, "node_modules/istanbul-lib-coverage": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", @@ -5418,12 +6013,30 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/jimp": { + "version": "0.22.12", + "resolved": "https://registry.npmjs.org/jimp/-/jimp-0.22.12.tgz", + "integrity": "sha512-R5jZaYDnfkxKJy1dwLpj/7cvyjxiclxU3F4TrI/J4j2rS0niq6YDUMoPn5hs8GDpO+OZGo7Ky057CRtWesyhfg==", + "license": "MIT", + "dependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/plugins": "^0.22.12", + "@jimp/types": "^0.22.12", + "regenerator-runtime": "^0.13.3" + } + }, "node_modules/jimp-compact": { "version": "0.16.1", "resolved": "https://registry.npmjs.org/jimp-compact/-/jimp-compact-0.16.1.tgz", "integrity": "sha512-dZ6Ra7u1G8c4Letq/B5EzAxj4tLFHL+cGtdpR+PVm4yzPDj+lCk+AbivWt1eOM+ikzkowtyV7qSqX6qr3t71Ww==", "license": "MIT" }, + "node_modules/jpeg-js": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/jpeg-js/-/jpeg-js-0.4.4.tgz", + "integrity": "sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==", + "license": "BSD-3-Clause" + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -5602,6 +6215,22 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "license": "MIT" }, + "node_modules/load-bmfont": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/load-bmfont/-/load-bmfont-1.4.2.tgz", + "integrity": "sha512-qElWkmjW9Oq1F9EI5Gt7aD9zcdHb9spJCW1L/dmPf7KzCCEJxq8nhHz5eCgI9aMf7vrG/wyaCqdsI+Iy9ZTlog==", + "license": "MIT", + "dependencies": { + "buffer-equal": "0.0.1", + "mime": "^1.3.4", + "parse-bmfont-ascii": "^1.0.3", + "parse-bmfont-binary": "^1.0.5", + "parse-bmfont-xml": "^1.1.4", + "phin": "^3.7.1", + "xhr": "^2.0.1", + "xtend": "^4.0.0" + } + }, "node_modules/locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", @@ -6214,6 +6843,15 @@ "node": ">=4" } }, + "node_modules/min-document": { + "version": "2.19.2", + "resolved": "https://registry.npmjs.org/min-document/-/min-document-2.19.2.tgz", + "integrity": "sha512-8S5I8db/uZN8r9HSLFVWPdJCvYOejMcEC82VIzNUc6Zkklf/d1gg2psfE79/vyhWOj4+J8MtwmoOz3TmvaGu5A==", + "license": "MIT", + "dependencies": { + "dom-walk": "^0.1.0" + } + }, "node_modules/minimatch": { "version": "9.0.9", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", @@ -6321,6 +6959,26 @@ "integrity": "sha512-SrQrok4CATudVzBS7coSz26QRSmlK9TzzoFbeKfcPBUFPjcQM9Rqvr/DlJkOrwI/0KcgvMub1n1g5Jt9EgRn4A==", "license": "MIT" }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, "node_modules/node-forge": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz", @@ -6421,6 +7079,12 @@ "node": ">=0.10.0" } }, + "node_modules/omggif": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/omggif/-/omggif-1.0.10.tgz", + "integrity": "sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw==", + "license": "MIT" + }, "node_modules/on-finished": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", @@ -6628,6 +7292,62 @@ "node": ">=6" } }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, + "node_modules/parse-bmfont-ascii": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/parse-bmfont-ascii/-/parse-bmfont-ascii-1.0.6.tgz", + "integrity": "sha512-U4RrVsUFCleIOBsIGYOMKjn9PavsGOXxbvYGtMOEfnId0SVNsgehXh1DxUdVPLoxd5mvcEtvmKs2Mmf0Mpa1ZA==", + "license": "MIT" + }, + "node_modules/parse-bmfont-binary": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/parse-bmfont-binary/-/parse-bmfont-binary-1.0.6.tgz", + "integrity": "sha512-GxmsRea0wdGdYthjuUeWTMWPqm2+FAd4GI8vCvhgJsFnoGhTrLhXDDupwTo7rXVAgaLIGoVHDZS9p/5XbSqeWA==", + "license": "MIT" + }, + "node_modules/parse-bmfont-xml": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/parse-bmfont-xml/-/parse-bmfont-xml-1.1.6.tgz", + "integrity": "sha512-0cEliVMZEhrFDwMh4SxIyVJpqYoOWDJ9P895tFuS+XuNzI5UBmBk5U5O4KuJdTnZpSBI4LFA2+ZiJaiwfSwlMA==", + "license": "MIT", + "dependencies": { + "xml-parse-from-string": "^1.0.0", + "xml2js": "^0.5.0" + } + }, + "node_modules/parse-bmfont-xml/node_modules/xml2js": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", + "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/parse-bmfont-xml/node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/parse-headers": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.6.tgz", + "integrity": "sha512-Tz11t3uKztEW5FEVZnj1ox8GKblWn+PvHY9TmJV5Mll2uHEwRdR/5Li1OlXoECjLYkApdhWy44ocONwXLiKO5A==", + "license": "MIT" + }, "node_modules/parse-png": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/parse-png/-/parse-png-2.1.0.tgz", @@ -6707,6 +7427,32 @@ "node": "20 || >=22" } }, + "node_modules/peek-readable": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-4.1.0.tgz", + "integrity": "sha512-ZI3LnwUv5nOGbQzD9c2iDG6toheuXSZP5esSHBjopsXH4dg19soufvpUGA3uohi5anFtGb2lhAVdHzH6R/Evvg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/phin": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/phin/-/phin-3.7.1.tgz", + "integrity": "sha512-GEazpTWwTZaEQ9RhL7Nyz0WwqilbqgLahDM3D0hxWwmVDI52nXEybHqiN6/elwpkJBhcuj+WbBu+QfT0uhPGfQ==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT", + "dependencies": { + "centra": "^2.7.0" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -6734,6 +7480,18 @@ "node": ">= 6" } }, + "node_modules/pixelmatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/pixelmatch/-/pixelmatch-4.0.2.tgz", + "integrity": "sha512-J8B6xqiO37sU/gkcMglv6h5Jbd9xNER7aHzpfRdNmV4IbQBzBpe4l9XmbG+xPF/znacgu2jfEw+wHffaq/YkXA==", + "license": "ISC", + "dependencies": { + "pngjs": "^3.0.0" + }, + "bin": { + "pixelmatch": "bin/pixelmatch" + } + }, "node_modules/plist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz", @@ -6841,6 +7599,15 @@ "node": "^14.17.0 || ^16.13.0 || >=18.0.0" } }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, "node_modules/progress": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", @@ -7240,6 +8007,38 @@ "node": ">=0.10.0" } }, + "node_modules/readable-stream": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", + "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/readable-web-to-node-stream": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/readable-web-to-node-stream/-/readable-web-to-node-stream-3.0.4.tgz", + "integrity": "sha512-9nX56alTf5bwXQ3ZDipHJhusu9NTQJ/CVPtb/XHAJCXihZeitfJvIRS4GqQ/mfIoOE3IelHMrpayVrosdHBuLw==", + "license": "MIT", + "dependencies": { + "readable-stream": "^4.7.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/regenerate": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz", @@ -7817,6 +8616,15 @@ "node": ">= 0.10.0" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -7873,6 +8681,23 @@ "node": ">=0.10.0" } }, + "node_modules/strtok3": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-6.3.0.tgz", + "integrity": "sha512-fZtbhtvI9I48xDSywd/somNqgUHl2L2cstmXCCif0itOf96jeW18MBSyrLuNicYQVkvpOxkZtkzujiTJ9LW5Jw==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^4.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/structured-headers": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/structured-headers/-/structured-headers-0.4.1.tgz", @@ -8105,6 +8930,18 @@ "integrity": "sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA==", "license": "MIT" }, + "node_modules/timm": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/timm/-/timm-1.7.1.tgz", + "integrity": "sha512-IjZc9KIotudix8bMaBW6QvMuq64BrJWFs1+4V0lXwWGQZwH+LnX87doAYhem4caOEusRP9/g6jVDQmZ8XOk1nw==", + "license": "MIT" + }, + "node_modules/tinycolor2": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz", + "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==", + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.16", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", @@ -8148,6 +8985,29 @@ "node": ">=0.6" } }, + "node_modules/token-types": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-4.2.1.tgz", + "integrity": "sha512-6udB24Q737UD/SDsKAHI9FCRP7Bqc9D/MQUV02ORQg5iskjtLJlZJNdN4kKtcdtwCeWIwIHDGaUsTsCCAa8sFQ==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, "node_modules/ts-interface-checker": { "version": "0.1.13", "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", @@ -8280,6 +9140,15 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/utif2": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/utif2/-/utif2-4.1.0.tgz", + "integrity": "sha512-+oknB9FHrJ7oW7A2WZYajOcv4FcDR4CfoGB0dPNfxbi4GO05RRnFmt5oa23+9w32EanrYcSJWspUiJkLMs+37w==", + "license": "MIT", + "dependencies": { + "pako": "^1.0.11" + } + }, "node_modules/utils-merge": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", @@ -8372,6 +9241,16 @@ "integrity": "sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg==", "license": "MIT" }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/whatwg-url-without-unicode": { "version": "8.0.0-3", "resolved": "https://registry.npmjs.org/whatwg-url-without-unicode/-/whatwg-url-without-unicode-8.0.0-3.tgz", @@ -8410,6 +9289,12 @@ "ieee754": "^1.1.13" } }, + "node_modules/whatwg-url/node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -8523,6 +9408,24 @@ "uuid": "dist/bin/uuid" } }, + "node_modules/xhr": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/xhr/-/xhr-2.6.0.tgz", + "integrity": "sha512-/eCGLb5rxjx5e3mF1A7s+pLlR6CGyqWN91fv1JgER5mVWg1MZmlhBvy9kjcsOdRk8RrIujotWyJamfyrp+WIcA==", + "license": "MIT", + "dependencies": { + "global": "~4.4.0", + "is-function": "^1.0.1", + "parse-headers": "^2.0.0", + "xtend": "^4.0.0" + } + }, + "node_modules/xml-parse-from-string": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/xml-parse-from-string/-/xml-parse-from-string-1.0.1.tgz", + "integrity": "sha512-ErcKwJTF54uRzzNMXq2X5sMIy88zJvfN2DmdoQvy7PAFJ+tPRU6ydWuOKNMyfmOjdyBQTFREi60s0Y0SyI0G0g==", + "license": "MIT" + }, "node_modules/xml2js": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.0.tgz", @@ -8554,6 +9457,15 @@ "node": ">=8.0" } }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/node_modules/@jimp/bmp/CHANGELOG.md b/node_modules/@jimp/bmp/CHANGELOG.md new file mode 100644 index 00000000..3d839517 --- /dev/null +++ b/node_modules/@jimp/bmp/CHANGELOG.md @@ -0,0 +1,85 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/bmp/LICENSE b/node_modules/@jimp/bmp/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/bmp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/bmp/README.md b/node_modules/@jimp/bmp/README.md new file mode 100644 index 00000000..dd90e545 --- /dev/null +++ b/node_modules/@jimp/bmp/README.md @@ -0,0 +1,6 @@ +
+ +

@jimp/bmp

+

Default Jimp bmp encoder/decoder.

+
diff --git a/node_modules/@jimp/bmp/es/index.js b/node_modules/@jimp/bmp/es/index.js new file mode 100644 index 00000000..f4dd9861 --- /dev/null +++ b/node_modules/@jimp/bmp/es/index.js @@ -0,0 +1,50 @@ +import BMP from "bmp-js"; +import { scan } from "@jimp/utils"; +const MIME_TYPE = "image/bmp"; +const MIME_TYPE_SECOND = "image/x-ms-bmp"; +function toAGBR(image) { + return scan(image, 0, 0, image.bitmap.width, image.bitmap.height, function (x, y, index) { + const red = this.bitmap.data[index + 0]; + const green = this.bitmap.data[index + 1]; + const blue = this.bitmap.data[index + 2]; + const alpha = this.bitmap.data[index + 3]; + this.bitmap.data[index + 0] = alpha; + this.bitmap.data[index + 1] = blue; + this.bitmap.data[index + 2] = green; + this.bitmap.data[index + 3] = red; + }).bitmap; +} +function fromAGBR(bitmap) { + return scan({ + bitmap + }, 0, 0, bitmap.width, bitmap.height, function (x, y, index) { + const alpha = this.bitmap.data[index + 0]; + const blue = this.bitmap.data[index + 1]; + const green = this.bitmap.data[index + 2]; + const red = this.bitmap.data[index + 3]; + this.bitmap.data[index + 0] = red; + this.bitmap.data[index + 1] = green; + this.bitmap.data[index + 2] = blue; + this.bitmap.data[index + 3] = bitmap.is_with_alpha ? alpha : 0xff; + }).bitmap; +} +const decode = data => fromAGBR(BMP.decode(data)); +const encode = image => BMP.encode(toAGBR(image)).data; +export default (() => ({ + mime: { + [MIME_TYPE]: ["bmp"] + }, + constants: { + MIME_BMP: MIME_TYPE, + MIME_X_MS_BMP: MIME_TYPE_SECOND + }, + decoders: { + [MIME_TYPE]: decode, + [MIME_TYPE_SECOND]: decode + }, + encoders: { + [MIME_TYPE]: encode, + [MIME_TYPE_SECOND]: encode + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/bmp/es/index.js.map b/node_modules/@jimp/bmp/es/index.js.map new file mode 100644 index 00000000..56d4859c --- /dev/null +++ b/node_modules/@jimp/bmp/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["BMP","scan","MIME_TYPE","MIME_TYPE_SECOND","toAGBR","image","bitmap","width","height","x","y","index","red","data","green","blue","alpha","fromAGBR","is_with_alpha","decode","encode","mime","constants","MIME_BMP","MIME_X_MS_BMP","decoders","encoders"],"sources":["../src/index.js"],"sourcesContent":["import BMP from \"bmp-js\";\nimport { scan } from \"@jimp/utils\";\n\nconst MIME_TYPE = \"image/bmp\";\nconst MIME_TYPE_SECOND = \"image/x-ms-bmp\";\n\nfunction toAGBR(image) {\n return scan(\n image,\n 0,\n 0,\n image.bitmap.width,\n image.bitmap.height,\n function (x, y, index) {\n const red = this.bitmap.data[index + 0];\n const green = this.bitmap.data[index + 1];\n const blue = this.bitmap.data[index + 2];\n const alpha = this.bitmap.data[index + 3];\n\n this.bitmap.data[index + 0] = alpha;\n this.bitmap.data[index + 1] = blue;\n this.bitmap.data[index + 2] = green;\n this.bitmap.data[index + 3] = red;\n }\n ).bitmap;\n}\n\nfunction fromAGBR(bitmap) {\n return scan(\n { bitmap },\n 0,\n 0,\n bitmap.width,\n bitmap.height,\n function (x, y, index) {\n const alpha = this.bitmap.data[index + 0];\n const blue = this.bitmap.data[index + 1];\n const green = this.bitmap.data[index + 2];\n const red = this.bitmap.data[index + 3];\n\n this.bitmap.data[index + 0] = red;\n this.bitmap.data[index + 1] = green;\n this.bitmap.data[index + 2] = blue;\n this.bitmap.data[index + 3] = bitmap.is_with_alpha ? alpha : 0xff;\n }\n ).bitmap;\n}\n\nconst decode = (data) => fromAGBR(BMP.decode(data));\nconst encode = (image) => BMP.encode(toAGBR(image)).data;\n\nexport default () => ({\n mime: { [MIME_TYPE]: [\"bmp\"] },\n\n constants: {\n MIME_BMP: MIME_TYPE,\n MIME_X_MS_BMP: MIME_TYPE_SECOND,\n },\n\n decoders: {\n [MIME_TYPE]: decode,\n [MIME_TYPE_SECOND]: decode,\n },\n\n encoders: {\n [MIME_TYPE]: encode,\n [MIME_TYPE_SECOND]: encode,\n },\n});\n"],"mappings":"AAAA,OAAOA,GAAG,MAAM,QAAQ;AACxB,SAASC,IAAI,QAAQ,aAAa;AAElC,MAAMC,SAAS,GAAG,WAAW;AAC7B,MAAMC,gBAAgB,GAAG,gBAAgB;AAEzC,SAASC,MAAM,CAACC,KAAK,EAAE;EACrB,OAAOJ,IAAI,CACTI,KAAK,EACL,CAAC,EACD,CAAC,EACDA,KAAK,CAACC,MAAM,CAACC,KAAK,EAClBF,KAAK,CAACC,MAAM,CAACE,MAAM,EACnB,UAAUC,CAAC,EAAEC,CAAC,EAAEC,KAAK,EAAE;IACrB,MAAMC,GAAG,GAAG,IAAI,CAACN,MAAM,CAACO,IAAI,CAACF,KAAK,GAAG,CAAC,CAAC;IACvC,MAAMG,KAAK,GAAG,IAAI,CAACR,MAAM,CAACO,IAAI,CAACF,KAAK,GAAG,CAAC,CAAC;IACzC,MAAMI,IAAI,G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ACO,IAAI,CAACF,KAAK,GAAG,CAAC,CAAC,GAAGI,IAAI;IAClC,IAAI,CAACT,MAAM,CAACO,IAAI,CAACF,KAAK,GAAG,CAAC,CAAC,GAAGL,MAAM,CAACY,aAAa,GAAGF,KAAK,GAAG,IAAI;EACnE,CAAC,CACF,CAACV,MAAM;AACV;AAEA,MAAMa,MAAM,GAAIN,IAAI,IAAKI,QAAQ,CAACjB,GAAG,CAACmB,MAAM,CAACN,IAAI,CAAC,CAAC;AACnD,MAAMO,MAAM,GAAIf,KAAK,IAAKL,GAAG,CAACoB,MAAM,CAAChB,MAAM,CAACC,KAAK,CAAC,CAAC,CAACQ,IAAI;AAExD,gBAAe,OAAO;EACpBQ,IAAI,EAAE;IAAE,CAACnB,SAAS,GAAG,CAAC,KAAK;EAAE,CAAC;EAE9BoB,SAAS,EAAE;IACTC,QAAQ,EAAErB,SAAS;IACnBsB,aAAa,EAAErB;EACjB,CAAC;EAEDsB,QAAQ,EAAE;IACR,CAACvB,SAAS,GAAGiB,MAAM;IACnB,CAAChB,gBAAgB,GAAGgB;EACtB,CAAC;EAEDO,QAAQ,EAAE;IACR,CAACxB,SAAS,GAAGkB,MAAM;IACnB,CAACjB,gBAAgB,GAAGiB;EACtB;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/bmp/index.d.ts b/node_modules/@jimp/bmp/index.d.ts new file mode 100644 index 00000000..0a9b9a51 --- /dev/null +++ b/node_modules/@jimp/bmp/index.d.ts @@ -0,0 +1,24 @@ +import { DecoderFn, EncoderFn } from "@jimp/core"; + +interface Bmp { + constants: { + MIME_BMP: "image/bmp"; + MIME_X_MS_BMP: "image/x-ms-bmp"; + }; + + mime: { + "image/bmp": string[]; + }; + + decoders: { + "image/bmp": DecoderFn; + "image/x-ms-bmp": DecoderFn; + }; + + encoders: { + "image/bmp": EncoderFn; + "image/x-ms-bmp": EncoderFn; + }; +} + +export default function (): Bmp; diff --git a/node_modules/@jimp/bmp/package.json b/node_modules/@jimp/bmp/package.json new file mode 100644 index 00000000..c3b6f766 --- /dev/null +++ b/node_modules/@jimp/bmp/package.json @@ -0,0 +1,38 @@ +{ + "name": "@jimp/bmp", + "version": "0.22.12", + "description": "Default Jimp bmp encoder/decoder.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "bmp-js": "^0.1.0" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/bmp/src/index.js b/node_modules/@jimp/bmp/src/index.js new file mode 100644 index 00000000..12fe2c79 --- /dev/null +++ b/node_modules/@jimp/bmp/src/index.js @@ -0,0 +1,69 @@ +import BMP from "bmp-js"; +import { scan } from "@jimp/utils"; + +const MIME_TYPE = "image/bmp"; +const MIME_TYPE_SECOND = "image/x-ms-bmp"; + +function toAGBR(image) { + return scan( + image, + 0, + 0, + image.bitmap.width, + image.bitmap.height, + function (x, y, index) { + const red = this.bitmap.data[index + 0]; + const green = this.bitmap.data[index + 1]; + const blue = this.bitmap.data[index + 2]; + const alpha = this.bitmap.data[index + 3]; + + this.bitmap.data[index + 0] = alpha; + this.bitmap.data[index + 1] = blue; + this.bitmap.data[index + 2] = green; + this.bitmap.data[index + 3] = red; + } + ).bitmap; +} + +function fromAGBR(bitmap) { + return scan( + { bitmap }, + 0, + 0, + bitmap.width, + bitmap.height, + function (x, y, index) { + const alpha = this.bitmap.data[index + 0]; + const blue = this.bitmap.data[index + 1]; + const green = this.bitmap.data[index + 2]; + const red = this.bitmap.data[index + 3]; + + this.bitmap.data[index + 0] = red; + this.bitmap.data[index + 1] = green; + this.bitmap.data[index + 2] = blue; + this.bitmap.data[index + 3] = bitmap.is_with_alpha ? alpha : 0xff; + } + ).bitmap; +} + +const decode = (data) => fromAGBR(BMP.decode(data)); +const encode = (image) => BMP.encode(toAGBR(image)).data; + +export default () => ({ + mime: { [MIME_TYPE]: ["bmp"] }, + + constants: { + MIME_BMP: MIME_TYPE, + MIME_X_MS_BMP: MIME_TYPE_SECOND, + }, + + decoders: { + [MIME_TYPE]: decode, + [MIME_TYPE_SECOND]: decode, + }, + + encoders: { + [MIME_TYPE]: encode, + [MIME_TYPE_SECOND]: encode, + }, +}); diff --git a/node_modules/@jimp/bmp/test/bmp.test.js b/node_modules/@jimp/bmp/test/bmp.test.js new file mode 100644 index 00000000..09587cec --- /dev/null +++ b/node_modules/@jimp/bmp/test/bmp.test.js @@ -0,0 +1,46 @@ +import { Jimp, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import expect from "@storybook/expect"; + +import bmp from "../src"; + +const jimp = configure({ types: [bmp] }, Jimp); + +describe("BMP", () => { + const imagesDir = getTestDir(__dirname) + "/images"; + + it("load BMP", async () => { + const image = await jimp.read(imagesDir + "/windows95.bmp"); + + expect(image.getPixelColor(10, 10)).toBe(0xeff7f7ff); + expect(image.getPixelColor(150, 80)).toBe(0x73add6ff); + expect(image.getPixelColor(190, 200)).toBe(0xf7c300ff); + }); + + it("export BMP", async () => { + const image = await jimp.read({ + width: 3, + height: 3, + data: [ + 0xff0000ff, 0xff0080ff, 0xff00ffff, 0xff0080ff, 0xff00ffff, 0x8000ffff, + 0xff00ffff, 0x8000ffff, 0x0000ffff, + ], + }); + const buffer = await image.getBufferAsync("image/bmp"); + + expect(buffer.toString()).toMatch(/^BMZ\u0000/); + }); + + it("uses correct colors for BMP", async function () { + this.timeout(4000); + + const expectedImg = await jimp.read( + getTestDir(__dirname) + "/images/windows95.png" + ); + const image = await jimp.read( + getTestDir(__dirname) + "/images/windows95.bmp" + ); + + expect(image.bitmap.data).toEqual(expectedImg.bitmap.data); + }); +}); diff --git a/node_modules/@jimp/bmp/test/images/windows95.bmp b/node_modules/@jimp/bmp/test/images/windows95.bmp new file mode 100644 index 00000000..b5f870eb Binary files /dev/null and b/node_modules/@jimp/bmp/test/images/windows95.bmp differ diff --git a/node_modules/@jimp/bmp/test/images/windows95.png b/node_modules/@jimp/bmp/test/images/windows95.png new file mode 100644 index 00000000..95bb0799 Binary files /dev/null and b/node_modules/@jimp/bmp/test/images/windows95.png differ diff --git a/node_modules/@jimp/core/LICENSE b/node_modules/@jimp/core/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/core/README.md b/node_modules/@jimp/core/README.md new file mode 100644 index 00000000..4ca355ff --- /dev/null +++ b/node_modules/@jimp/core/README.md @@ -0,0 +1,52 @@ +
+ +

@jimp/core

+
+ +The main Jimp class. This class can be extended with types and bitmap manipulation functions. Out of the box it does not support any image type. + +## Available Methods + +### Jimp + +The Jimp class constructor. + +### addConstants + +Add constant or static methods to the Jimp constructor. + +```js +addConstants({ + MIME_SPECIAL: "image/special", +}); +``` + +### addJimpMethods + +Add a bitmap manipulation method to Jimp constructor. These method should return this so that the function can be chain-able. + +```js +addJimpMethods({ + cropCrazy: function() { + // Your custom image manipulation method + + return this; + } +}) + +const image = await Jimp.read(...); + +image.resize(10, Jimp.AUTO), + .cropCrazy(); + +await image.writeAsync('test.png'); +``` + +### addType + +Add a image mime type to Jimp constructor. First argument is a mime type and the second is an array of file extension for that type. + +```js +addType("image/special", ["spec", "special"]); +``` diff --git a/node_modules/@jimp/core/es/composite/composite-modes.js b/node_modules/@jimp/core/es/composite/composite-modes.js new file mode 100644 index 00000000..8ab468eb --- /dev/null +++ b/node_modules/@jimp/core/es/composite/composite-modes.js @@ -0,0 +1,209 @@ +export function srcOver(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const r = (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a; + const g = (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a; + const b = (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a; + return { + r, + g, + b, + a + }; +} +export function dstOver(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const r = (dst.r * dst.a + src.r * src.a * (1 - dst.a)) / a; + const g = (dst.g * dst.a + src.g * src.a * (1 - dst.a)) / a; + const b = (dst.b * dst.a + src.b * src.a * (1 - dst.a)) / a; + return { + r, + g, + b, + a + }; +} +export function multiply(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + const g = (sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + const b = (sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r, + g, + b, + a + }; +} +export function add(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (sra + dra) / a; + const g = (sga + dga) / a; + const b = (sba + dba) / a; + return { + r, + g, + b, + a + }; +} +export function screen(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (sra * dst.a + dra * src.a - sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + const g = (sga * dst.a + dga * src.a - sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + const b = (sba * dst.a + dba * src.a - sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r, + g, + b, + a + }; +} +export function overlay(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (2 * dra <= dst.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a; + const g = (2 * dga <= dst.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a; + const b = (2 * dba <= dst.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a; + return { + r, + g, + b, + a + }; +} +export function darken(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (Math.min(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + const g = (Math.min(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + const b = (Math.min(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r, + g, + b, + a + }; +} +export function lighten(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (Math.max(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + const g = (Math.max(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + const b = (Math.max(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r, + g, + b, + a + }; +} +export function hardLight(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (2 * sra <= src.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a; + const g = (2 * sga <= src.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a; + const b = (2 * sba <= src.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a; + return { + r, + g, + b, + a + }; +} +export function difference(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (sra + dra - 2 * Math.min(sra * dst.a, dra * src.a)) / a; + const g = (sga + dga - 2 * Math.min(sga * dst.a, dga * src.a)) / a; + const b = (sba + dba - 2 * Math.min(sba * dst.a, dba * src.a)) / a; + return { + r, + g, + b, + a + }; +} +export function exclusion(src, dst) { + let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + const a = dst.a + src.a - dst.a * src.a; + const sra = src.r * src.a; + const sga = src.g * src.a; + const sba = src.b * src.a; + const dra = dst.r * dst.a; + const dga = dst.g * dst.a; + const dba = dst.b * dst.a; + const r = (sra * dst.a + dra * src.a - 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + const g = (sga * dst.a + dga * src.a - 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + const b = (sba * dst.a + dba * src.a - 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r, + g, + b, + a + }; +} +//# sourceMappingURL=composite-modes.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/composite/composite-modes.js.map b/node_modules/@jimp/core/es/composite/composite-modes.js.map new file mode 100644 index 00000000..89d703c6 --- /dev/null +++ b/node_modules/@jimp/core/es/composite/composite-modes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"composite-modes.js","names":["srcOver","src","dst","ops","a","r","g","b","dstOver","multiply","sra","sga","sba","dra","dga","dba","add","screen","overlay","darken","Math","min","lighten","max","hardLight","difference","exclusion"],"sources":["../../src/composite/composite-modes.js"],"sourcesContent":["export function srcOver(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const r = (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a;\n const g = (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a;\n const b = (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a;\n\n return { r, g, b, a };\n}\n\nexport function dstOver(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const r = (dst.r * dst.a + src.r * src.a * (1 - dst.a)) / a;\n const g = (dst.g * dst.a + src.g * src.a * (1 - dst.a)) / a;\n const b = (dst.b * dst.a + src.b * src.a * (1 - dst.a)) / a;\n\n return { r, g, b, a };\n}\n\nexport function multiply(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r = (sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;\n const g = (sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;\n const b = (sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;\n\n return { r, g, b, a };\n}\n\nexport function add(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r = (sra + dra) / a;\n const g = (sga + dga) / a;\n const b = (sba + dba) / a;\n\n return { r, g, b, a };\n}\n\nexport function screen(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r =\n (sra * dst.a +\n dra * src.a -\n sra * dra +\n sra * (1 - dst.a) +\n dra * (1 - src.a)) /\n a;\n const g =\n (sga * dst.a +\n dga * src.a -\n sga * dga +\n sga * (1 - dst.a) +\n dga * (1 - src.a)) /\n a;\n const b =\n (sba * dst.a +\n dba * src.a -\n sba * dba +\n sba * (1 - dst.a) +\n dba * (1 - src.a)) /\n a;\n\n return { r, g, b, a };\n}\n\nexport function overlay(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r =\n (2 * dra <= dst.a\n ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)\n : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) /\n a;\n\n const g =\n (2 * dga <= dst.a\n ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)\n : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) /\n a;\n\n const b =\n (2 * dba <= dst.a\n ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)\n : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) /\n a;\n\n return { r, g, b, a };\n}\n\nexport function darken(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r =\n (Math.min(sra * dst.a, dra * src.a) +\n sra * (1 - dst.a) +\n dra * (1 - src.a)) /\n a;\n const g =\n (Math.min(sga * dst.a, dga * src.a) +\n sga * (1 - dst.a) +\n dga * (1 - src.a)) /\n a;\n const b =\n (Math.min(sba * dst.a, dba * src.a) +\n sba * (1 - dst.a) +\n dba * (1 - src.a)) /\n a;\n\n return { r, g, b, a };\n}\n\nexport function lighten(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r =\n (Math.max(sra * dst.a, dra * src.a) +\n sra * (1 - dst.a) +\n dra * (1 - src.a)) /\n a;\n const g =\n (Math.max(sga * dst.a, dga * src.a) +\n sga * (1 - dst.a) +\n dga * (1 - src.a)) /\n a;\n const b =\n (Math.max(sba * dst.a, dba * src.a) +\n sba * (1 - dst.a) +\n dba * (1 - src.a)) /\n a;\n\n return { r, g, b, a };\n}\n\nexport function hardLight(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r =\n (2 * sra <= src.a\n ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)\n : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) /\n a;\n\n const g =\n (2 * sga <= src.a\n ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)\n : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) /\n a;\n\n const b =\n (2 * sba <= src.a\n ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)\n : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) /\n a;\n\n return { r, g, b, a };\n}\n\nexport function difference(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r = (sra + dra - 2 * Math.min(sra * dst.a, dra * src.a)) / a;\n const g = (sga + dga - 2 * Math.min(sga * dst.a, dga * src.a)) / a;\n const b = (sba + dba - 2 * Math.min(sba * dst.a, dba * src.a)) / a;\n\n return { r, g, b, a };\n}\n\nexport function exclusion(src, dst, ops = 1) {\n src.a *= ops;\n\n const a = dst.a + src.a - dst.a * src.a;\n\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n\n const r =\n (sra * dst.a +\n dra * src.a -\n 2 * sra * dra +\n sra * (1 - dst.a) +\n dra * (1 - src.a)) /\n a;\n const g =\n (sga * dst.a +\n dga * src.a -\n 2 * sga * dga +\n sga * (1 - dst.a) +\n dga * (1 - src.a)) /\n a;\n const b =\n (sba * dst.a +\n dba * src.a -\n 2 * sba * d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,GAAG,GAAGZ,GAAG,CAACG,CAAC,GACX,CAAC,GAAGM,GAAG,GAAGG,GAAG,GACbH,GAAG,IAAI,CAAC,GAAGR,GAAG,CAACE,CAAC,CAAC,GACjBS,GAAG,IAAI,CAAC,GAAGZ,GAAG,CAACG,CAAC,CAAC,IACnBA,CAAC;EACH,MAAME,CAAC,GACL,CAACK,GAAG,GAAGT,GAAG,CAACE,CAAC,GACVU,GAAG,GAAGb,GAAG,CAACG,CAAC,GACX,CAAC,GAAGO,GAAG,GAAGG,GAAG,GACbH,GAAG,IAAI,CAAC,GAAGT,GAAG,CAACE,CAAC,CAAC,GACjBU,GAAG,IAAI,CAAC,GAAGb,GAAG,CAACG,CAAC,CAAC,IACnBA,CAAC;EACH,MAAMG,CAAC,GACL,CAACK,GAAG,GAAGV,GAAG,CAACE,CAAC,GACVW,GAAG,GAAGd,GAAG,CAACG,CAAC,GACX,CAAC,GAAGQ,GAAG,GAAGG,GAAG,GACbH,GAAG,IAAI,CAAC,GAAGV,GAAG,CAACE,CAAC,CAAC,GACjBW,GAAG,IAAI,CAAC,GAAGd,GAAG,CAACG,CAAC,CAAC,IACnBA,CAAC;EAEH,OAAO;IAAEC,CAAC;IAAEC,CAAC;IAAEC,CAAC;IAAEH;EAAE,CAAC;AACvB"} \ No newline at end of file diff --git a/node_modules/@jimp/core/es/composite/index.js b/node_modules/@jimp/core/es/composite/index.js new file mode 100644 index 00000000..2b4748e0 --- /dev/null +++ b/node_modules/@jimp/core/es/composite/index.js @@ -0,0 +1,79 @@ +import { isNodePattern, throwError } from "@jimp/utils"; +import * as constants from "../constants"; +import * as compositeModes from "./composite-modes"; + +/** + * Composites a source image over to this image respecting alpha channels + * @param {Jimp} src the source Jimp instance + * @param {number} x the x position to blit the image + * @param {number} y the y position to blit the image + * @param {object} options determine what mode to use + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default function composite(src, x, y) { + let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + let cb = arguments.length > 4 ? arguments[4] : undefined; + if (typeof options === "function") { + cb = options; + options = {}; + } + if (!(src instanceof this.constructor)) { + return throwError.call(this, "The source must be a Jimp image", cb); + } + if (typeof x !== "number" || typeof y !== "number") { + return throwError.call(this, "x and y must be numbers", cb); + } + let { + mode, + opacitySource, + opacityDest + } = options; + if (!mode) { + mode = constants.BLEND_SOURCE_OVER; + } + if (typeof opacitySource !== "number" || opacitySource < 0 || opacitySource > 1) { + opacitySource = 1.0; + } + if (typeof opacityDest !== "number" || opacityDest < 0 || opacityDest > 1) { + opacityDest = 1.0; + } + + // eslint-disable-next-line import/namespace + const blendmode = compositeModes[mode]; + + // round input + x = Math.round(x); + y = Math.round(y); + const baseImage = this; + if (opacityDest !== 1.0) { + baseImage.opacity(opacityDest); + } + src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) { + const dstIdx = baseImage.getPixelIndex(x + sx, y + sy, constants.EDGE_CROP); + if (dstIdx === -1) { + // Skip target pixels outside of dst + return; + } + const blended = blendmode({ + r: this.bitmap.data[idx + 0] / 255, + g: this.bitmap.data[idx + 1] / 255, + b: this.bitmap.data[idx + 2] / 255, + a: this.bitmap.data[idx + 3] / 255 + }, { + r: baseImage.bitmap.data[dstIdx + 0] / 255, + g: baseImage.bitmap.data[dstIdx + 1] / 255, + b: baseImage.bitmap.data[dstIdx + 2] / 255, + a: baseImage.bitmap.data[dstIdx + 3] / 255 + }, opacitySource); + baseImage.bitmap.data[dstIdx + 0] = this.constructor.limit255(blended.r * 255); + baseImage.bitmap.data[dstIdx + 1] = this.constructor.limit255(blended.g * 255); + baseImage.bitmap.data[dstIdx + 2] = this.constructor.limit255(blended.b * 255); + baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(blended.a * 255); + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/composite/index.js.map b/node_modules/@jimp/core/es/composite/index.js.map new file mode 100644 index 00000000..3629f6f1 --- /dev/null +++ b/node_modules/@jimp/core/es/composite/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","constants","compositeModes","composite","src","x","y","options","cb","constructor","call","mode","opacitySource","opacityDest","BLEND_SOURCE_OVER","blendmode","Math","round","baseImage","opacity","scanQuiet","bitmap","width","height","sx","sy","idx","dstIdx","getPixelIndex","EDGE_CROP","blended","r","data","g","b","a","limit255"],"sources":["../../src/composite/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\nimport * as constants from \"../constants\";\n\nimport * as compositeModes from \"./composite-modes\";\n\n/**\n * Composites a source image over to this image respecting alpha channels\n * @param {Jimp} src the source Jimp instance\n * @param {number} x the x position to blit the image\n * @param {number} y the y position to blit the image\n * @param {object} options determine what mode to use\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default function composite(src, x, y, options = {}, cb) {\n if (typeof options === \"function\") {\n cb = options;\n options = {};\n }\n\n if (!(src instanceof this.constructor)) {\n return throwError.call(this, \"The source must be a Jimp image\", cb);\n }\n\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n\n let { mode, opacitySource, opacityDest } = options;\n\n if (!mode) {\n mode = constants.BLEND_SOURCE_OVER;\n }\n\n if (\n typeof opacitySource !== \"number\" ||\n opacitySource < 0 ||\n opacitySource > 1\n ) {\n opacitySource = 1.0;\n }\n\n if (typeof opacityDest !== \"number\" || opacityDest < 0 || opacityDest > 1) {\n opacityDest = 1.0;\n }\n\n // eslint-disable-next-line import/namespace\n const blendmode = compositeModes[mode];\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n\n const baseImage = this;\n\n if (opacityDest !== 1.0) {\n baseImage.opacity(opacityDest);\n }\n\n src.scanQuiet(\n 0,\n 0,\n src.bitmap.width,\n src.bitmap.height,\n function (sx, sy, idx) {\n const dstIdx = baseImage.getPixelIndex(\n x + sx,\n y + sy,\n constants.EDGE_CROP\n );\n\n if (dstIdx === -1) {\n // Skip target pixels outside of dst\n return;\n }\n\n const blended = blendmode(\n {\n r: this.bitmap.data[idx + 0] / 255,\n g: this.bitmap.data[idx + 1] / 255,\n b: this.bitmap.data[idx + 2] / 255,\n a: this.bitmap.data[idx + 3] / 255,\n },\n {\n r: baseImage.bitmap.data[dstIdx + 0] / 255,\n g: baseImage.bitmap.data[dstIdx + 1] / 255,\n b: baseImage.bitmap.data[dstIdx + 2] / 255,\n a: baseImage.bitmap.data[dstIdx + 3] / 255,\n },\n opacitySource\n );\n\n baseImage.bitmap.data[dstIdx + 0] = this.constructor.limit255(\n blended.r * 255\n );\n baseImage.bitmap.data[dstIdx + 1] = this.constructor.limit255(\n blended.g * 255\n );\n baseImage.bitmap.data[dstIdx + 2] = this.constructor.limit255(\n blended.b * 255\n );\n baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(\n blended.a * 255\n );\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n}\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;AACvD,OAAO,KAAKC,SAAS,MAAM,cAAc;AAEzC,OAAO,KAAKC,cAAc,MAAM,mBAAmB;;AAEnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,SAAS,CAACC,GAAG,EAAEC,CAAC,EAAEC,CAAC,EAAoB;EAAA,IAAlBC,OAAO,uEAAG,CAAC,CAAC;EAAA,IAAEC,EAAE;EAC3D,IAAI,OAAOD,OAAO,KAAK,UAAU,EAAE;IACjCC,EAAE,GAAGD,OAAO;IACZA,OAAO,GAAG,CAAC,CAAC;EACd;EAEA,IAAI,EAAEH,GAAG,YAAY,IAAI,CAACK,WAAW,CAAC,EAAE;IACtC,OAAOT,UAAU,CAACU,IAAI,CAAC,IAAI,EAAE,iCAAiC,EA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C2B,QAAQ,CAC3DN,OAAO,CAACI,CAAC,GAAG,GAAG,CAChB;IACDhB,SAAS,CAACG,MAAM,CAACW,IAAI,CAACL,MAAM,GAAG,CAAC,CAAC,GAAG,IAAI,CAAClB,WAAW,CAAC2B,QAAQ,CAC3DN,OAAO,CAACK,CAAC,GAAG,GAAG,CAChB;EACH,CAAC,CACF;EAED,IAAIpC,aAAa,CAACS,EAAE,CAAC,EAAE;IACrBA,EAAE,CAACE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;EAC3B;EAEA,OAAO,IAAI;AACb"} \ No newline at end of file diff --git a/node_modules/@jimp/core/es/constants.js b/node_modules/@jimp/core/es/constants.js new file mode 100644 index 00000000..0fd9babf --- /dev/null +++ b/node_modules/@jimp/core/es/constants.js @@ -0,0 +1,29 @@ +// used to auto resizing etc. +export const AUTO = -1; + +// Align modes for cover, contain, bit masks +export const HORIZONTAL_ALIGN_LEFT = 1; +export const HORIZONTAL_ALIGN_CENTER = 2; +export const HORIZONTAL_ALIGN_RIGHT = 4; +export const VERTICAL_ALIGN_TOP = 8; +export const VERTICAL_ALIGN_MIDDLE = 16; +export const VERTICAL_ALIGN_BOTTOM = 32; + +// blend modes +export const BLEND_SOURCE_OVER = "srcOver"; +export const BLEND_DESTINATION_OVER = "dstOver"; +export const BLEND_MULTIPLY = "multiply"; +export const BLEND_ADD = "add"; +export const BLEND_SCREEN = "screen"; +export const BLEND_OVERLAY = "overlay"; +export const BLEND_DARKEN = "darken"; +export const BLEND_LIGHTEN = "lighten"; +export const BLEND_HARDLIGHT = "hardLight"; +export const BLEND_DIFFERENCE = "difference"; +export const BLEND_EXCLUSION = "exclusion"; + +// Edge Handling +export const EDGE_EXTEND = 1; +export const EDGE_WRAP = 2; +export const EDGE_CROP = 3; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/constants.js.map b/node_modules/@jimp/core/es/constants.js.map new file mode 100644 index 00000000..c3f0c2f7 --- /dev/null +++ b/node_modules/@jimp/core/es/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","names":["AUTO","HORIZONTAL_ALIGN_LEFT","HORIZONTAL_ALIGN_CENTER","HORIZONTAL_ALIGN_RIGHT","VERTICAL_ALIGN_TOP","VERTICAL_ALIGN_MIDDLE","VERTICAL_ALIGN_BOTTOM","BLEND_SOURCE_OVER","BLEND_DESTINATION_OVER","BLEND_MULTIPLY","BLEND_ADD","BLEND_SCREEN","BLEND_OVERLAY","BLEND_DARKEN","BLEND_LIGHTEN","BLEND_HARDLIGHT","BLEND_DIFFERENCE","BLEND_EXCLUSION","EDGE_EXTEND","EDGE_WRAP","EDGE_CROP"],"sources":["../src/constants.js"],"sourcesContent":["// used to auto resizing etc.\nexport const AUTO = -1;\n\n// Align modes for cover, contain, bit masks\nexport const HORIZONTAL_ALIGN_LEFT = 1;\nexport const HORIZONTAL_ALIGN_CENTER = 2;\nexport const HORIZONTAL_ALIGN_RIGHT = 4;\n\nexport const VERTICAL_ALIGN_TOP = 8;\nexport const VERTICAL_ALIGN_MIDDLE = 16;\nexport const VERTICAL_ALIGN_BOTTOM = 32;\n\n// blend modes\nexport const BLEND_SOURCE_OVER = \"srcOver\";\nexport const BLEND_DESTINATION_OVER = \"dstOver\";\nexport const BLEND_MULTIPLY = \"multiply\";\nexport const BLEND_ADD = \"add\";\nexport const BLEND_SCREEN = \"screen\";\nexport const BLEND_OVERLAY = \"overlay\";\nexport const BLEND_DARKEN = \"darken\";\nexport const BLEND_LIGHTEN = \"lighten\";\nexport const BLEND_HARDLIGHT = \"hardLight\";\nexport const BLEND_DIFFERENCE = \"difference\";\nexport const BLEND_EXCLUSION = \"exclusion\";\n\n// Edge Handling\nexport const EDGE_EXTEND = 1;\nexport const EDGE_WRAP = 2;\nexport const EDGE_CROP = 3;\n"],"mappings":"AAAA;AACA,OAAO,MAAMA,IAAI,GAAG,CAAC,CAAC;;AAEtB;AACA,OAAO,MAAMC,qBAAqB,GAAG,CAAC;AACtC,OAAO,MAAMC,uBAAuB,GAAG,CAAC;AACxC,OAAO,MAAMC,sBAAsB,GAAG,CAAC;AAEvC,OAAO,MAAMC,kBAAkB,GAAG,CAAC;AACnC,OAAO,MAAMC,qBAAqB,GAAG,EAAE;AACvC,OAAO,MAAMC,qBAAqB,GAAG,EAAE;;AAEvC;AACA,OAAO,MAAMC,iBAAiB,GAAG,SAAS;AAC1C,OAAO,MAAMC,sBAAsB,GAAG,SAAS;AAC/C,OAAO,MAAMC,cAAc,GAAG,UAAU;AACxC,OAAO,MAAMC,SAAS,GAAG,KAAK;AAC9B,OAAO,MAAMC,YAAY,GAAG,QAAQ;AACpC,OAAO,MAAMC,aAAa,GAAG,SAAS;AACtC,OAAO,MAAMC,YAAY,GAAG,QAAQ;AACpC,OAAO,MAAMC,aAAa,GAAG,SAAS;AACtC,OAAO,MAAMC,eAAe,GAAG,WAAW;AAC1C,OAAO,MAAMC,gBAAgB,GAAG,YAAY;AAC5C,OAAO,MAAMC,eAAe,GAAG,WAAW;;AAE1C;AACA,OAAO,MAAMC,WAAW,GAAG,CAAC;AAC5B,OAAO,MAAMC,SAAS,GAAG,CAAC;AAC1B,OAAO,MAAMC,SAAS,GAAG,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/core/es/index.js b/node_modules/@jimp/core/es/index.js new file mode 100644 index 00000000..cb4569db --- /dev/null +++ b/node_modules/@jimp/core/es/index.js @@ -0,0 +1,1027 @@ +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +import fs from "fs"; +import Path from "path"; +import EventEmitter from "events"; +import { isNodePattern, throwError, scan, scanIterator } from "@jimp/utils"; +import anyBase from "any-base"; +import pixelMatch from "pixelmatch"; +import tinyColor from "tinycolor2"; +import ImagePHash from "./modules/phash"; +import request from "./request"; +import composite from "./composite"; +import promisify from "./utils/promisify"; +import * as MIME from "./utils/mime"; +import { parseBitmap, getBuffer, getBufferAsync } from "./utils/image-bitmap"; +import * as constants from "./constants"; +const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_"; + +// an array storing the maximum string length of hashes at various bases +// 0 and 1 do not exist as possible hash lengths +const maxHashLength = [NaN, NaN]; +for (let i = 2; i < 65; i++) { + const maxHash = anyBase(anyBase.BIN, alphabet.slice(0, i))(new Array(64 + 1).join("1")); + maxHashLength.push(maxHash.length); +} + +// no operation +function noop() {} + +// error checking methods + +function isArrayBuffer(test) { + return Object.prototype.toString.call(test).toLowerCase().indexOf("arraybuffer") > -1; +} + +// Prepare a Buffer object from the arrayBuffer. Necessary in the browser > node conversion, +// But this function is not useful when running in node directly +function bufferFromArrayBuffer(arrayBuffer) { + const buffer = Buffer.alloc(arrayBuffer.byteLength); + const view = new Uint8Array(arrayBuffer); + for (let i = 0; i < buffer.length; ++i) { + buffer[i] = view[i]; + } + return buffer; +} +function loadFromURL(options, cb) { + request(options, (err, data) => { + if (err) { + return cb(err); + } + if (typeof data === "object" && Buffer.isBuffer(data)) { + return cb(null, data); + } + if (typeof data === "object" && isArrayBuffer(data)) { + return cb(null, bufferFromArrayBuffer(data)); + } + return new Error(`Could not load Buffer from <${options.url}>`); + }); +} +function loadBufferFromPath(src, cb) { + if (fs && typeof fs.readFile === "function" && !src.match(/^(http|ftp)s?:\/\/./)) { + fs.readFile(src, cb); + } else { + loadFromURL({ + url: src + }, cb); + } +} +function isRawRGBAData(obj) { + return obj && typeof obj === "object" && typeof obj.width === "number" && typeof obj.height === "number" && (Buffer.isBuffer(obj.data) || obj.data instanceof Uint8Array || typeof Uint8ClampedArray === "function" && obj.data instanceof Uint8ClampedArray) && (obj.data.length === obj.width * obj.height * 4 || obj.data.length === obj.width * obj.height * 3); +} +function makeRGBABufferFromRGB(buffer) { + if (buffer.length % 3 !== 0) { + throw new Error("Buffer length is incorrect"); + } + const rgbaBuffer = Buffer.allocUnsafe(buffer.length / 3 * 4); + let j = 0; + for (let i = 0; i < buffer.length; i++) { + rgbaBuffer[j] = buffer[i]; + if ((i + 1) % 3 === 0) { + rgbaBuffer[++j] = 255; + } + j++; + } + return rgbaBuffer; +} +const emptyBitmap = { + data: null, + width: null, + height: null +}; + +/** + * Jimp constructor (from a file) + * @param path a path to the image + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap + */ + +/** + * Jimp constructor (from a url with options) + * @param options { url, otherOptions} + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap + */ + +/** + * Jimp constructor (from another Jimp image or raw image data) + * @param image a Jimp image to clone + * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap + */ + +/** + * Jimp constructor (from a Buffer) + * @param data a Buffer containing the image data + * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap + */ + +/** + * Jimp constructor (to generate a new image) + * @param w the width of the image + * @param h the height of the image + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap + */ + +/** + * Jimp constructor (to generate a new image) + * @param w the width of the image + * @param h the height of the image + * @param background color to fill the image with + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap + */ + +class Jimp extends EventEmitter { + // An object representing a bitmap in memory, comprising: + // - data: a buffer of the bitmap data + // - width: the width of the image in pixels + // - height: the height of the image in pixels + + // Default colour to use for new pixels + + // Default MIME is PNG + + // Exif data for the image + + // Whether Transparency supporting formats will be exported as RGB or RGBA + + constructor() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + super(); + _defineProperty(this, "bitmap", emptyBitmap); + _defineProperty(this, "_background", 0x00000000); + _defineProperty(this, "_originalMime", Jimp.MIME_PNG); + _defineProperty(this, "_exif", null); + _defineProperty(this, "_rgba", true); + _defineProperty(this, "writeAsync", path => promisify(this.write, this, path)); + _defineProperty(this, "getBase64Async", mime => promisify(this.getBase64, this, mime)); + _defineProperty(this, "getBuffer", getBuffer); + _defineProperty(this, "getBufferAsync", getBufferAsync); + _defineProperty(this, "getPixelColour", this.getPixelColor); + _defineProperty(this, "setPixelColour", this.setPixelColor); + const jimpInstance = this; + let cb = noop; + if (isArrayBuffer(args[0])) { + args[0] = bufferFromArrayBuffer(args[0]); + } + function finish() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + const [err] = args; + const evData = err || {}; + evData.methodName = "constructor"; + setTimeout(() => { + // run on next tick. + if (err && cb === noop) { + jimpInstance.emitError("constructor", err); + } else if (!err) { + jimpInstance.emitMulti("constructor", "initialized"); + } + cb.call(jimpInstance, ...args); + }, 1); + } + if (typeof args[0] === "number" && typeof args[1] === "number" || parseInt(args[0], 10) && parseInt(args[1], 10)) { + // create a new image + const w = parseInt(args[0], 10); + const h = parseInt(args[1], 10); + cb = args[2]; + + // with a hex color + if (typeof args[2] === "number") { + this._background = args[2]; + cb = args[3]; + } + + // with a css color + if (typeof args[2] === "string") { + this._background = Jimp.cssColorToHex(args[2]); + cb = args[3]; + } + if (typeof cb === "undefined") { + cb = noop; + } + if (typeof cb !== "function") { + return throwError.call(this, "cb must be a function", finish); + } + this.bitmap = { + data: Buffer.alloc(w * h * 4), + width: w, + height: h + }; + for (let i = 0; i < this.bitmap.data.length; i += 4) { + this.bitmap.data.writeUInt32BE(this._background, i); + } + finish(null, this); + } else if (typeof args[0] === "object" && args[0].url) { + cb = args[1] || noop; + if (typeof cb !== "function") { + return throwError.call(this, "cb must be a function", finish); + } + loadFromURL(args[0], (err, data) => { + if (err) { + return throwError.call(this, err, finish); + } + this.parseBitmap(data, args[0].url, finish); + }); + } else if (args[0] instanceof Jimp) { + // clone an existing Jimp + const [original] = args; + cb = args[1]; + if (typeof cb === "undefined") { + cb = noop; + } + if (typeof cb !== "function") { + return throwError.call(this, "cb must be a function", finish); + } + this.bitmap = { + data: Buffer.from(original.bitmap.data), + width: original.bitmap.width, + height: original.bitmap.height + }; + this._quality = original._quality; + this._deflateLevel = original._deflateLevel; + this._deflateStrategy = original._deflateStrategy; + this._filterType = original._filterType; + this._rgba = original._rgba; + this._background = original._background; + this._originalMime = original._originalMime; + finish(null, this); + } else if (isRawRGBAData(args[0])) { + const [imageData] = args; + cb = args[1] || noop; + const isRGBA = imageData.width * imageData.height * 4 === imageData.data.length; + const buffer = isRGBA ? Buffer.from(imageData.data) : makeRGBABufferFromRGB(imageData.data); + this.bitmap = { + data: buffer, + width: imageData.width, + height: imageData.height + }; + finish(null, this); + } else if (typeof args[0] === "string") { + // read from a path + const path = args[0]; + cb = args[1]; + if (typeof cb === "undefined") { + cb = noop; + } + if (typeof cb !== "function") { + return throwError.call(this, "cb must be a function", finish); + } + loadBufferFromPath(path, (err, data) => { + if (err) { + return throwError.call(this, err, finish); + } + this.parseBitmap(data, path, finish); + }); + } else if (typeof args[0] === "object" && Buffer.isBuffer(args[0])) { + // read from a buffer + const data = args[0]; + cb = args[1]; + if (typeof cb !== "function") { + return throwError.call(this, "cb must be a function", finish); + } + this.parseBitmap(data, null, finish); + } else { + // Allow client libs to add new ways to build a Jimp object. + // Extra constructors must be added by `Jimp.appendConstructorOption()` + cb = args[args.length - 1]; + if (typeof cb !== "function") { + // TODO: try to solve the args after cb problem. + cb = args[args.length - 2]; + if (typeof cb !== "function") { + cb = noop; + } + } + const extraConstructor = Jimp.__extraConstructors.find(c => c.test(...args)); + if (extraConstructor) { + new Promise((resolve, reject) => { + extraConstructor.run.call(this, resolve, reject, ...args); + }).then(() => finish(null, this)).catch(finish); + } else { + return throwError.call(this, "No matching constructor overloading was found. " + "Please see the docs for how to call the Jimp constructor.", finish); + } + } + } + + /** + * Parse a bitmap with the loaded image types. + * + * @param {Buffer} data raw image data + * @param {string} path optional path to file + * @param {function(Error, Jimp)} finish (optional) a callback for when complete + * @memberof Jimp + */ + parseBitmap(data, path, finish) { + parseBitmap.call(this, data, null, finish); + } + + /** + * Sets the type of the image (RGB or RGBA) when saving in a format that supports transparency (default is RGBA) + * @param {boolean} bool A Boolean, true to use RGBA or false to use RGB + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + rgba(bool, cb) { + if (typeof bool !== "boolean") { + return throwError.call(this, "bool must be a boolean, true for RGBA or false for RGB", cb); + } + this._rgba = bool; + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } + + /** + * Emit for multiple listeners + * @param {string} methodName name of the method to emit an error for + * @param {string} eventName name of the eventName to emit an error for + * @param {object} data to emit + */ + emitMulti(methodName, eventName) { + let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + data = Object.assign(data, { + methodName, + eventName + }); + this.emit("any", data); + if (methodName) { + this.emit(methodName, data); + } + this.emit(eventName, data); + } + emitError(methodName, err) { + this.emitMulti(methodName, "error", err); + } + + /** + * Get the current height of the image + * @return {number} height of the image + */ + getHeight() { + return this.bitmap.height; + } + + /** + * Get the current width of the image + * @return {number} width of the image + */ + getWidth() { + return this.bitmap.width; + } + + /** + * Nicely format Jimp object when sent to the console e.g. console.log(image) + * @returns {string} pretty printed + */ + inspect() { + return ""; + } + + /** + * Nicely format Jimp object when converted to a string + * @returns {string} pretty printed + */ + toString() { + return "[object Jimp]"; + } + + /** + * Returns the original MIME of the image (default: "image/png") + * @returns {string} the MIME + */ + getMIME() { + const mime = this._originalMime || Jimp.MIME_PNG; + return mime; + } + + /** + * Returns the appropriate file extension for the original MIME of the image (default: "png") + * @returns {string} the file extension + */ + getExtension() { + const mime = this.getMIME(); + return MIME.getExtension(mime); + } + + /** + * Writes the image to a file + * @param {string} path a path to the destination file + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is saved to disk + * @returns {Jimp} this for chaining of methods + */ + write(path, cb) { + if (!fs || !fs.createWriteStream) { + throw new Error("Cant access the filesystem. You can use the getBase64 method."); + } + if (typeof path !== "string") { + return throwError.call(this, "path must be a string", cb); + } + if (typeof cb === "undefined") { + cb = noop; + } + if (typeof cb !== "function") { + return throwError.call(this, "cb must be a function", cb); + } + const mime = MIME.getType(path) || this.getMIME(); + const pathObj = Path.parse(path); + if (pathObj.dir) { + fs.mkdirSync(pathObj.dir, { + recursive: true + }); + } + this.getBuffer(mime, (err, buffer) => { + if (err) { + return throwError.call(this, err, cb); + } + const stream = fs.createWriteStream(path); + stream.on("open", () => { + stream.write(buffer); + stream.end(); + }).on("error", err => { + return throwError.call(this, err, cb); + }); + stream.on("finish", () => { + cb.call(this, null, this); + }); + }); + return this; + } + /** + * Converts the image to a base 64 string + * @param {string} mime the mime type of the image data to be created + * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument + * @returns {Jimp} this for chaining of methods + */ + getBase64(mime, cb) { + if (mime === Jimp.AUTO) { + // allow auto MIME detection + mime = this.getMIME(); + } + if (typeof mime !== "string") { + return throwError.call(this, "mime must be a string", cb); + } + if (typeof cb !== "function") { + return throwError.call(this, "cb must be a function", cb); + } + this.getBuffer(mime, function (err, data) { + if (err) { + return throwError.call(this, err, cb); + } + const src = "data:" + mime + ";base64," + data.toString("base64"); + cb.call(this, null, src); + }); + return this; + } + /** + * Generates a perceptual hash of the image . And pads the string. Can configure base. + * @param {number} base (optional) a number between 2 and 64 representing the base for the hash (e.g. 2 is binary, 10 is decimal, 16 is hex, 64 is base 64). Defaults to 64. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {string} a string representing the hash + */ + hash(base, cb) { + base = base || 64; + if (typeof base === "function") { + cb = base; + base = 64; + } + if (typeof base !== "number") { + return throwError.call(this, "base must be a number", cb); + } + if (base < 2 || base > 64) { + return throwError.call(this, "base must be a number between 2 and 64", cb); + } + let hash = this.pHash(); + hash = anyBase(anyBase.BIN, alphabet.slice(0, base))(hash); + while (hash.length < maxHashLength[base]) { + hash = "0" + hash; // pad out with leading zeros + } + + if (isNodePattern(cb)) { + cb.call(this, null, hash); + } + return hash; + } + + /** + * Calculates the perceptual hash + * @returns {number} the perceptual hash + */ + pHash() { + const pHash = new ImagePHash(); + return pHash.getHash(this); + } + + /** + * Calculates the hamming distance of the current image and a hash based on their perceptual hash + * @param {hash} compareHash hash to compare to + * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical + */ + distanceFromHash(compareHash) { + const pHash = new ImagePHash(); + const currentHash = pHash.getHash(this); + return pHash.distance(currentHash, compareHash); + } + + /** + * Converts the image to a buffer + * @param {string} mime the mime type of the image buffer to be created + * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument + * @returns {Jimp} this for chaining of methods + */ + + /** + * Returns the offset of a pixel in the bitmap buffer + * @param {number} x the x coordinate + * @param {number} y the y coordinate + * @param {number} edgeHandling (optional) define how to sum pixels from outside the border + * @param {number} cb (optional) a callback for when complete + * @returns {number} the index of the pixel or -1 if not found + */ + getPixelIndex(x, y, edgeHandling, cb) { + let xi; + let yi; + if (typeof edgeHandling === "function" && typeof cb === "undefined") { + cb = edgeHandling; + edgeHandling = null; + } + if (!edgeHandling) { + edgeHandling = Jimp.EDGE_EXTEND; + } + if (typeof x !== "number" || typeof y !== "number") { + return throwError.call(this, "x and y must be numbers", cb); + } + + // round input + x = Math.round(x); + y = Math.round(y); + xi = x; + yi = y; + if (edgeHandling === Jimp.EDGE_EXTEND) { + if (x < 0) xi = 0; + if (x >= this.bitmap.width) xi = this.bitmap.width - 1; + if (y < 0) yi = 0; + if (y >= this.bitmap.height) yi = this.bitmap.height - 1; + } + if (edgeHandling === Jimp.EDGE_WRAP) { + if (x < 0) { + xi = this.bitmap.width + x; + } + if (x >= this.bitmap.width) { + xi = x % this.bitmap.width; + } + if (y < 0) { + yi = this.bitmap.height + y; + } + if (y >= this.bitmap.height) { + yi = y % this.bitmap.height; + } + } + let i = this.bitmap.width * yi + xi << 2; + + // if out of bounds index is -1 + if (xi < 0 || xi >= this.bitmap.width) { + i = -1; + } + if (yi < 0 || yi >= this.bitmap.height) { + i = -1; + } + if (isNodePattern(cb)) { + cb.call(this, null, i); + } + return i; + } + + /** + * Returns the hex colour value of a pixel + * @param {number} x the x coordinate + * @param {number} y the y coordinate + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {number} the color of the pixel + */ + getPixelColor(x, y, cb) { + if (typeof x !== "number" || typeof y !== "number") return throwError.call(this, "x and y must be numbers", cb); + const idx = this.getPixelIndex(x, y); + const hex = this.bitmap.data.readUInt32BE(idx); + if (isNodePattern(cb)) { + cb.call(this, null, hex); + } + return hex; + } + /** + * Returns the hex colour value of a pixel + * @param {number} hex color to set + * @param {number} x the x coordinate + * @param {number} y the y coordinate + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {number} the index of the pixel or -1 if not found + */ + setPixelColor(hex, x, y, cb) { + if (typeof hex !== "number" || typeof x !== "number" || typeof y !== "number") return throwError.call(this, "hex, x and y must be numbers", cb); + const idx = this.getPixelIndex(x, y); + this.bitmap.data.writeUInt32BE(hex, idx); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } + /** + * Determine if the image contains opaque pixels. + * @return {boolean} hasAlpha whether the image contains opaque pixels + */ + hasAlpha() { + const { + width, + height, + data + } = this.bitmap; + const byteLen = width * height << 2; + for (let idx = 3; idx < byteLen; idx += 4) { + if (data[idx] !== 0xff) { + return true; + } + } + return false; + } + + /** + * Iterate scan through a region of the bitmap + * @param {number} x the x coordinate to begin the scan at + * @param {number} y the y coordinate to begin the scan at + * @param w the width of the scan region + * @param h the height of the scan region + * @returns {IterableIterator<{x: number, y: number, idx: number, image: Jimp}>} + */ + scanIterator(x, y, w, h) { + if (typeof x !== "number" || typeof y !== "number") { + return throwError.call(this, "x and y must be numbers"); + } + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers"); + } + return scanIterator(this, x, y, w, h); + } +} +export function addConstants(constants) { + let jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp; + Object.entries(constants).forEach(_ref => { + let [name, value] = _ref; + jimpInstance[name] = value; + }); +} +export function addJimpMethods(methods) { + let jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp; + Object.entries(methods).forEach(_ref2 => { + let [name, value] = _ref2; + jimpInstance.prototype[name] = value; + }); +} +addConstants(constants); +addJimpMethods({ + composite +}); +Jimp.__extraConstructors = []; + +/** + * Allow client libs to add new ways to build a Jimp object. + * @param {string} name identify the extra constructor. + * @param {function} test a function that returns true when it accepts the arguments passed to the main constructor. + * @param {function} run where the magic happens. + */ +Jimp.appendConstructorOption = function (name, test, run) { + Jimp.__extraConstructors.push({ + name, + test, + run + }); +}; + +/** + * Read an image from a file or a Buffer. Takes the same args as the constructor + * @returns {Promise} a promise + */ +Jimp.read = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + return new Promise((resolve, reject) => { + // eslint-disable-next-line no-new + new Jimp(...args, (err, image) => { + if (err) reject(err);else resolve(image); + }); + }); +}; +Jimp.create = Jimp.read; + +/** + * A static helper method that converts RGBA values to a single integer value + * @param {number} r the red value (0-255) + * @param {number} g the green value (0-255) + * @param {number} b the blue value (0-255) + * @param {number} a the alpha value (0-255) + * @param {function(Error, Jimp)} cb (optional) A callback for when complete + * @returns {number} an single integer colour value + */ +Jimp.rgbaToInt = function (r, g, b, a, cb) { + if (typeof r !== "number" || typeof g !== "number" || typeof b !== "number" || typeof a !== "number") { + return throwError.call(this, "r, g, b and a must be numbers", cb); + } + if (r < 0 || r > 255) { + return throwError.call(this, "r must be between 0 and 255", cb); + } + if (g < 0 || g > 255) { + throwError.call(this, "g must be between 0 and 255", cb); + } + if (b < 0 || b > 255) { + return throwError.call(this, "b must be between 0 and 255", cb); + } + if (a < 0 || a > 255) { + return throwError.call(this, "a must be between 0 and 255", cb); + } + let i = r & 0xff; + i <<= 8; + i |= g & 0xff; + i <<= 8; + i |= b & 0xff; + i <<= 8; + i |= a & 0xff; + + // Ensure sign is correct + i >>>= 0; + if (isNodePattern(cb)) { + cb.call(this, null, i); + } + return i; +}; + +/** + * A static helper method that converts RGBA values to a single integer value + * @param {number} i a single integer value representing an RGBA colour (e.g. 0xFF0000FF for red) + * @param {function(Error, Jimp)} cb (optional) A callback for when complete + * @returns {object} an object with the properties r, g, b and a representing RGBA values + */ +Jimp.intToRGBA = function (i, cb) { + if (typeof i !== "number") { + return throwError.call(this, "i must be a number", cb); + } + const rgba = {}; + rgba.r = Math.floor(i / Math.pow(256, 3)); + rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2)); + rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1)); + rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0)); + if (isNodePattern(cb)) { + cb.call(this, null, rgba); + } + return rgba; +}; + +/** + * Converts a css color (Hex, 8-digit (RGBA) Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to a hex number + * @param {string} cssColor a number + * @returns {number} a hex number representing a color + */ +Jimp.cssColorToHex = function (cssColor) { + cssColor = cssColor || 0; // 0, null, undefined, NaN + + if (typeof cssColor === "number") return Number(cssColor); + return parseInt(tinyColor(cssColor).toHex8(), 16); +}; + +/** + * Limits a number to between 0 or 255 + * @param {number} n a number + * @returns {number} the number limited to between 0 or 255 + */ +Jimp.limit255 = function (n) { + n = Math.max(n, 0); + n = Math.min(n, 255); + return n; +}; + +/** + * Diffs two images and returns + * @param {Jimp} img1 a Jimp image to compare + * @param {Jimp} img2 a Jimp image to compare + * @param {number} threshold (optional) a number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1) + * @returns {object} an object { percent: percent similar, diff: a Jimp image highlighting differences } + */ +Jimp.diff = function (img1, img2) { + let threshold = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.1; + if (!(img1 instanceof Jimp) || !(img2 instanceof Jimp)) return throwError.call(this, "img1 and img2 must be an Jimp images"); + const bmp1 = img1.bitmap; + const bmp2 = img2.bitmap; + if (bmp1.width !== bmp2.width || bmp1.height !== bmp2.height) { + if (bmp1.width * bmp1.height > bmp2.width * bmp2.height) { + // img1 is bigger + img1 = img1.cloneQuiet().resize(bmp2.width, bmp2.height); + } else { + // img2 is bigger (or they are the same in area) + img2 = img2.cloneQuiet().resize(bmp1.width, bmp1.height); + } + } + if (typeof threshold !== "number" || threshold < 0 || threshold > 1) { + return throwError.call(this, "threshold must be a number between 0 and 1"); + } + const diff = new Jimp(bmp1.width, bmp1.height, 0xffffffff); + const numDiffPixels = pixelMatch(bmp1.data, bmp2.data, diff.bitmap.data, diff.bitmap.width, diff.bitmap.height, { + threshold + }); + return { + percent: numDiffPixels / (diff.bitmap.width * diff.bitmap.height), + image: diff + }; +}; + +/** + * Calculates the hamming distance of two images based on their perceptual hash + * @param {Jimp} img1 a Jimp image to compare + * @param {Jimp} img2 a Jimp image to compare + * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical + */ +Jimp.distance = function (img1, img2) { + const phash = new ImagePHash(); + const hash1 = phash.getHash(img1); + const hash2 = phash.getHash(img2); + return phash.distance(hash1, hash2); +}; + +/** + * Calculates the hamming distance of two images based on their perceptual hash + * @param {hash} hash1 a pHash + * @param {hash} hash2 a pHash + * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical + */ +Jimp.compareHashes = function (hash1, hash2) { + const phash = new ImagePHash(); + return phash.distance(hash1, hash2); +}; + +/** + * Compute color difference + * 0 means no difference, 1 means maximum difference. + * @param {number} rgba1: first color to compare. + * @param {number} rgba2: second color to compare. + * Both parameters must be an color object {r:val, g:val, b:val, a:val} + * Where `a` is optional and `val` is an integer between 0 and 255. + * @returns {number} float between 0 and 1. + */ +Jimp.colorDiff = function (rgba1, rgba2) { + const pow = n => Math.pow(n, 2); + const { + max + } = Math; + const maxVal = 255 * 255 * 3; + if (rgba1.a !== 0 && !rgba1.a) { + rgba1.a = 255; + } + if (rgba2.a !== 0 && !rgba2.a) { + rgba2.a = 255; + } + return (max(pow(rgba1.r - rgba2.r), pow(rgba1.r - rgba2.r - rgba1.a + rgba2.a)) + max(pow(rgba1.g - rgba2.g), pow(rgba1.g - rgba2.g - rgba1.a + rgba2.a)) + max(pow(rgba1.b - rgba2.b), pow(rgba1.b - rgba2.b - rgba1.a + rgba2.a))) / maxVal; +}; + +/** + * Helper to create Jimp methods that emit events before and after its execution. + * @param {string} methodName The name to be appended to Jimp prototype. + * @param {string} evName The event name to be called. + * It will be prefixed by `before-` and emitted when on method call. + * It will be appended by `ed` and emitted after the method run. + * @param {function} method A function implementing the method itself. + * It will also create a quiet version that will not emit events, to not + * mess the user code with many `changed` event calls. You can call with + * `methodName + "Quiet"`. + * + * The emitted event comes with a object parameter to the listener with the + * `methodName` as one attribute. + */ +export function jimpEvMethod(methodName, evName, method) { + const evNameBefore = "before-" + evName; + const evNameAfter = evName.replace(/e$/, "") + "ed"; + Jimp.prototype[methodName] = function () { + let wrappedCb; + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + const cb = args[method.length - 1]; + const jimpInstance = this; + if (typeof cb === "function") { + wrappedCb = function () { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + const [err, data] = args; + if (err) { + jimpInstance.emitError(methodName, err); + } else { + jimpInstance.emitMulti(methodName, evNameAfter, { + [methodName]: data + }); + } + cb.apply(this, args); + }; + args[args.length - 1] = wrappedCb; + } else { + wrappedCb = false; + } + this.emitMulti(methodName, evNameBefore); + let result; + try { + result = method.apply(this, args); + if (!wrappedCb) { + this.emitMulti(methodName, evNameAfter, { + [methodName]: result + }); + } + } catch (error) { + error.methodName = methodName; + this.emitError(methodName, error); + } + return result; + }; + Jimp.prototype[methodName + "Quiet"] = method; +} + +/** + * Creates a new image that is a clone of this one. + * @param {function(Error, Jimp)} cb (optional) A callback for when complete + * @returns the new image + */ +jimpEvMethod("clone", "clone", function (cb) { + const clone = new Jimp(this); + if (isNodePattern(cb)) { + cb.call(clone, null, clone); + } + return clone; +}); + +/** + * Simplify jimpEvMethod call for the common `change` evName. + * @param {string} methodName name of the method + * @param {function} method to watch changes for + */ +export function jimpEvChange(methodName, method) { + jimpEvMethod(methodName, "change", method); +} + +/** + * Sets the type of the image (RGB or RGBA) when saving as PNG format (default is RGBA) + * @param b A Boolean, true to use RGBA or false to use RGB + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +jimpEvChange("background", function (hex, cb) { + if (typeof hex !== "number") { + return throwError.call(this, "hex must be a hexadecimal rgba value", cb); + } + this._background = hex; + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; +}); + +/** + * Scans through a region of the bitmap, calling a function for each pixel. + * @param {number} x the x coordinate to begin the scan at + * @param {number} y the y coordinate to begin the scan at + * @param w the width of the scan region + * @param h the height of the scan region + * @param f a function to call on even pixel; the (x, y) position of the pixel + * and the index of the pixel in the bitmap buffer are passed to the function + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +jimpEvChange("scan", function (x, y, w, h, f, cb) { + if (typeof x !== "number" || typeof y !== "number") { + return throwError.call(this, "x and y must be numbers", cb); + } + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + if (typeof f !== "function") { + return throwError.call(this, "f must be a function", cb); + } + const result = scan(this, x, y, w, h, f); + if (isNodePattern(cb)) { + cb.call(this, null, result); + } + return result; +}); +if (process.env.ENVIRONMENT === "BROWSER") { + // For use in a web browser or web worker + /* global self */ + let gl; + if (typeof window !== "undefined" && typeof window === "object") { + gl = window; + } + if (typeof self !== "undefined" && typeof self === "object") { + gl = self; + } + gl.Jimp = Jimp; + gl.Buffer = Buffer; +} +export { addType } from "./utils/mime"; +export default Jimp; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/index.js.map b/node_modules/@jimp/core/es/index.js.map new file mode 100644 index 00000000..cd3c35f6 --- /dev/null +++ b/node_modules/@jimp/core/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["fs","Path","EventEmitter","isNodePattern","throwError","scan","scanIterator","anyBase","pixelMatch","tinyColor","ImagePHash","request","composite","promisify","MIME","parseBitmap","getBuffer","getBufferAsync","constants","alphabet","maxHashLength","NaN","i","maxHash","BIN","slice","Array","join","push","length","noop","isArrayBuffer","test","Object","prototype","toString","call","toLowerCase","indexOf","bufferFromArrayBuffer","arrayBuffer","buffer","Buffer","alloc","byteLength","view","Uint8Array","loadFromURL","options","cb","err","data","isBuffer","Error","url","loadBufferFromPath","src","readFile","match","isRawRGBAData","obj","width","height","Uint8ClampedArray","makeRGBABufferFromRGB","rgbaBuffer","allocUnsafe","j","emptyBitmap","Jimp","constructor","args","MIME_PNG","path","write","mime","getBase64","getPixelColor","setPixelColor","jimpInstance","finish","evData","methodName","setTimeout","emitError","emitMulti","parseInt","w","h","_background","cssColorToHex","bitmap","writeUInt32BE","original","from","_quality","_deflateLevel","_deflateStrategy","_filterType","_rgba","_originalMime","imageData","isRGBA","extraConstructor","__extraConstructors","find","c","Promise","resolve","reject","run","then","catch","rgba","bool","eventName","assign","emit","getHeight","getWidth","inspect","getMIME","getExtension","createWriteStream","getType","pathObj","parse","dir","mkdirSync","recursive","stream","on","end","AUTO","hash","base","pHash","getHash","distanceFromHash","compareHash","currentHash","distance","getPixelIndex","x","y","edgeHandling","xi","yi","EDGE_EXTEND","Math","round","EDGE_WRAP","idx","hex","readUInt32BE","hasAlpha","byteLen","addConstants","entries","forEach","name","value","addJimpMethods","methods","appendConstructorOption","read","image","create","rgbaToInt","r","g","b","a","intToRGBA","floor","pow","cssColor","Number","toHex8","limit255","n","max","min","diff","img1","img2","threshold","bmp1","bmp2","cloneQuiet","resize","numDiffPixels","percent","phash","hash1","hash2","compareHashes","colorDiff","rgba1","rgba2","maxVal","jimpEvMethod","evName","method","evNameBefore","evNameAfter","replace","wrappedCb","apply","result","error","clone","jimpEvChange","f","process","env","ENVIRONMENT","gl","window","self","addType"],"sources":["../src/index.js"],"sourcesContent":["import fs from \"fs\";\nimport Path from \"path\";\nimport EventEmitter from \"events\";\n\nimport { isNodePattern, throwError, scan, scanIterator } from \"@jimp/utils\";\nimport anyBase from \"any-base\";\nimport pixelMatch from \"pixelmatch\";\nimport tinyColor from \"tinycolor2\";\n\nimport ImagePHash from \"./modules/phash\";\nimport request from \"./request\";\n\nimport composite from \"./composite\";\nimport promisify from \"./utils/promisify\";\nimport * as MIME from \"./utils/mime\";\nimport { parseBitmap, getBuffer, getBufferAsync } from \"./utils/image-bitmap\";\nimport * as constants from \"./constants\";\n\nconst alphabet =\n \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_\";\n\n// an array storing the maximum string length of hashes at various bases\n// 0 and 1 do not exist as possible hash lengths\nconst maxHashLength = [NaN, NaN];\n\nfor (let i = 2; i < 65; i++) {\n const maxHash = anyBase(\n anyBase.BIN,\n alphabet.slice(0, i)\n )(new Array(64 + 1).join(\"1\"));\n maxHashLength.push(maxHash.length);\n}\n\n// no operation\nfunction noop() {}\n\n// error checking methods\n\nfunction isArrayBuffer(test) {\n return (\n Object.prototype.toString.call(test).toLowerCase().indexOf(\"arraybuffer\") >\n -1\n );\n}\n\n// Prepare a Buffer object from the arrayBuffer. Necessary in the browser > node conversion,\n// But this function is not useful when running in node directly\nfunction bufferFromArrayBuffer(arrayBuffer) {\n const buffer = Buffer.alloc(arrayBuffer.byteLength);\n const view = new Uint8Array(arrayBuffer);\n\n for (let i = 0; i < buffer.length; ++i) {\n buffer[i] = view[i];\n }\n\n return buffer;\n}\n\nfunction loadFromURL(options, cb) {\n request(options, (err, data) => {\n if (err) {\n return cb(err);\n }\n\n if (typeof data === \"object\" && Buffer.isBuffer(data)) {\n return cb(null, data);\n }\n\n if (typeof data === \"object\" && isArrayBuffer(data)) {\n return cb(null, bufferFromArrayBuffer(data));\n }\n\n return new Error(`Could not load Buffer from <${options.url}>`);\n });\n}\n\nfunction loadBufferFromPath(src, cb) {\n if (\n fs &&\n typeof fs.readFile === \"function\" &&\n !src.match(/^(http|ftp)s?:\\/\\/./)\n ) {\n fs.readFile(src, cb);\n } else {\n loadFromURL({ url: src }, cb);\n }\n}\n\nfunction isRawRGBAData(obj) {\n return (\n obj &&\n typeof obj === \"object\" &&\n typeof obj.width === \"number\" &&\n typeof obj.height === \"number\" &&\n (Buffer.isBuffer(obj.data) ||\n obj.data instanceof Uint8Array ||\n (typeof Uint8ClampedArray === \"function\" &&\n obj.data instanceof Uint8ClampedArray)) &&\n (obj.data.length === obj.width * obj.height * 4 ||\n obj.data.length === obj.width * obj.height * 3)\n );\n}\n\nfunction makeRGBABufferFromRGB(buffer) {\n if (buffer.length % 3 !== 0) {\n throw new Error(\"Buffer length is incorrect\");\n }\n\n const rgbaBuffer = Buffer.allocUnsafe((buffer.length / 3) * 4);\n let j = 0;\n\n for (let i = 0; i < buffer.length; i++) {\n rgbaBuffer[j] = buffer[i];\n\n if ((i + 1) % 3 === 0) {\n rgbaBuffer[++j] = 255;\n }\n\n j++;\n }\n\n return rgbaBuffer;\n}\n\nconst emptyBitmap = {\n data: null,\n width: null,\n height: null,\n};\n\n/**\n * Jimp constructor (from a file)\n * @param path a path to the image\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (from a url with options)\n * @param options { url, otherOptions}\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (from another Jimp image or raw image data)\n * @param image a Jimp image to clone\n * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (from a Buffer)\n * @param data a Buffer containing the image data\n * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (to generate a new image)\n * @param w the width of the image\n * @param h the height of the image\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (to generate a new image)\n * @param w the width of the image\n * @param h the height of the image\n * @param background color to fill the image with\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap\n */\n\nclass Jimp extends EventEmitter {\n // An object representing a bitmap in memory, comprising:\n // - data: a buffer of the bitmap data\n // - width: the width of the image in pixels\n // - height: the height of the image in pixels\n bitmap = emptyBitmap;\n\n // Default colour to use for new pixels\n _background = 0x00000000;\n\n // Default MIME is PNG\n _originalMime = Jimp.MIME_PNG;\n\n // Exif data for the image\n _exif = null;\n\n // Whether Transparency supporting formats will be exported as RGB or RGBA\n _rgba = true;\n\n constructor(...args) {\n super();\n\n const jimpInstance = this;\n let cb = noop;\n\n if (isArrayBuffer(args[0])) {\n args[0] = bufferFromArrayBuffer(args[0]);\n }\n\n function finish(...args) {\n const [err] = args;\n const evData = err || {};\n evData.methodName = \"constructor\";\n\n setTimeout(() => {\n // run on next tick.\n if (err && cb === noop) {\n jimpInstance.emitError(\"constructor\", err);\n } else if (!err) {\n jimpInstance.emitMulti(\"constructor\", \"initialized\");\n }\n\n cb.call(jimpInstance, ...args);\n }, 1);\n }\n\n if (\n (typeof args[0] === \"number\" && typeof args[1] === \"number\") ||\n (parseInt(args[0], 10) && parseInt(args[1], 10))\n ) {\n // create a new image\n const w = parseInt(args[0], 10);\n const h = parseInt(args[1], 10);\n cb = args[2];\n\n // with a hex color\n if (typeof args[2] === \"number\") {\n this._background = args[2];\n cb = args[3];\n }\n\n // with a css color\n if (typeof args[2] === \"string\") {\n this._background = Jimp.cssColorToHex(args[2]);\n cb = args[3];\n }\n\n if (typeof cb === \"undefined\") {\n cb = noop;\n }\n\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n\n this.bitmap = {\n data: Buffer.alloc(w * h * 4),\n width: w,\n height: h,\n };\n\n for (let i = 0; i < this.bitmap.data.length; i += 4) {\n this.bitmap.data.writeUInt32BE(this._background, i);\n }\n\n finish(null, this);\n } else if (typeof args[0] === \"object\" && args[0].url) {\n cb = args[1] || noop;\n\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n\n loadFromURL(args[0], (err, data) => {\n if (err) {\n return throwError.call(this, err, finish);\n }\n\n this.parseBitmap(data, args[0].url, finish);\n });\n } else if (args[0] instanceof Jimp) {\n // clone an existing Jimp\n const [original] = args;\n cb = args[1];\n\n if (typeof cb === \"undefined\") {\n cb = noop;\n }\n\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n\n this.bitmap = {\n data: Buffer.from(original.bitmap.data),\n width: original.bitmap.width,\n height: original.bitmap.height,\n };\n\n this._quality = original._quality;\n this._deflateLevel = original._deflateLevel;\n this._deflateStrategy = original._deflateStrategy;\n this._filterType = original._filterType;\n this._rgba = original._rgba;\n this._background = original._background;\n this._originalMime = original._originalMime;\n\n finish(null, this);\n } else if (isRawRGBAData(args[0])) {\n const [imageData] = args;\n cb = args[1] || noop;\n\n const isRGBA =\n imageData.width * imageData.height * 4 === imageData.data.length;\n const buffer = isRGBA\n ? Buffer.from(imageData.data)\n : makeRGBABufferFromRGB(imageData.data);\n\n this.bitmap = {\n data: buffer,\n width: imageData.width,\n height: imageData.height,\n };\n\n finish(null, this);\n } else if (typeof args[0] === \"string\") {\n // read from a path\n const path = args[0];\n cb = args[1];\n\n if (typeof cb === \"undefined\") {\n cb = noop;\n }\n\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n\n loadBufferFromPath(path, (err, data) => {\n if (err) {\n return throwError.call(this, err, finish);\n }\n\n this.parseBitmap(data, path, finish);\n });\n } else if (typeof args[0] === \"object\" && Buffer.isBuffer(args[0])) {\n // read from a buffer\n const data = args[0];\n cb = args[1];\n\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n\n this.parseBitmap(data, null, finish);\n } else {\n // Allow client libs to add new ways to build a Jimp object.\n // Extra constructors must be added by `Jimp.appendConstructorOption()`\n cb = args[args.length - 1];\n\n if (typeof cb !== \"function\") {\n // TODO: try to solve the args after cb problem.\n cb = args[args.length - 2];\n\n if (typeof cb !== \"function\") {\n cb = noop;\n }\n }\n\n const extraConstructor = Jimp.__extraConstructors.find((c) =>\n c.test(...args)\n );\n\n if (extraConstructor) {\n new Promise((resolve, reject) => {\n extraConstructor.run.call(this, resolve, reject, ...args);\n })\n .then(() => finish(null, this))\n .catch(finish);\n } else {\n return throwError.call(\n this,\n \"No matching constructor overloading was found. \" +\n \"Please see the docs for how to call the Jimp constructor.\",\n finish\n );\n }\n }\n }\n\n /**\n * Parse a bitmap with the loaded image types.\n *\n * @param {Buffer} data raw image data\n * @param {string} path optional path to file\n * @param {function(Error, Jimp)} finish (optional) a callback for when complete\n * @memberof Jimp\n */\n parseBitmap(data, path, finish) {\n parseBitmap.call(this, data, null, finish);\n }\n\n /**\n * Sets the type of the image (RGB or RGBA) when saving in a format that supports transparency (default is RGBA)\n * @param {boolean} bool A Boolean, true to use RGBA or false to use RGB\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n rgba(bool, cb) {\n if (typeof bool !== \"boolean\") {\n return throwError.call(\n this,\n \"bool must be a boolean, true for RGBA or false for RGB\",\n cb\n );\n }\n\n this._rgba = bool;\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n }\n\n /**\n * Emit for multiple listeners\n * @param {string} methodName name of the method to emit an error for\n * @param {string} eventName name of the eventName to emit an error for\n * @param {object} data to emit\n */\n emitMulti(methodName, eventName, data = {}) {\n data = Object.assign(data, { methodName, eventName });\n this.emit(\"any\", data);\n\n if (methodName) {\n this.emit(methodName, data);\n }\n\n this.emit(eventName, data);\n }\n\n emitError(methodName, err) {\n this.emitMulti(methodName, \"error\", err);\n }\n\n /**\n * Get the current height of the image\n * @return {number} height of the image\n */\n getHeight() {\n return this.bitmap.height;\n }\n\n /**\n * Get the current width of the image\n * @return {number} width of the image\n */\n getWidth() {\n return this.bitmap.width;\n }\n\n /**\n * Nicely format Jimp object when sent to the console e.g. console.log(image)\n * @returns {string} pretty printed\n */\n inspect() {\n return (\n \"\"\n );\n }\n\n /**\n * Nicely format Jimp object when converted to a string\n * @returns {string} pretty printed\n */\n toString() {\n return \"[object Jimp]\";\n }\n\n /**\n * Returns the original MIME of the image (default: \"image/png\")\n * @returns {string} the MIME\n */\n getMIME() {\n const mime = this._originalMime || Jimp.MIME_PNG;\n\n return mime;\n }\n\n /**\n * Returns the appropriate file extension for the original MIME of the image (default: \"png\")\n * @returns {string} the file extension\n */\n getExtension() {\n const mime = this.getMIME();\n\n return MIME.getExtension(mime);\n }\n\n /**\n * Writes the image to a file\n * @param {string} path a path to the destination file\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is saved to disk\n * @returns {Jimp} this for chaining of methods\n */\n write(path, cb) {\n if (!fs || !fs.createWriteStream) {\n throw new Error(\n \"Cant access the filesystem. You can use the getBase64 method.\"\n );\n }\n\n if (typeof path !== \"string\") {\n return throwError.call(this, \"path must be a string\", cb);\n }\n\n if (typeof cb === \"undefined\") {\n cb = noop;\n }\n\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", cb);\n }\n\n const mime = MIME.getType(path) || this.getMIME();\n const pathObj = Path.parse(path);\n\n if (pathObj.dir) {\n fs.mkdirSync(pathObj.dir, { recursive: true });\n }\n\n this.getBuffer(mime, (err, buffer) => {\n if (err) {\n return throwError.call(this, err, cb);\n }\n\n const stream = fs.createWriteStream(path);\n\n stream\n .on(\"open\", () => {\n stream.write(buffer);\n stream.end();\n })\n .on(\"error\", (err) => {\n return throwError.call(this, err, cb);\n });\n stream.on(\"finish\", () => {\n cb.call(this, null, this);\n });\n });\n\n return this;\n }\n\n writeAsync = (path) => promisify(this.write, this, path);\n\n /**\n * Converts the image to a base 64 string\n * @param {string} mime the mime type of the image data to be created\n * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument\n * @returns {Jimp} this for chaining of methods\n */\n getBase64(mime, cb) {\n if (mime === Jimp.AUTO) {\n // allow auto MIME detection\n mime = this.getMIME();\n }\n\n if (typeof mime !== \"string\") {\n return throwError.call(this, \"mime must be a string\", cb);\n }\n\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", cb);\n }\n\n this.getBuffer(mime, function (err, data) {\n if (err) {\n return throwError.call(this, err, cb);\n }\n\n const src = \"data:\" + mime + \";base64,\" + data.toString(\"base64\");\n cb.call(this, null, src);\n });\n\n return this;\n }\n\n getBase64Async = (mime) => promisify(this.getBase64, this, mime);\n\n /**\n * Generates a perceptual hash of the image . And pads the string. Can configure base.\n * @param {number} base (optional) a number between 2 and 64 representing the base for the hash (e.g. 2 is binary, 10 is decimal, 16 is hex, 64 is base 64). Defaults to 64.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {string} a string representing the hash\n */\n hash(base, cb) {\n base = base || 64;\n\n if (typeof base === \"function\") {\n cb = base;\n base = 64;\n }\n\n if (typeof base !== \"number\") {\n return throwError.call(this, \"base must be a number\", cb);\n }\n\n if (base < 2 || base > 64) {\n return throwError.call(\n this,\n \"base must be a number between 2 and 64\",\n cb\n );\n }\n\n let hash = this.pHash();\n hash = anyBase(anyBase.BIN, alphabet.slice(0, base))(hash);\n\n while (hash.length < maxHashLength[base]) {\n hash = \"0\" + hash; // pad out with leading zeros\n }\n\n if (isNodePattern(cb)) {\n cb.call(this, null, hash);\n }\n\n return hash;\n }\n\n /**\n * Calculates the perceptual hash\n * @returns {number} the perceptual hash\n */\n pHash() {\n const pHash = new ImagePHash();\n return pHash.getHash(this);\n }\n\n /**\n * Calculates the hamming distance of the current image and a hash based on their perceptual hash\n * @param {hash} compareHash hash to compare to\n * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical\n */\n distanceFromHash(compareHash) {\n const pHash = new ImagePHash();\n const currentHash = pHash.getHash(this);\n\n return pHash.distance(currentHash, compareHash);\n }\n\n /**\n * Converts the image to a buffer\n * @param {string} mime the mime type of the image buffer to be created\n * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument\n * @returns {Jimp} this for chaining of methods\n */\n getBuffer = getBuffer;\n\n getBufferAsync = getBufferAsync;\n\n /**\n * Returns the offset of a pixel in the bitmap buffer\n * @param {number} x the x coordinate\n * @param {number} y the y coordinate\n * @param {number} edgeHandling (optional) define how to sum pixels from outside the border\n * @param {number} cb (optional) a callback for when complete\n * @returns {number} the index of the pixel or -1 if not found\n */\n getPixelIndex(x, y, edgeHandling, cb) {\n let xi;\n let yi;\n\n if (typeof edgeHandling === \"function\" && typeof cb === \"undefined\") {\n cb = edgeHandling;\n edgeHandling = null;\n }\n\n if (!edgeHandling) {\n edgeHandling = Jimp.EDGE_EXTEND;\n }\n\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n xi = x;\n yi = y;\n\n if (edgeHandling === Jimp.EDGE_EXTEND) {\n if (x < 0) xi = 0;\n if (x >= this.bitmap.width) xi = this.bitmap.width - 1;\n if (y < 0) yi = 0;\n if (y >= this.bitmap.height) yi = this.bitmap.height - 1;\n }\n\n if (edgeHandling === Jimp.EDGE_WRAP) {\n if (x < 0) {\n xi = this.bitmap.width + x;\n }\n\n if (x >= this.bitmap.width) {\n xi = x % this.bitmap.width;\n }\n\n if (y < 0) {\n yi = this.bitmap.height + y;\n }\n\n if (y >= this.bitmap.height) {\n yi = y % this.bitmap.height;\n }\n }\n\n let i = (this.bitmap.width * yi + xi) << 2;\n\n // if out of bounds index is -1\n if (xi < 0 || xi >= this.bitmap.width) {\n i = -1;\n }\n\n if (yi < 0 || yi >= this.bitmap.height) {\n i = -1;\n }\n\n if (isNodePattern(cb)) {\n cb.call(this, null, i);\n }\n\n return i;\n }\n\n /**\n * Returns the hex colour value of a pixel\n * @param {number} x the x coordinate\n * @param {number} y the y coordinate\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {number} the color of the pixel\n */\n getPixelColor(x, y, cb) {\n if (typeof x !== \"number\" || typeof y !== \"number\")\n return throwError.call(this, \"x and y must be numbers\", cb);\n\n const idx = this.getPixelIndex(x, y);\n const hex = this.bitmap.data.readUInt32BE(idx);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, hex);\n }\n\n return hex;\n }\n\n getPixelColour = this.getPixelColor;\n\n /**\n * Returns the hex colour value of a pixel\n * @param {number} hex color to set\n * @param {number} x the x coordinate\n * @param {number} y the y coordinate\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {number} the index of the pixel or -1 if not found\n */\n setPixelColor(hex, x, y, cb) {\n if (\n typeof hex !== \"number\" ||\n typeof x !== \"number\" ||\n typeof y !== \"number\"\n )\n return throwError.call(this, \"hex, x and y must be numbers\", cb);\n\n const idx = this.getPixelIndex(x, y);\n this.bitmap.data.writeUInt32BE(hex, idx);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n }\n\n setPixelColour = this.setPixelColor;\n\n /**\n * Determine if the image contains opaque pixels.\n * @return {boolean} hasAlpha whether the image contains opaque pixels\n */\n hasAlpha() {\n const {width, height, data} = this.bitmap;\n const byteLen = (width * height) << 2;\n\n for (let idx = 3; idx < byteLen; idx += 4) {\n if (data[idx] !== 0xff) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Iterate scan through a region of the bitmap\n * @param {number} x the x coordinate to begin the scan at\n * @param {number} y the y coordinate to begin the scan at\n * @param w the width of the scan region\n * @param h the height of the scan region\n * @returns {IterableIterator<{x: number, y: number, idx: number, image: Jimp}>}\n */\n scanIterator(x, y, w, h) {\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\");\n }\n\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\");\n }\n\n return scanIterator(this, x, y, w, h);\n }\n}\n\nexport function addConstants(constants, jimpInstance = Jimp) {\n Object.entries(constants).forEach(([name, value]) => {\n jimpInstance[name] = value;\n });\n}\n\nexport function addJimpMethods(methods, jimpInstance = Jimp) {\n Object.entries(methods).forEach(([name, value]) => {\n jimpInstance.prototype[name] = value;\n });\n}\n\naddConstants(constants);\naddJimpMethods({ composite });\n\nJimp.__extraConstructors = [];\n\n/**\n * Allow client libs to add new ways to build a Jimp object.\n * @param {string} name identify the extra constructor.\n * @param {function} test a function that returns true when it accepts the arguments passed to the main constructor.\n * @param {function} run where the magic happens.\n */\nJimp.appendConstructorOption = function (name, test, run) {\n Jimp.__extraConstructors.push({ name, test, run });\n};\n\n/**\n * Read an image from a file or a Buffer. Takes the same args as the constructor\n * @returns {Promise} a promise\n */\nJimp.read = function (...args) {\n return new Promise((resolve, reject) => {\n // eslint-disable-next-line no-new\n new Jimp(...args, (err, image) => {\n if (err) reject(err);\n else resolve(image);\n });\n });\n};\n\nJimp.create = Jimp.read;\n\n/**\n * A static helper method that converts RGBA values to a single integer value\n * @param {number} r the red value (0-255)\n * @param {number} g the green value (0-255)\n * @param {number} b the blue value (0-255)\n * @param {number} a the alpha value (0-255)\n * @param {function(Error, Jimp)} cb (optional) A callback for when complete\n * @returns {number} an single integer colour value\n */\nJimp.rgbaToInt = function (r, g, b, a, cb) {\n if (\n typeof r !== \"number\" ||\n typeof g !== \"number\" ||\n typeof b !== \"number\" ||\n typeof a !== \"number\"\n ) {\n return throwError.call(this, \"r, g, b and a must be numbers\", cb);\n }\n\n if (r < 0 || r > 255) {\n return throwError.call(this, \"r must be between 0 and 255\", cb);\n }\n\n if (g < 0 || g > 255) {\n throwError.call(this, \"g must be between 0 and 255\", cb);\n }\n\n if (b < 0 || b > 255) {\n return throwError.call(this, \"b must be between 0 and 255\", cb);\n }\n\n if (a < 0 || a > 255) {\n return throwError.call(this, \"a must be between 0 and 255\", cb);\n }\n\n let i = (r & 0xff);\n i <<= 8;\n i |= (g & 0xff)\n i <<= 8;\n i |= (b & 0xff)\n i <<= 8;\n i |= (a & 0xff);\n\n // Ensure sign is correct\n i >>>= 0;\n\n if (isNodePattern(cb)) {\n cb.call(this, null, i);\n }\n\n return i;\n};\n\n/**\n * A static helper method that converts RGBA values to a single integer value\n * @param {number} i a single integer value representing an RGBA colour (e.g. 0xFF0000FF for red)\n * @param {function(Error, Jimp)} cb (optional) A callback for when complete\n * @returns {object} an object with the properties r, g, b and a representing RGBA values\n */\nJimp.intToRGBA = function (i, cb) {\n if (typeof i !== \"number\") {\n return throwError.call(this, \"i must be a number\", cb);\n }\n\n const rgba = {};\n\n rgba.r = Math.floor(i / Math.pow(256, 3));\n rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2));\n rgba.b = Math.floor(\n (i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) /\n Math.pow(256, 1)\n );\n rgba.a = Math.floor(\n (i -\n rgba.r * Math.pow(256, 3) -\n rgba.g * Math.pow(256, 2) -\n rgba.b * Math.pow(256, 1)) /\n Math.pow(256, 0)\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, rgba);\n }\n\n return rgba;\n};\n\n/**\n * Converts a css color (Hex, 8-digit (RGBA) Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to a hex number\n * @param {string} cssColor a number\n * @returns {number} a hex number representing a color\n */\nJimp.cssColorToHex = function (cssColor) {\n cssColor = cssColor || 0; // 0, null, undefined, NaN\n\n if (typeof cssColor === \"number\") return Number(cssColor);\n\n return parseInt(tinyColor(cssColor).toHex8(), 16);\n};\n\n/**\n * Limits a number to between 0 or 255\n * @param {number} n a number\n * @returns {number} the number limited to between 0 or 255\n */\nJimp.limit255 = function (n) {\n n = Math.max(n, 0);\n n = Math.min(n, 255);\n\n return n;\n};\n\n/**\n * Diffs two images and returns\n * @param {Jimp} img1 a Jimp image to compare\n * @param {Jimp} img2 a Jimp image to compare\n * @param {number} threshold (optional) a number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1)\n * @returns {object} an object { percent: percent similar, diff: a Jimp image highlighting differences }\n */\nJimp.diff = function (img1, img2, threshold = 0.1) {\n if (!(img1 instanceof Jimp) || !(img2 instanceof Jimp))\n return throwError.call(this, \"img1 and img2 must be an Jimp images\");\n\n const bmp1 = img1.bitmap;\n const bmp2 = img2.bitmap;\n\n if (bmp1.width !== bmp2.width || bmp1.height !== bmp2.height) {\n if (bmp1.width * bmp1.height > bmp2.width * bmp2.height) {\n // img1 is bigger\n img1 = img1.cloneQuiet().resize(bmp2.width, bmp2.height);\n } else {\n // img2 is bigger (or they are the same in area)\n img2 = img2.cloneQuiet().resize(bmp1.width, bmp1.height);\n }\n }\n\n if (typeof threshold !== \"number\" || threshold < 0 || threshold > 1) {\n return throwError.call(this, \"threshold must be a number between 0 and 1\");\n }\n\n const diff = new Jimp(bmp1.width, bmp1.height, 0xffffffff);\n\n const numDiffPixels = pixelMatch(\n bmp1.data,\n bmp2.data,\n diff.bitmap.data,\n diff.bitmap.width,\n diff.bitmap.height,\n { threshold }\n );\n\n return {\n percent: numDiffPixels / (diff.bitmap.width * diff.bitmap.height),\n image: diff,\n };\n};\n\n/**\n * Calculates the hamming distance of two images based on their perceptual hash\n * @param {Jimp} img1 a Jimp image to compare\n * @param {Jimp} img2 a Jimp image to compare\n * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical\n */\nJimp.distance = function (img1, img2) {\n const phash = new ImagePHash();\n const hash1 = phash.getHash(img1);\n const hash2 = phash.getHash(img2);\n\n return phash.distance(hash1, hash2);\n};\n\n/**\n * Calculates the hamming distance of two images based on their perceptual hash\n * @param {hash} hash1 a pHash\n * @param {hash} hash2 a pHash\n * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical\n */\nJimp.compareHashes = function (hash1, hash2) {\n const phash = new ImagePHash();\n\n return phash.distance(hash1, hash2);\n};\n\n/**\n * Compute color difference\n * 0 means no difference, 1 means maximum difference.\n * @param {number} rgba1: first color to compare.\n * @param {number} rgba2: second color to compare.\n * Both parameters must be an color object {r:val, g:val, b:val, a:val}\n * Where `a` is optional and `val` is an integer between 0 and 255.\n * @returns {number} float between 0 and 1.\n */\nJimp.colorDiff = function (rgba1, rgba2) {\n const pow = (n) => Math.pow(n, 2);\n const { max } = Math;\n const maxVal = 255 * 255 * 3;\n\n if (rgba1.a !== 0 && !rgba1.a) {\n rgba1.a = 255;\n }\n\n if (rgba2.a !== 0 && !rgba2.a) {\n rgba2.a = 255;\n }\n\n return (\n (max(pow(rgba1.r - rgba2.r), pow(rgba1.r - rgba2.r - rgba1.a + rgba2.a)) +\n max(pow(rgba1.g - rgba2.g), pow(rgba1.g - rgba2.g - rgba1.a + rgba2.a)) +\n max(pow(rgba1.b - rgba2.b), pow(rgba1.b - rgba2.b - rgba1.a + rgba2.a))) /\n maxVal\n );\n};\n\n/**\n * Helper to create Jimp methods that emit events before and after its execution.\n * @param {string} methodName The name to be appended to Jimp prototype.\n * @param {string} evName The event name to be called.\n * It will be prefixed by `before-` and emitted when on method call.\n * It will be appended by `ed` and emitted after the method run.\n * @param {function} method A function implementing the method itself.\n * It will also create a quiet version that will not emit events, to not\n * mess the user code with many `changed` event calls. You can call with\n * `methodName + \"Quiet\"`.\n *\n * The emitted event comes with a object parameter to the listener with the\n * `methodName` as one attribute.\n */\nexport function jimpEvMethod(methodName, evName, method) {\n const evNameBefore = \"before-\" + evName;\n const evNameAfter = evName.replace(/e$/, \"\") + \"ed\";\n\n Jimp.prototype[methodName] = function (...args) {\n let wrappedCb;\n const cb = args[method.length - 1];\n const jimpInstance = this;\n\n if (typeof cb === \"function\") {\n wrappedCb = function (...args) {\n const [err, data] = args;\n\n if (err) {\n jimpInstance.emitError(methodName, err);\n } else {\n jimpInstance.emitMulti(methodName, evNameAfter, {\n [methodName]: data,\n });\n }\n\n cb.apply(this, args);\n };\n\n args[args.length - 1] = wrappedCb;\n } else {\n wrappedCb = false;\n }\n\n this.emitMulti(methodName, evNameBefore);\n\n let result;\n\n try {\n result = method.apply(this, args);\n\n if (!wrappedCb) {\n this.emitMulti(methodName, evNameAfter, {\n [methodName]: result,\n });\n }\n } catch (error) {\n error.methodName = methodName;\n this.emitError(methodName, error);\n }\n\n return result;\n };\n\n Jimp.prototype[methodName + \"Quiet\"] = method;\n}\n\n/**\n * Creates a new image that is a clone of this one.\n * @param {function(Error, Jimp)} cb (optional) A callback for when complete\n * @returns the new image\n */\njimpEvMethod(\"clone\", \"clone\", function (cb) {\n const clone = new Jimp(this);\n\n if (isNodePattern(cb)) {\n cb.call(clone, null, clone);\n }\n\n return clone;\n});\n\n/**\n * Simplify jimpEvMethod call for the common `change` evName.\n * @param {string} methodName name of the method\n * @param {function} method to watch changes for\n */\nexport function jimpEvChange(methodName, method) {\n jimpEvMethod(methodName, \"change\", method);\n}\n\n/**\n * Sets the type of the image (RGB or RGBA) when saving as PNG format (default is RGBA)\n * @param b A Boolean, true to use RGBA or false to use RGB\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\njimpEvChange(\"background\", function (hex, cb) {\n if (typeof hex !== \"number\") {\n return throwError.call(this, \"hex must be a hexadecimal rgba value\", cb);\n }\n\n this._background = hex;\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n});\n\n/**\n * Scans through a region of the bitmap, calling a function for each pixel.\n * @param {number} x the x coordinate to begin the scan at\n * @param {number} y the y coordinate to begin the scan at\n * @param w the width of the scan region\n * @param h the height of the scan region\n * @param f a function to call on even pixel; the (x, y) position of the pixel\n * and the index of the pixel in the bitmap buffer are passed to the function\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\njimpEvChange(\"scan\", function (x, y, w, h, f, cb) {\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n\n if (typeof f !== \"function\") {\n return throwError.call(this, \"f must be a function\", cb);\n }\n\n const result = scan(this, x, y, w, h, f);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, result);\n }\n\n return result;\n});\n\nif (process.env.ENVIRONMENT === \"BROWSER\") {\n // For use in a web browser or web worker\n /* global self */\n let gl;\n\n if (typeof window !== \"undefined\" && typeof window === \"object\") {\n gl = window;\n }\n\n if (typeof self !== \"undefined\" && typeof self === \"object\") {\n gl = self;\n }\n\n gl.Jimp = Jimp;\n gl.Buffer = Buffer;\n}\n\nexport { addType } from \"./utils/mime\";\n\nexport default Jimp;\n"],"mappings":";;;AAAA,OAAOA,EAAE,MAAM,IAAI;AACnB,OAAOC,IAAI,MAAM,MAAM;AACvB,OAAOC,YAAY,MAAM,QAAQ;AAEjC,SAASC,aAAa,EAAEC,UAAU,EAAEC,IAAI,EAAEC,YAAY,QAAQ,aAAa;AAC3E,OAAOC,OAAO,MAAM,UAAU;AAC9B,OAAOC,UAAU,MAAM,YAAY;AACnC,OAAOC,SAAS,MAAM,YAAY;AAElC,OAAOC,UAAU,MAAM,iBAAiB;AACxC,OAAOC,OAAO,MAAM,WAAW;AAE/B,OAAOC,SAAS,MAAM,aAAa;AACnC,OAAOC,SAAS,MAAM,mBAAmB;AACzC,OAAO,KAAKC,IAAI,MAAM,cAAc;AACpC,SAASC,WAAW,EAAEC,SAAS,EAAEC,cAAc,QAAQ,sBAAsB;AAC7E,OAAO,KAAKC,SAAS,MAAM,aAAa;AAExC,MAAMC,QAAQ,GACZ,kEAAkE;;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UAAU,CAACgC,IAAI,CAAC,IAAI,EAAE,sBAAsB,EAAEa,EAAE,CAAC;EAC1D;EAEA,MAAMgK,MAAM,GAAG5M,IAAI,CAAC,IAAI,EAAE0I,CAAC,EAAEC,CAAC,EAAEzD,CAAC,EAAEC,CAAC,EAAE6H,CAAC,CAAC;EAExC,IAAIlN,aAAa,CAAC8C,EAAE,CAAC,EAAE;IACrBA,EAAE,CAACb,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE6K,MAAM,CAAC;EAC7B;EAEA,OAAOA,MAAM;AACf,CAAC,CAAC;AAEF,IAAIK,OAAO,CAACC,GAAG,CAACC,WAAW,KAAK,SAAS,EAAE;EACzC;EACA;EACA,IAAIC,EAAE;EAEN,IAAI,OAAOC,MAAM,KAAK,WAAW,IAAI,OAAOA,MAAM,KAAK,QAAQ,EAAE;IAC/DD,EAAE,GAAGC,MAAM;EACb;EAEA,IAAI,OAAOC,IAAI,KAAK,WAAW,IAAI,OAAOA,IAAI,KAAK,QAAQ,EAAE;IAC3DF,EAAE,GAAGE,IAAI;EACX;EAEAF,EAAE,CAACpJ,IAAI,GAAGA,IAAI;EACdoJ,EAAE,CAAC/K,MAAM,GAAGA,MAAM;AACpB;AAEA,SAASkL,OAAO,QAAQ,cAAc;AAEtC,eAAevJ,IAAI"} \ No newline at end of file diff --git a/node_modules/@jimp/core/es/modules/phash.js b/node_modules/@jimp/core/es/modules/phash.js new file mode 100644 index 00000000..b404606e --- /dev/null +++ b/node_modules/@jimp/core/es/modules/phash.js @@ -0,0 +1,162 @@ +/* +Copyright (c) 2011 Elliot Shepherd + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +// https://code.google.com/p/ironchef-team21/source/browse/ironchef_team21/src/ImagePHash.java + +/* + * pHash-like image hash. + * Author: Elliot Shepherd (elliot@jarofworms.com + * Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html + */ + +function ImagePHash(size, smallerSize) { + this.size = this.size || size; + this.smallerSize = this.smallerSize || smallerSize; + initCoefficients(this.size); +} +ImagePHash.prototype.size = 32; +ImagePHash.prototype.smallerSize = 8; +ImagePHash.prototype.distance = function (s1, s2) { + let counter = 0; + for (let k = 0; k < s1.length; k++) { + if (s1[k] !== s2[k]) { + counter++; + } + } + return counter / s1.length; +}; + +// Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on. +ImagePHash.prototype.getHash = function (img) { + /* 1. Reduce size. + * Like Average Hash, pHash starts with a small image. + * However, the image is larger than 8x8; 32x32 is a good size. + * This is really done to simplify the DCT computation and not + * because it is needed to reduce the high frequencies. + */ + img = img.clone().resize(this.size, this.size); + + /* 2. Reduce color. + * The image is reduced to a grayscale just to further simplify + * the number of computations. + */ + img.grayscale(); + const vals = []; + for (let x = 0; x < img.bitmap.width; x++) { + vals[x] = []; + for (let y = 0; y < img.bitmap.height; y++) { + vals[x][y] = intToRGBA(img.getPixelColor(x, y)).b; + } + } + + /* 3. Compute the DCT. + * The DCT separates the image into a collection of frequencies + * and scalars. While JPEG uses an 8x8 DCT, this algorithm uses + * a 32x32 DCT. + */ + const dctVals = applyDCT(vals, this.size); + + /* 4. Reduce the DCT. + * This is the magic step. While the DCT is 32x32, just keep the + * top-left 8x8. Those represent the lowest frequencies in the + * picture. + */ + /* 5. Compute the average value. + * Like the Average Hash, compute the mean DCT value (using only + * the 8x8 DCT low-frequency values and excluding the first term + * since the DC coefficient can be significantly different from + * the other values and will throw off the average). + */ + let total = 0; + for (let x = 0; x < this.smallerSize; x++) { + for (let y = 0; y < this.smallerSize; y++) { + total += dctVals[x][y]; + } + } + const avg = total / (this.smallerSize * this.smallerSize); + + /* 6. Further reduce the DCT. + * This is the magic step. Set the 64 hash bits to 0 or 1 + * depending on whether each of the 64 DCT values is above or + * below the average value. The result doesn't tell us the + * actual low frequencies; it just tells us the very-rough + * relative scale of the frequencies to the mean. The result + * will not vary as long as the overall structure of the image + * remains the same; this can survive gamma and color histogram + * adjustments without a problem. + */ + let hash = ""; + for (let x = 0; x < this.smallerSize; x++) { + for (let y = 0; y < this.smallerSize; y++) { + hash += dctVals[x][y] > avg ? "1" : "0"; + } + } + return hash; +}; + +// DCT function stolen from http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java + +/** + Convert a 32-bit integer color value to an RGBA object. + */ +function intToRGBA(i) { + const a = i & 0xff; + i >>>= 8; + const b = i & 0xff; + i >>>= 8; + const g = i & 0xff; + i >>>= 8; + const r = i & 0xff; + return { + r, + g, + b, + a + }; +} +const c = []; +function initCoefficients(size) { + for (let i = 1; i < size; i++) { + c[i] = 1; + } + c[0] = 1 / Math.sqrt(2.0); +} +function applyDCT(f, size) { + const N = size; + const F = []; + for (let u = 0; u < N; u++) { + F[u] = []; + for (let v = 0; v < N; v++) { + let sum = 0; + for (let i = 0; i < N; i++) { + for (let j = 0; j < N; j++) { + sum += Math.cos((2 * i + 1) / (2.0 * N) * u * Math.PI) * Math.cos((2 * j + 1) / (2.0 * N) * v * Math.PI) * f[i][j]; + } + } + sum *= c[u] * c[v] / 4; + F[u][v] = sum; + } + } + return F; +} +export default ImagePHash; +//# sourceMappingURL=phash.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/modules/phash.js.map b/node_modules/@jimp/core/es/modules/phash.js.map new file mode 100644 index 00000000..d3476d5f --- /dev/null +++ b/node_modules/@jimp/core/es/modules/phash.js.map @@ -0,0 +1 @@ +{"version":3,"file":"phash.js","names":["ImagePHash","size","smallerSize","initCoefficients","prototype","distance","s1","s2","counter","k","length","getHash","img","clone","resize","grayscale","vals","x","bitmap","width","y","height","intToRGBA","getPixelColor","b","dctVals","applyDCT","total","avg","hash","i","a","g","r","c","Math","sqrt","f","N","F","u","v","sum","j","cos","PI"],"sources":["../../src/modules/phash.js"],"sourcesContent":["/*\nCopyright (c) 2011 Elliot Shepherd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies 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 FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n// https://code.google.com/p/ironchef-team21/source/browse/ironchef_team21/src/ImagePHash.java\n\n/*\n * pHash-like image hash.\n * Author: Elliot Shepherd (elliot@jarofworms.com\n * Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html\n */\n\nfunction ImagePHash(size, smallerSize) {\n this.size = this.size || size;\n this.smallerSize = this.smallerSize || smallerSize;\n initCoefficients(this.size);\n}\n\nImagePHash.prototype.size = 32;\nImagePHash.prototype.smallerSize = 8;\n\nImagePHash.prototype.distance = function (s1, s2) {\n let counter = 0;\n\n for (let k = 0; k < s1.length; k++) {\n if (s1[k] !== s2[k]) {\n counter++;\n }\n }\n\n return counter / s1.length;\n};\n\n// Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on.\nImagePHash.prototype.getHash = function (img) {\n /* 1. Reduce size.\n * Like Average Hash, pHash starts with a small image.\n * However, the image is larger than 8x8; 32x32 is a good size.\n * This is really done to simplify the DCT computation and not\n * because it is needed to reduce the high frequencies.\n */\n img = img.clone().resize(this.size, this.size);\n\n /* 2. Reduce color.\n * The image is reduced to a grayscale just to further simplify\n * the number of computations.\n */\n img.grayscale();\n\n const vals = [];\n\n for (let x = 0; x < img.bitmap.width; x++) {\n vals[x] = [];\n for (let y = 0; y < img.bitmap.height; y++) {\n vals[x][y] = intToRGBA(img.getPixelColor(x, y)).b;\n }\n }\n\n /* 3. Compute the DCT.\n * The DCT separates the image into a collection of frequencies\n * and scalars. While JPEG uses an 8x8 DCT, this algorithm uses\n * a 32x32 DCT.\n */\n const dctVals = applyDCT(vals, this.size);\n\n /* 4. Reduce the DCT.\n * This is the magic step. While the DCT is 32x32, just keep the\n * top-left 8x8. Those represent the lowest frequencies in the\n * picture.\n */\n /* 5. Compute the average value.\n * Like the Average Hash, compute the mean DCT value (using only\n * the 8x8 DCT low-frequency values and excluding the first term\n * since the DC coefficient can be significantly different from\n * the other values and will throw off the average).\n */\n let total = 0;\n\n for (let x = 0; x < this.smallerSize; x++) {\n for (let y = 0; y < this.smallerSize; y++) {\n total += dctVals[x][y];\n }\n }\n\n const avg = total / (this.smallerSize * this.smallerSize);\n\n /* 6. Further reduce the DCT.\n * This is the magic step. Set the 64 hash bits to 0 or 1\n * depending on whether each of the 64 DCT values is above or\n * below the average value. The result doesn't tell us the\n * actual low frequencies; it just tells us the very-rough\n * relative scale of the frequencies to the mean. The result\n * will not vary as long as the overall structure of the image\n * remains the same; this can survive gamma and color histogram\n * adjustments without a problem.\n */\n let hash = \"\";\n\n for (let x = 0; x < this.smallerSize; x++) {\n for (let y = 0; y < this.smallerSize; y++) {\n hash += dctVals[x][y] > avg ? \"1\" : \"0\";\n }\n }\n\n return hash;\n};\n\n// DCT function stolen from http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java\n\n/**\n Convert a 32-bit integer color value to an RGBA object.\n */\nfunction intToRGBA(i) {\n const a = i & 0xff;\n i >>>= 8;\n const b = i & 0xff;\n i >>>= 8;\n const g = i & 0xff;\n i >>>= 8;\n const r = i & 0xff;\n\n return {r, g, b, a};\n}\n\nconst c = [];\nfunction initCoefficients(size) {\n for (let i = 1; i < size; i++) {\n c[i] = 1;\n }\n\n c[0] = 1 / Math.sqrt(2.0);\n}\n\nfunction applyDCT(f, size) {\n const N = size;\n const F = [];\n\n for (let u = 0; u < N; u++) {\n F[u] = [];\n for (let v = 0; v < N; v++) {\n let sum = 0;\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n sum +=\n Math.cos(((2 * i + 1) / (2.0 * N)) * u * Math.PI) *\n Math.cos(((2 * j + 1) / (2.0 * N)) * v * Math.PI) *\n f[i][j];\n }\n }\n\n sum *= (c[u] * c[v]) / 4;\n F[u][v] = sum;\n }\n }\n\n return F;\n}\n\nexport default ImagePHash;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,SAASA,UAAU,CAACC,IAAI,EAAEC,WAAW,EAAE;EACrC,IAAI,CAACD,IAAI,GAAG,IAAI,CAACA,IAAI,IAAIA,IAAI;EAC7B,IAAI,CAACC,WAAW,GAAG,I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GD,CAAC,GAAG,CAAC,KAAK,GAAG,GAAGL,CAAC,CAAC,GAAIG,CAAC,GAAGN,IAAI,CAACU,EAAE,CAAC,GACjDR,CAAC,CAACP,CAAC,CAAC,CAACa,CAAC,CAAC;QACX;MACF;MAEAD,GAAG,IAAKR,CAAC,CAACM,CAAC,CAAC,GAAGN,CAAC,CAACO,CAAC,CAAC,GAAI,CAAC;MACxBF,CAAC,CAACC,CAAC,CAAC,CAACC,CAAC,CAAC,GAAGC,GAAG;IACf;EACF;EAEA,OAAOH,CAAC;AACV;AAEA,eAAevC,UAAU"} \ No newline at end of file diff --git a/node_modules/@jimp/core/es/request.js b/node_modules/@jimp/core/es/request.js new file mode 100644 index 00000000..566d0a7c --- /dev/null +++ b/node_modules/@jimp/core/es/request.js @@ -0,0 +1,16 @@ +import "isomorphic-fetch"; +export default ((_ref, cb) => { + let { + url, + ...options + } = _ref; + fetch(url, options).then(response => { + if (response.ok) { + return response.arrayBuffer().catch(error => { + throw new Error(`Response is not a buffer for url ${url}. Error: ${error.message}`); + }); + } + throw new Error(`HTTP Status ${response.status} for url ${url}`); + }).then(data => cb(null, data)).catch(error => cb(error)); +}); +//# sourceMappingURL=request.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/request.js.map b/node_modules/@jimp/core/es/request.js.map new file mode 100644 index 00000000..5e709941 --- /dev/null +++ b/node_modules/@jimp/core/es/request.js.map @@ -0,0 +1 @@ +{"version":3,"file":"request.js","names":["cb","url","options","fetch","then","response","ok","arrayBuffer","catch","error","Error","message","status","data"],"sources":["../src/request.js"],"sourcesContent":["import \"isomorphic-fetch\";\n\nexport default ({ url, ...options }, cb) => {\n fetch(url, options)\n .then((response) => {\n if (response.ok) {\n return response.arrayBuffer().catch((error) => {\n throw new Error(\n `Response is not a buffer for url ${url}. Error: ${error.message}`\n );\n });\n }\n\n throw new Error(`HTTP Status ${response.status} for url ${url}`);\n })\n .then((data) => cb(null, data))\n .catch((error) => cb(error));\n};\n"],"mappings":"AAAA,OAAO,kBAAkB;AAEzB,gBAAe,OAAsBA,EAAE,KAAK;EAAA,IAA5B;IAAEC,GAAG;IAAE,GAAGC;EAAQ,CAAC;EACjCC,KAAK,CAACF,GAAG,EAAEC,OAAO,CAAC,CAChBE,IAAI,CAAEC,QAAQ,IAAK;IAClB,IAAIA,QAAQ,CAACC,EAAE,EAAE;MACf,OAAOD,QAAQ,CAACE,WAAW,EAAE,CAACC,KAAK,CAAEC,KAAK,IAAK;QAC7C,MAAM,IAAIC,KAAK,CACZ,oCAAmCT,GAAI,YAAWQ,KAAK,CAACE,OAAQ,EAAC,CACnE;MACH,CAAC,CAAC;IACJ;IAEA,MAAM,IAAID,KAAK,CAAE,eAAcL,QAAQ,CAACO,MAAO,YAAWX,GAAI,EAAC,CAAC;EAClE,CAAC,CAAC,CACDG,IAAI,CAAES,IAAI,IAAKb,EAAE,CAAC,IAAI,EAAEa,IAAI,CAAC,CAAC,CAC9BL,KAAK,CAAEC,KAAK,IAAKT,EAAE,CAACS,KAAK,CAAC,CAAC;AAChC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/core/es/utils/image-bitmap.js b/node_modules/@jimp/core/es/utils/image-bitmap.js new file mode 100644 index 00000000..1ae43bec --- /dev/null +++ b/node_modules/@jimp/core/es/utils/image-bitmap.js @@ -0,0 +1,210 @@ +import FileType from "file-type"; +import EXIFParser from "exif-parser"; +import { throwError } from "@jimp/utils"; +import * as constants from "../constants"; +import * as MIME from "./mime"; +import promisify from "./promisify"; +async function getMIMEFromBuffer(buffer, path) { + const fileTypeFromBuffer = await FileType.fromBuffer(buffer); + if (fileTypeFromBuffer) { + // If fileType returns something for buffer, then return the mime given + return fileTypeFromBuffer.mime; + } + if (path) { + // If a path is supplied, and fileType yields no results, then retry with MIME + // Path can be either a file path or a url + return MIME.getType(path); + } + return null; +} + +/* + * Obtains image orientation from EXIF metadata. + * + * @param img {Jimp} a Jimp image object + * @returns {number} a number 1-8 representing EXIF orientation, + * in particular 1 if orientation tag is missing + */ +function getExifOrientation(img) { + return img._exif && img._exif.tags && img._exif.tags.Orientation || 1; +} + +/** + * Returns a function which translates EXIF-rotated coordinates into + * non-rotated ones. + * + * Transformation reference: http://sylvana.net/jpegcrop/exif_orientation.html. + * + * @param img {Jimp} a Jimp image object + * @returns {function} transformation function for transformBitmap(). + */ +function getExifOrientationTransformation(img) { + const w = img.getWidth(); + const h = img.getHeight(); + switch (getExifOrientation(img)) { + case 1: + // Horizontal (normal) + // does not need to be supported here + return null; + case 2: + // Mirror horizontal + return function (x, y) { + return [w - x - 1, y]; + }; + case 3: + // Rotate 180 + return function (x, y) { + return [w - x - 1, h - y - 1]; + }; + case 4: + // Mirror vertical + return function (x, y) { + return [x, h - y - 1]; + }; + case 5: + // Mirror horizontal and rotate 270 CW + return function (x, y) { + return [y, x]; + }; + case 6: + // Rotate 90 CW + return function (x, y) { + return [y, h - x - 1]; + }; + case 7: + // Mirror horizontal and rotate 90 CW + return function (x, y) { + return [w - y - 1, h - x - 1]; + }; + case 8: + // Rotate 270 CW + return function (x, y) { + return [w - y - 1, x]; + }; + default: + return null; + } +} + +/* + * Transforms bitmap in place (moves pixels around) according to given + * transformation function. + * + * @param img {Jimp} a Jimp image object, which bitmap is supposed to + * be transformed + * @param width {number} bitmap width after the transformation + * @param height {number} bitmap height after the transformation + * @param transformation {function} transformation function which defines pixel + * mapping between new and source bitmap. It takes a pair of coordinates + * in the target, and returns a respective pair of coordinates in + * the source bitmap, i.e. has following form: + * `function(new_x, new_y) { return [src_x, src_y] }`. + */ +function transformBitmap(img, width, height, transformation) { + // Underscore-prefixed values are related to the source bitmap + // Their counterparts with no prefix are related to the target bitmap + const _data = img.bitmap.data; + const _width = img.bitmap.width; + const data = Buffer.alloc(_data.length); + for (let x = 0; x < width; x++) { + for (let y = 0; y < height; y++) { + const [_x, _y] = transformation(x, y); + const idx = width * y + x << 2; + const _idx = _width * _y + _x << 2; + const pixel = _data.readUInt32BE(_idx); + data.writeUInt32BE(pixel, idx); + } + } + img.bitmap.data = data; + img.bitmap.width = width; + img.bitmap.height = height; +} + +/* + * Automagically rotates an image based on its EXIF data (if present). + * @param img {Jimp} a Jimp image object + */ +function exifRotate(img) { + if (getExifOrientation(img) < 2) return; + const transformation = getExifOrientationTransformation(img); + const swapDimensions = getExifOrientation(img) > 4; + const newWidth = swapDimensions ? img.bitmap.height : img.bitmap.width; + const newHeight = swapDimensions ? img.bitmap.width : img.bitmap.height; + transformBitmap(img, newWidth, newHeight, transformation); +} + +// parses a bitmap from the constructor to the JIMP bitmap property +export async function parseBitmap(data, path, cb) { + const mime = await getMIMEFromBuffer(data, path); + if (typeof mime !== "string") { + return cb(new Error("Could not find MIME for Buffer <" + path + ">")); + } + this._originalMime = mime.toLowerCase(); + try { + const mime = this.getMIME(); + if (this.constructor.decoders[mime]) { + this.bitmap = this.constructor.decoders[mime](data); + } else { + return throwError.call(this, "Unsupported MIME type: " + mime, cb); + } + } catch (error) { + return cb.call(this, error, this); + } + try { + this._exif = EXIFParser.create(data).parse(); + exifRotate(this); // EXIF data + } catch (error) { + /* meh */ + } + cb.call(this, null, this); + return this; +} +function compositeBitmapOverBackground(Jimp, image) { + return new Jimp(image.bitmap.width, image.bitmap.height, image._background).composite(image, 0, 0).bitmap; +} + +/** + * Converts the image to a buffer + * @param {(string|number)} mime the mime type of the image buffer to be created + * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument + * @returns {Jimp} this for chaining of methods + */ +export function getBuffer(mime, cb) { + if (mime === constants.AUTO) { + // allow auto MIME detection + mime = this.getMIME(); + } + if (typeof mime !== "string") { + return throwError.call(this, "mime must be a string", cb); + } + if (typeof cb !== "function") { + return throwError.call(this, "cb must be a function", cb); + } + mime = mime.toLowerCase(); + if (this._rgba && this.constructor.hasAlpha[mime]) { + this.bitmap.data = Buffer.from(this.bitmap.data); + } else { + // when format doesn't support alpha + // composite onto a new image so that the background shows through alpha channels + this.bitmap.data = compositeBitmapOverBackground(this.constructor, this).data; + } + if (this.constructor.encoders[mime]) { + const buffer = this.constructor.encoders[mime](this); + // Typically, buffers return a string or map. However, the gif library "gifwrap" seemingly returns promises. + if (buffer instanceof Promise) { + // trigger the callback when the promise has been resolved + buffer.then(buff => { + cb.call(this, null, buff); + }); + } else { + cb.call(this, null, buffer); + } + } else { + return throwError.call(this, "Unsupported MIME type: " + mime, cb); + } + return this; +} +export function getBufferAsync(mime) { + return promisify(getBuffer, this, mime); +} +//# sourceMappingURL=image-bitmap.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/utils/image-bitmap.js.map b/node_modules/@jimp/core/es/utils/image-bitmap.js.map new file mode 100644 index 00000000..10277e5d --- /dev/null +++ b/node_modules/@jimp/core/es/utils/image-bitmap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"image-bitmap.js","names":["FileType","EXIFParser","throwError","constants","MIME","promisify","getMIMEFromBuffer","buffer","path","fileTypeFromBuffer","fromBuffer","mime","getType","getExifOrientation","img","_exif","tags","Orientation","getExifOrientationTransformation","w","getWidth","h","getHeight","x","y","transformBitmap","width","height","transformation","_data","bitmap","data","_width","Buffer","alloc","length","_x","_y","idx","_idx","pixel","readUInt32BE","writeUInt32BE","exifRotate","swapDimensions","newWidth","newHeight","parseBitmap","cb","Error","_originalMime","toLowerCase","getMIME","constructor","decoders","call","error","create","parse","compositeBitmapOverBackground","Jimp","image","_background","composite","getBuffer","AUTO","_rgba","hasAlpha","from","encoders","Promise","then","buff","getBufferAsync"],"sources":["../../src/utils/image-bitmap.js"],"sourcesContent":["import FileType from \"file-type\";\n\nimport EXIFParser from \"exif-parser\";\nimport { throwError } from \"@jimp/utils\";\n\nimport * as constants from \"../constants\";\nimport * as MIME from \"./mime\";\nimport promisify from \"./promisify\";\n\nasync function getMIMEFromBuffer(buffer, path) {\n const fileTypeFromBuffer = await FileType.fromBuffer(buffer);\n\n if (fileTypeFromBuffer) {\n // If fileType returns something for buffer, then return the mime given\n return fileTypeFromBuffer.mime;\n }\n\n if (path) {\n // If a path is supplied, and fileType yields no results, then retry with MIME\n // Path can be either a file path or a url\n return MIME.getType(path);\n }\n\n return null;\n}\n\n/*\n * Obtains image orientation from EXIF metadata.\n *\n * @param img {Jimp} a Jimp image object\n * @returns {number} a number 1-8 representing EXIF orientation,\n * in particular 1 if orientation tag is missing\n */\nfunction getExifOrientation(img) {\n return (img._exif && img._exif.tags && img._exif.tags.Orientation) || 1;\n}\n\n/**\n * Returns a function which translates EXIF-rotated coordinates into\n * non-rotated ones.\n *\n * Transformation reference: http://sylvana.net/jpegcrop/exif_orientation.html.\n *\n * @param img {Jimp} a Jimp image object\n * @returns {function} transformation function for transformBitmap().\n */\nfunction getExifOrientationTransformation(img) {\n const w = img.getWidth();\n const h = img.getHeight();\n\n switch (getExifOrientation(img)) {\n case 1: // Horizontal (normal)\n // does not need to be supported here\n return null;\n\n case 2: // Mirror horizontal\n return function (x, y) {\n return [w - x - 1, y];\n };\n\n case 3: // Rotate 180\n return function (x, y) {\n return [w - x - 1, h - y - 1];\n };\n\n case 4: // Mirror vertical\n return function (x, y) {\n return [x, h - y - 1];\n };\n\n case 5: // Mirror horizontal and rotate 270 CW\n return function (x, y) {\n return [y, x];\n };\n\n case 6: // Rotate 90 CW\n return function (x, y) {\n return [y, h - x - 1];\n };\n\n case 7: // Mirror horizontal and rotate 90 CW\n return function (x, y) {\n return [w - y - 1, h - x - 1];\n };\n\n case 8: // Rotate 270 CW\n return function (x, y) {\n return [w - y - 1, x];\n };\n\n default:\n return null;\n }\n}\n\n/*\n * Transforms bitmap in place (moves pixels around) according to given\n * transformation function.\n *\n * @param img {Jimp} a Jimp image object, which bitmap is supposed to\n * be transformed\n * @param width {number} bitmap width after the transformation\n * @param height {number} bitmap height after the transformation\n * @param transformation {function} transformation function which defines pixel\n * mapping between new and source bitmap. It takes a pair of coordinates\n * in the target, and returns a respective pair of coordinates in\n * the source bitmap, i.e. has following form:\n * `function(new_x, new_y) { return [src_x, src_y] }`.\n */\nfunction transformBitmap(img, width, height, transformation) {\n // Underscore-prefixed values are related to the source bitmap\n // Their counterparts with no prefix are related to the target bitmap\n const _data = img.bitmap.data;\n const _width = img.bitmap.width;\n\n const data = Buffer.alloc(_data.length);\n\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n const [_x, _y] = transformation(x, y);\n\n const idx = (width * y + x) << 2;\n const _idx = (_width * _y + _x) << 2;\n\n const pixel = _data.readUInt32BE(_idx);\n data.writeUInt32BE(pixel, idx);\n }\n }\n\n img.bitmap.data = data;\n img.bitmap.width = width;\n img.bitmap.height = height;\n}\n\n/*\n * Automagically rotates an image based on its EXIF data (if present).\n * @param img {Jimp} a Jimp image object\n */\nfunction exifRotate(img) {\n if (getExifOrientation(img) < 2) return;\n\n const transformation = getExifOrientationTransformation(img);\n const swapDimensions = getExifOrientation(img) > 4;\n\n const newWidth = swapDimensions ? img.bitmap.height : img.bitmap.width;\n const newHeight = swapDimensions ? img.bitmap.width : img.bitmap.height;\n\n transformBitmap(img, newWidth, newHeight, transformation);\n}\n\n// parses a bitmap from the constructor to the JIMP bitmap property\nexport async function parseBitmap(data, path, cb) {\n const mime = await getMIMEFromBuffer(data, path);\n\n if (typeof mime !== \"string\") {\n return cb(new Error(\"Could not find MIME for Buffer <\" + path + \">\"));\n }\n\n this._originalMime = mime.toLowerCase();\n\n try {\n const mime = this.getMIME();\n\n if (this.constructor.decoders[mime]) {\n this.bitmap = this.constructor.decoders[mime](data);\n } else {\n return throwError.call(this, \"Unsupported MIME type: \" + mime, cb);\n }\n } catch (error) {\n return cb.call(this, error, this);\n }\n\n try {\n this._exif = EXIFParser.create(data).parse();\n exifRotate(this); // EXIF data\n } catch (error) {\n /* meh */\n }\n\n cb.call(this, null, this);\n\n return this;\n}\n\nfunction compositeBitmapOverBackground(Jimp, image) {\n return new Jimp(\n image.bitmap.width,\n image.bitmap.height,\n image._background\n ).composite(image, 0, 0).bitmap;\n}\n\n/**\n * Converts the image to a buffer\n * @param {(string|number)} mime the mime type of the image buffer to be created\n * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument\n * @returns {Jimp} this for chaining of methods\n */\nexport function getBuffer(mime, cb) {\n if (mime === constants.AUTO) {\n // allow auto MIME detection\n mime = this.getMIME();\n }\n\n if (typeof mime !== \"string\") {\n return throwError.call(this, \"mime must be a string\", cb);\n }\n\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", cb);\n }\n\n mime = mime.toLowerCase();\n\n if (this._rgba && this.constructor.hasAlpha[mime]) {\n this.bitmap.data = Buffer.from(this.bitmap.data);\n } else {\n // when format doesn't support alpha\n // composite onto a new image so that the background shows through alpha channels\n this.bitmap.data = compositeBitmapOverBackground(\n this.constructor,\n this\n ).data;\n }\n\n if (this.constructor.encoders[mime]) {\n const buffer = this.constructor.encoders[mime](this);\n // Typically, buffers return a string or map. However, the gif library \"gifwrap\" seemingly returns promises.\n if (buffer instanceof Promise) {\n // trigger the callback when the promise has been resolved\n buffer.then((buff) => {\n cb.call(this, null, buff);\n });\n } else {\n cb.call(this, null, buffer);\n }\n } else {\n return throwError.call(this, \"Unsupported MIME type: \" + mime, cb);\n }\n\n return this;\n}\n\nexport function getBufferAsync(mime) {\n return promisify(getBuffer, this, mime);\n}\n"],"mappings":"AAAA,OAAOA,QAAQ,MAAM,WAAW;AAEhC,OAAOC,UAAU,MAAM,aAAa;AACpC,SAASC,UAAU,QAAQ,aAAa;AAExC,OAAO,KAAKC,SAAS,MAAM,cAAc;AACzC,OAAO,KAAKC,IAAI,MAAM,QAAQ;AAC9B,OAAOC,SAAS,MAAM,aAAa;AAEnC,eAAeC,iBAAiB,CAACC,MAAM,EAAEC,IAAI,EAAE;EAC7C,MAAMC,kBAAkB,GAAG,MAAMT,QAAQ,CAACU,UAAU,CAACH,MAAM,CAAC;EAE5D,IAAIE,kBAAkB,EAAE;IACtB;IACA,OAAOA,kBAAkB,CAACE,IAAI;EAChC;EAEA,IAAIH,IAAI,EAAE;IACR;IACA;IACA,OAAOJ,IAAI,CAACQ,OAAO,CA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I,EAAErD,IAAI,CAAC;AACzC"} \ No newline at end of file diff --git a/node_modules/@jimp/core/es/utils/mime.js b/node_modules/@jimp/core/es/utils/mime.js new file mode 100644 index 00000000..55e0c51e --- /dev/null +++ b/node_modules/@jimp/core/es/utils/mime.js @@ -0,0 +1,25 @@ +const mimeTypes = {}; +const findType = extension => Object.entries(mimeTypes).find(type => type[1].includes(extension)) || []; +export const addType = (mime, extensions) => { + mimeTypes[mime] = extensions; +}; + +/** + * Lookup a mime type based on extension + * @param {string} path path to find extension for + * @returns {string} mime found mime type + */ +export const getType = path => { + const pathParts = path.split("/").slice(-1); + const extension = pathParts[pathParts.length - 1].split(".").pop(); + const type = findType(extension); + return type[0]; +}; + +/** + * Return file extension associated with a mime type + * @param {string} type mime type to look up + * @returns {string} extension file extension + */ +export const getExtension = type => (mimeTypes[type.toLowerCase()] || [])[0]; +//# sourceMappingURL=mime.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/utils/mime.js.map b/node_modules/@jimp/core/es/utils/mime.js.map new file mode 100644 index 00000000..896500f2 --- /dev/null +++ b/node_modules/@jimp/core/es/utils/mime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mime.js","names":["mimeTypes","findType","extension","Object","entries","find","type","includes","addType","mime","extensions","getType","path","pathParts","split","slice","length","pop","getExtension","toLowerCase"],"sources":["../../src/utils/mime.js"],"sourcesContent":["const mimeTypes = {};\n\nconst findType = (extension) =>\n Object.entries(mimeTypes).find((type) => type[1].includes(extension)) || [];\n\nexport const addType = (mime, extensions) => {\n mimeTypes[mime] = extensions;\n};\n\n/**\n * Lookup a mime type based on extension\n * @param {string} path path to find extension for\n * @returns {string} mime found mime type\n */\nexport const getType = (path) => {\n const pathParts = path.split(\"/\").slice(-1);\n const extension = pathParts[pathParts.length - 1].split(\".\").pop();\n const type = findType(extension);\n\n return type[0];\n};\n\n/**\n * Return file extension associated with a mime type\n * @param {string} type mime type to look up\n * @returns {string} extension file extension\n */\nexport const getExtension = (type) => (mimeTypes[type.toLowerCase()] || [])[0];\n"],"mappings":"AAAA,MAAMA,SAAS,GAAG,CAAC,CAAC;AAEpB,MAAMC,QAAQ,GAAIC,SAAS,IACzBC,MAAM,CAACC,OAAO,CAACJ,SAAS,CAAC,CAACK,IAAI,CAAEC,IAAI,IAAKA,IAAI,CAAC,CAAC,CAAC,CAACC,QAAQ,CAACL,SAAS,CAAC,CAAC,IAAI,EAAE;AAE7E,OAAO,MAAMM,OAAO,GAAG,CAACC,IAAI,EAAEC,UAAU,KAAK;EAC3CV,SAAS,CAACS,IAAI,CAAC,GAAGC,UAAU;AAC9B,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,OAAO,GAAIC,IAAI,IAAK;EAC/B,MAAMC,SAAS,GAAGD,IAAI,CAACE,KAAK,CAAC,GAAG,CAAC,CAACC,KAAK,CAAC,CAAC,CAAC,CAAC;EAC3C,MAAMb,SAAS,GAAGW,SAAS,CAACA,SAAS,CAACG,MAAM,GAAG,CAAC,CAAC,CAACF,KAAK,CAAC,GAAG,CAAC,CAACG,GAAG,EAAE;EAClE,MAAMX,IAAI,GAAGL,QAAQ,CAACC,SAAS,CAAC;EAEhC,OAAOI,IAAI,CAAC,CAAC,CAAC;AAChB,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMY,YAAY,GAAIZ,IAAI,IAAK,CAACN,SAAS,CAACM,IAAI,CAACa,WAAW,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/core/es/utils/promisify.js b/node_modules/@jimp/core/es/utils/promisify.js new file mode 100644 index 00000000..c40350de --- /dev/null +++ b/node_modules/@jimp/core/es/utils/promisify.js @@ -0,0 +1,16 @@ +const promisify = function (fun, ctx) { + for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } + return new Promise((resolve, reject) => { + args.push((err, data) => { + if (err) { + reject(err); + } + resolve(data); + }); + fun.bind(ctx)(...args); + }); +}; +export default promisify; +//# sourceMappingURL=promisify.js.map \ No newline at end of file diff --git a/node_modules/@jimp/core/es/utils/promisify.js.map b/node_modules/@jimp/core/es/utils/promisify.js.map new file mode 100644 index 00000000..9b619756 --- /dev/null +++ b/node_modules/@jimp/core/es/utils/promisify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promisify.js","names":["promisify","fun","ctx","args","Promise","resolve","reject","push","err","data","bind"],"sources":["../../src/utils/promisify.js"],"sourcesContent":["const promisify = (fun, ctx, ...args) =>\n new Promise((resolve, reject) => {\n args.push((err, data) => {\n if (err) {\n reject(err);\n }\n\n resolve(data);\n });\n fun.bind(ctx)(...args);\n });\n\nexport default promisify;\n"],"mappings":"AAAA,MAAMA,SAAS,GAAG,UAACC,GAAG,EAAEC,GAAG;EAAA,kCAAKC,IAAI;IAAJA,IAAI;EAAA;EAAA,OAClC,IAAIC,OAAO,CAAC,CAACC,OAAO,EAAEC,MAAM,KAAK;IAC/BH,IAAI,CAACI,IAAI,CAAC,CAACC,GAAG,EAAEC,IAAI,KAAK;MACvB,IAAID,GAAG,EAAE;QACPF,MAAM,CAACE,GAAG,CAAC;MACb;MAEAH,OAAO,CAACI,IAAI,CAAC;IACf,CAAC,CAAC;IACFR,GAAG,CAACS,IAAI,CAACR,GAAG,CAAC,CAAC,GAAGC,IAAI,CAAC;EACxB,CAAC,CAAC;AAAA;AAEJ,eAAeH,SAAS"} \ No newline at end of file diff --git a/node_modules/@jimp/core/node_modules/buffer/AUTHORS.md b/node_modules/@jimp/core/node_modules/buffer/AUTHORS.md new file mode 100644 index 00000000..22eb1712 --- /dev/null +++ b/node_modules/@jimp/core/node_modules/buffer/AUTHORS.md @@ -0,0 +1,70 @@ +# Authors + +#### Ordered by first contribution. + +- Romain Beauxis (toots@rastageeks.org) +- Tobias Koppers (tobias.koppers@googlemail.com) +- Janus (ysangkok@gmail.com) +- Rainer Dreyer (rdrey1@gmail.com) +- Tõnis Tiigi (tonistiigi@gmail.com) +- James Halliday (mail@substack.net) +- Michael Williamson (mike@zwobble.org) +- elliottcable (github@elliottcable.name) +- rafael (rvalle@livelens.net) +- Andrew Kelley (superjoe30@gmail.com) +- Andreas Madsen (amwebdk@gmail.com) +- Mike Brevoort (mike.brevoort@pearson.com) +- Brian White (mscdex@mscdex.net) +- Feross Aboukhadijeh (feross@feross.org) +- Ruben Verborgh (ruben@verborgh.org) +- eliang (eliang.cs@gmail.com) +- Jesse Tane (jesse.tane@gmail.com) +- Alfonso Boza (alfonso@cloud.com) +- Mathias Buus (mathiasbuus@gmail.com) +- Devon Govett (devongovett@gmail.com) +- Daniel Cousens (github@dcousens.com) +- Joseph Dykstra (josephdykstra@gmail.com) +- Parsha Pourkhomami (parshap+git@gmail.com) +- Damjan Košir (damjan.kosir@gmail.com) +- daverayment (dave.rayment@gmail.com) +- kawanet (u-suke@kawa.net) +- Linus Unnebäck (linus@folkdatorn.se) +- Nolan Lawson (nolan.lawson@gmail.com) +- Calvin Metcalf (calvin.metcalf@gmail.com) +- Koki Takahashi (hakatasiloving@gmail.com) +- Guy Bedford (guybedford@gmail.com) +- Jan Schär (jscissr@gmail.com) +- RaulTsc (tomescu.raul@gmail.com) +- Matthieu Monsch (monsch@alum.mit.edu) +- Dan Ehrenberg (littledan@chromium.org) +- Kirill Fomichev (fanatid@ya.ru) +- Yusuke Kawasaki (u-suke@kawa.net) +- DC (dcposch@dcpos.ch) +- John-David Dalton (john.david.dalton@gmail.com) +- adventure-yunfei (adventure030@gmail.com) +- Emil Bay (github@tixz.dk) +- Sam Sudar (sudar.sam@gmail.com) +- Volker Mische (volker.mische@gmail.com) +- David Walton (support@geekstocks.com) +- Сковорода Никита Андреевич (chalkerx@gmail.com) +- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) +- ukstv (sergey.ukustov@machinomy.com) +- Renée Kooi (renee@kooi.me) +- ranbochen (ranbochen@qq.com) +- Vladimir Borovik (bobahbdb@gmail.com) +- greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) +- kumavis (aaron@kumavis.me) +- Sergey Ukustov (sergey.ukustov@machinomy.com) +- Fei Liu (liu.feiwood@gmail.com) +- Blaine Bublitz (blaine.bublitz@gmail.com) +- clement (clement@seald.io) +- Koushik Dutta (koushd@gmail.com) +- Jordan Harband (ljharb@gmail.com) +- Niklas Mischkulnig (mischnic@users.noreply.github.com) +- Nikolai Vavilov (vvnicholas@gmail.com) +- Fedor Nezhivoi (gyzerok@users.noreply.github.com) +- Peter Newman (peternewman@users.noreply.github.com) +- mathmakgakpak (44949126+mathmakgakpak@users.noreply.github.com) +- jkkang (jkkang@smartauth.kr) + +#### Generated by bin/update-authors.sh. diff --git a/node_modules/@jimp/core/node_modules/buffer/LICENSE b/node_modules/@jimp/core/node_modules/buffer/LICENSE new file mode 100644 index 00000000..d6bf75dc --- /dev/null +++ b/node_modules/@jimp/core/node_modules/buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, 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/@jimp/core/node_modules/buffer/README.md b/node_modules/@jimp/core/node_modules/buffer/README.md new file mode 100644 index 00000000..9a23d7cf --- /dev/null +++ b/node_modules/@jimp/core/node_modules/buffer/README.md @@ -0,0 +1,410 @@ +# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/buffer/master.svg +[travis-url]: https://travis-ci.org/feross/buffer +[npm-image]: https://img.shields.io/npm/v/buffer.svg +[npm-url]: https://npmjs.org/package/buffer +[downloads-image]: https://img.shields.io/npm/dm/buffer.svg +[downloads-url]: https://npmjs.org/package/buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### The buffer module from [node.js](https://nodejs.org/), for the browser. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg +[saucelabs-url]: https://saucelabs.com/u/buffer + +With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. + +The goal is to provide an API that is 100% identical to +[node's Buffer API](https://nodejs.org/api/buffer.html). Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +## features + +- Manipulate binary data like a boss, in all browsers! +- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) +- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) +- Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) +- Preserves Node API exactly, with one minor difference (see below) +- Square-bracket `buf[4]` notation works! +- Does not modify any browser prototypes or put anything on `window` +- Comprehensive test suite (including all buffer tests from node.js core) + +## install + +To use this module directly (without browserify), install it: + +```bash +npm install buffer +``` + +This module was previously called **native-buffer-browserify**, but please use **buffer** +from now on. + +If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). + +## usage + +The module's API is identical to node's `Buffer` API. Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +As mentioned above, `require('buffer')` or use the `Buffer` global with +[browserify](http://browserify.org) and this module will automatically be included +in your bundle. Almost any npm module will work in the browser, even if it assumes that +the node `Buffer` API will be available. + +To depend on this module explicitly (without browserify), require it like this: + +```js +var Buffer = require('buffer/').Buffer // note: the trailing slash is important! +``` + +To require this module explicitly, use `require('buffer/')` which tells the node.js module +lookup algorithm (also used by browserify) to use the **npm module** named `buffer` +instead of the **node.js core** module named `buffer`! + + +## how does it work? + +The Buffer constructor returns instances of `Uint8Array` that have their prototype +changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, +so the returned instances will have all the node `Buffer` methods and the +`Uint8Array` methods. Square bracket notation works as expected -- it returns a +single octet. + +The `Uint8Array` prototype remains unmodified. + + +## tracking the latest node api + +This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer +API is considered **stable** in the +[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), +so it is unlikely that there will ever be breaking changes. +Nonetheless, when/if the Buffer API changes in node, this module's API will change +accordingly. + +## related packages + +- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer +- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer +- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package + +## conversion packages + +### convert typed array to buffer + +Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. + +### convert buffer to typed array + +`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. + +### convert blob to buffer + +Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. + +### convert buffer to blob + +To convert a `Buffer` to a `Blob`, use the `Blob` constructor: + +```js +var blob = new Blob([ buffer ]) +``` + +Optionally, specify a mimetype: + +```js +var blob = new Blob([ buffer ], { type: 'text/html' }) +``` + +### convert arraybuffer to buffer + +To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. + +```js +var buffer = Buffer.from(arrayBuffer) +``` + +### convert buffer to arraybuffer + +To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): + +```js +var arrayBuffer = buffer.buffer.slice( + buffer.byteOffset, buffer.byteOffset + buffer.byteLength +) +``` + +Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. + +## performance + +See perf tests in `/perf`. + +`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a +sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will +always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, +which is included to compare against. + +NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. + +### Chrome 38 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | +| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | +| | | | | +| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | +| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | +| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | +| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | +| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | +| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | +| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | +| | | | | +| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | +| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | +| | | | | +| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | +| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | +| | | | | +| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | +| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | +| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | + + +### Firefox 33 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | +| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | +| | | | | +| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | +| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | +| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | +| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | +| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | +| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | +| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | +| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | +| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | +| | | | | +| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | +| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | +| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | + +### Safari 8 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | +| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | +| | | | | +| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | +| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | +| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | +| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | +| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | +| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | +| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | +| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | +| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | +| | | | | +| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | +| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | +| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | + + +### Node 0.11.14 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | +| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | +| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | +| | | | | +| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | +| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | +| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | +| | | | | +| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | +| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | +| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | +| | | | | +| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | +| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | +| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | +| | | | | +| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | +| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | +| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | +| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | +| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | +| | | | | +| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | +| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | +| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | +| | | | | +| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | +| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | +| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | +| | | | | +| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | +| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | +| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | +| | | | | +| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | +| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | +| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | +| | | | | +| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | +| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | +| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | + +### iojs 1.8.1 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | +| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | +| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | +| | | | | +| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | +| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | +| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | +| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | +| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | +| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | +| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | +| | | | | +| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | +| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | +| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | +| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | +| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | +| | | | | +| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | +| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | +| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | +| | | | | +| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | +| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | +| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | +| | | | | +| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | +| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | +| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | +| | | | | +| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | +| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | +| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | +| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | +| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | +| | | | | + +## Testing the project + +First, install the project: + + npm install + +Then, to run tests in Node.js, run: + + npm run test-node + +To test locally in a browser, you can run: + + npm run test-browser-es5-local # For ES5 browsers that don't support ES6 + npm run test-browser-es6-local # For ES6 compliant browsers + +This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). + +To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: + + npm test + +This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. + +## JavaScript Standard Style + +This module uses [JavaScript Standard Style](https://github.com/feross/standard). + +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +To test that the code conforms to the style, `npm install` and run: + + ./node_modules/.bin/standard + +## credit + +This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). + +## Security Policies and Procedures + +The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/node_modules/@jimp/core/node_modules/buffer/index.d.ts b/node_modules/@jimp/core/node_modules/buffer/index.d.ts new file mode 100644 index 00000000..5d1a804e --- /dev/null +++ b/node_modules/@jimp/core/node_modules/buffer/index.d.ts @@ -0,0 +1,186 @@ +export class Buffer extends Uint8Array { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer | Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initializing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; +} diff --git a/node_modules/@jimp/core/node_modules/buffer/index.js b/node_modules/@jimp/core/node_modules/buffer/index.js new file mode 100644 index 00000000..609cf311 --- /dev/null +++ b/node_modules/@jimp/core/node_modules/buffer/index.js @@ -0,0 +1,1817 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + var proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +var hexSliceLookupTable = (function () { + var alphabet = '0123456789abcdef' + var table = new Array(256) + for (var i = 0; i < 16; ++i) { + var i16 = i * 16 + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() diff --git a/node_modules/@jimp/core/node_modules/buffer/package.json b/node_modules/@jimp/core/node_modules/buffer/package.json new file mode 100644 index 00000000..3b1b4986 --- /dev/null +++ b/node_modules/@jimp/core/node_modules/buffer/package.json @@ -0,0 +1,96 @@ +{ + "name": "buffer", + "description": "Node.js Buffer API, for the browser", + "version": "5.7.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/buffer/issues" + }, + "contributors": [ + "Romain Beauxis ", + "James Halliday " + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + }, + "devDependencies": { + "airtap": "^3.0.0", + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "concat-stream": "^2.0.0", + "hyperquest": "^2.1.3", + "is-buffer": "^2.0.4", + "is-nan": "^1.3.0", + "split": "^1.0.1", + "standard": "*", + "tape": "^5.0.1", + "through2": "^4.0.2", + "uglify-js": "^3.11.3" + }, + "homepage": "https://github.com/feross/buffer", + "jspm": { + "map": { + "./index.js": { + "node": "@node/buffer" + } + } + }, + "keywords": [ + "arraybuffer", + "browser", + "browserify", + "buffer", + "compatible", + "dataview", + "uint8array" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/buffer.git" + }, + "scripts": { + "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", + "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", + "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", + "test": "standard && node ./bin/test.js", + "test-browser-es5": "airtap -- test/*.js", + "test-browser-es5-local": "airtap --local -- test/*.js", + "test-browser-es6": "airtap -- test/*.js test/node/*.js", + "test-browser-es6-local": "airtap --local -- test/*.js test/node/*.js", + "test-node": "tape test/*.js test/node/*.js", + "update-authors": "./bin/update-authors.sh" + }, + "standard": { + "ignore": [ + "test/node/**/*.js", + "test/common.js", + "test/_polyfill.js", + "perf/**/*.js" + ], + "globals": [ + "SharedArrayBuffer" + ] + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/@jimp/core/package.json b/node_modules/@jimp/core/package.json new file mode 100644 index 00000000..7558b3eb --- /dev/null +++ b/node_modules/@jimp/core/package.json @@ -0,0 +1,45 @@ +{ + "name": "@jimp/core", + "version": "0.22.12", + "description": "Jimp core", + "main": "dist/index.js", + "module": "es/index.js", + "types": "types/index.d.ts", + "sideEffects": false, + "files": [ + "dist", + "es", + "index.d.ts", + "fonts", + "types" + ], + "repository": "jimp-dev/jimp", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "Oliver Moran ", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "any-base": "^1.1.0", + "buffer": "^5.2.0", + "exif-parser": "^0.1.12", + "file-type": "^16.5.4", + "isomorphic-fetch": "^3.0.0", + "pixelmatch": "^4.0.2", + "tinycolor2": "^1.6.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/core/types/etc.d.ts b/node_modules/@jimp/core/types/etc.d.ts new file mode 100644 index 00000000..e13192e6 --- /dev/null +++ b/node_modules/@jimp/core/types/etc.d.ts @@ -0,0 +1,93 @@ +import { Jimp } from "./jimp"; + +export interface Image { + bitmap: Bitmap; +} + +export type DecoderFn = (data: Buffer) => Bitmap; +export type EncoderFn = ( + image: ImageType +) => Buffer; + +export type GenericCallback = ( + this: TThis, + err: Error | null, + value: T +) => U; + +/** + * `jimp` must be defined otherwise `this` will not apply properly + * for custom configurations where plugins and types are needed + */ +export type ImageCallback = ( + this: jimp, + err: Error | null, + value: jimp, + coords: { + x: number; + y: number; + } +) => any; + +type BlendMode = { + mode: string; + opacitySource: number; + opacityDest: number; +}; + +type ChangeName = "background" | "scan" | "crop"; + +type ListenableName = + | "any" + | "initialized" + | "before-change" + | "changed" + | "before-clone" + | "cloned" + | ChangeName; + +type ListenerData = T extends "any" + ? any + : T extends ChangeName + ? { + eventName: "before-change" | "changed"; + methodName: T; + [key: string]: any; + } + : { + eventName: T; + methodName: T extends "initialized" + ? "constructor" + : T extends "before-change" | "changed" + ? ChangeName + : T extends "before-clone" | "cloned" + ? "clone" + : any; + }; + +type URLOptions = { + url: string; + compression?: boolean; + headers: { + [key: string]: any; + }; +}; + +export interface Bitmap { + data: Buffer; + width: number; + height: number; +} + +export interface RGB { + r: number; + g: number; + b: number; +} + +export interface RGBA { + r: number; + g: number; + b: number; + a: number; +} diff --git a/node_modules/@jimp/core/types/functions.d.ts b/node_modules/@jimp/core/types/functions.d.ts new file mode 100644 index 00000000..de74902e --- /dev/null +++ b/node_modules/@jimp/core/types/functions.d.ts @@ -0,0 +1,17 @@ +import { Jimp } from "./jimp"; + +export function addConstants( + constants: [string, string | number], + jimpInstance?: Jimp +): void; +export function addJimpMethods( + methods: [string, Function], + jimpInstance?: Jimp +): void; +export function jimpEvMethod( + methodName: string, + evName: string, + method: Function +): void; +export function jimpEvChange(methodName: string, method: Function): void; +export function addType(mime: string, extensions: string[]): void; diff --git a/node_modules/@jimp/core/types/index.d.ts b/node_modules/@jimp/core/types/index.d.ts new file mode 100644 index 00000000..88bd53a7 --- /dev/null +++ b/node_modules/@jimp/core/types/index.d.ts @@ -0,0 +1,9 @@ +export * from "./etc"; +export * from "./functions"; +export * from "./plugins"; +export * from "./utils"; +import { Jimp, JimpConstructors } from "./jimp"; + +export { Jimp, JimpConstructors }; +declare const defaultExp: Jimp; +export default defaultExp; diff --git a/node_modules/@jimp/core/types/jimp.d.ts b/node_modules/@jimp/core/types/jimp.d.ts new file mode 100644 index 00000000..3c3509ea --- /dev/null +++ b/node_modules/@jimp/core/types/jimp.d.ts @@ -0,0 +1,247 @@ +import { + Bitmap, + ImageCallback, + URLOptions, + ListenableName, + ListenerData, + GenericCallback, + BlendMode, + RGBA, + RGB, +} from "./etc"; + +interface DiffReturn { + percent: number; + image: This; +} + +interface ScanIteratorReturn { + x: number; + y: number; + idx: number; + image: This; +} + +export interface JimpConstructors { + prototype: Jimp; + // Constants + AUTO: -1; + // blend modes + BLEND_SOURCE_OVER: string; + BLEND_DESTINATION_OVER: string; + BLEND_MULTIPLY: string; + BLEND_ADD: string; + BLEND_SCREEN: string; + BLEND_OVERLAY: string; + BLEND_DARKEN: string; + BLEND_LIGHTEN: string; + BLEND_HARDLIGHT: string; + BLEND_DIFFERENCE: string; + BLEND_EXCLUSION: string; + // Align modes for cover, contain, bit masks + HORIZONTAL_ALIGN_LEFT: 1; + HORIZONTAL_ALIGN_CENTER: 2; + HORIZONTAL_ALIGN_RIGHT: 4; + VERTICAL_ALIGN_TOP: 8; + VERTICAL_ALIGN_MIDDLE: 16; + VERTICAL_ALIGN_BOTTOM: 32; + // Edge Handling + EDGE_EXTEND: 1; + EDGE_WRAP: 2; + EDGE_CROP: 3; + + // Constructors + new (path: string, cb?: ImageCallback): this["prototype"]; + new ( + urlOptions: URLOptions, + cb?: ImageCallback + ): this["prototype"]; + new (image: Jimp, cb?: ImageCallback): this["prototype"]; + new (data: Buffer, cb?: ImageCallback): this["prototype"]; + new (data: Bitmap, cb?: ImageCallback): this["prototype"]; + new ( + w: number, + h: number, + cb?: ImageCallback + ): this["prototype"]; + new ( + w: number, + h: number, + background?: number | string, + cb?: ImageCallback + ): this["prototype"]; + // For custom constructors when using Jimp.appendConstructorOption + new (...args: any[]): this["prototype"]; + + // Functions + /** + * I'd like to make `Args` generic and used in `run` and `test` but alas, + * it's not possible RN: + * https://github.com/microsoft/TypeScript/issues/26113 + */ + appendConstructorOption< + Args extends any[], + J extends Jimp = this["prototype"] + >( + name: string, + test: (...args: any[]) => boolean, + run: ( + this: J, + resolve: (jimp?: J) => any, + reject: (reason: Error) => any, + ...args: any[] + ) => any + ): void; + read( + path: string, + cb?: ImageCallback + ): Promise; + read( + image: Jimp, + cb?: ImageCallback + ): Promise; + read( + data: Buffer, + cb?: ImageCallback + ): Promise; + read( + w: number, + h: number, + background?: number | string, + cb?: ImageCallback + ): Promise; + create(path: string): Promise; + create(image: Jimp): Promise; + create(data: Buffer): Promise; + create( + w: number, + h: number, + background?: number | string + ): Promise; + rgbaToInt( + r: number, + g: number, + b: number, + a: number, + cb?: GenericCallback + ): number; + intToRGBA(i: number, cb?: GenericCallback): RGBA; + cssColorToHex(cssColor: string): number; + limit255(n: number): number; + diff( + img1: Jimp, + img2: Jimp, + threshold?: number + ): DiffReturn; + distance(img1: Jimp, img2: Jimp): number; + compareHashes(hash1: string, hash2: string): number; + colorDiff(rgba1: RGB, rgba2: RGB): number; + colorDiff(rgba1: RGBA, rgba2: RGBA): number; +} + +export interface Jimp { + // Properties + bitmap: Bitmap; + _rgba: boolean; + _background: number; + _originalMime: string; + // Methods + on( + event: T, + cb: (data: ListenerData) => any + ): any; + parseBitmap( + data: Buffer, + path: string | null | undefined, + cb?: ImageCallback + ): void; + hasAlpha(): boolean; + getHeight(): number; + getWidth(): number; + inspect(): string; + toString(): string; + getMIME(): string; + getExtension(): string; + distanceFromHash(hash: string): number; + write(path: string, cb?: ImageCallback): this; + writeAsync(path: string): Promise; + rgba(bool: boolean, cb?: ImageCallback): this; + getBase64(mime: string | JimpConstructors["AUTO"], cb: GenericCallback): this; + pHash: () => string; + getBase64Async(mime: string | JimpConstructors["AUTO"]): Promise; + hash(cb?: GenericCallback): string; + hash( + base: number | null | undefined, + cb?: GenericCallback + ): string; + getBuffer(mime: string, cb: GenericCallback): this; + getBufferAsync(mime: string): Promise; + getPixelIndex( + x: number, + y: number, + cb?: GenericCallback + ): number; + getPixelIndex( + x: number, + y: number, + edgeHandling: number, + cb?: GenericCallback + ): number; + getPixelColor( + x: number, + y: number, + cb?: GenericCallback + ): number; + getPixelColour( + x: number, + y: number, + cb?: GenericCallback + ): number; + setPixelColor( + hex: number, + x: number, + y: number, + cb?: ImageCallback + ): this; + setPixelColour( + hex: number, + x: number, + y: number, + cb?: ImageCallback + ): this; + clone(cb?: ImageCallback): this; + cloneQuiet(cb?: ImageCallback): this; + background(hex: number, cb?: ImageCallback): this; + backgroundQuiet(hex: number, cb?: ImageCallback): this; + scan( + x: number, + y: number, + w: number, + h: number, + f: (this: this, x: number, y: number, idx: number) => any, + cb?: ImageCallback + ): this; + scanQuiet( + x: number, + y: number, + w: number, + h: number, + f: (this: this, x: number, y: number, idx: number) => any, + cb?: ImageCallback + ): this; + scanIterator( + x: number, + y: number, + w: number, + h: number + ): IterableIterator>; + + // Effect methods + composite( + src: Jimp, + x: number, + y: number, + options?: BlendMode, + cb?: ImageCallback + ): this; +} diff --git a/node_modules/@jimp/core/types/plugins.d.ts b/node_modules/@jimp/core/types/plugins.d.ts new file mode 100644 index 00000000..62bf2ea9 --- /dev/null +++ b/node_modules/@jimp/core/types/plugins.d.ts @@ -0,0 +1,51 @@ +/** + * These files pertain to the typings of plugins or types + * + * They're not meant as utils to decode types, but rather + * the type definitons themsleves for plugins and types of various kinds + */ +import { Image, EncoderFn, DecoderFn } from "./etc"; + +import { Omit } from "./utils"; + +export type IllformedPlugin = Omit & { + class?: never; + constants?: never; +}; + +export interface WellFormedPlugin { + mime?: { + [MIME_TYPE: string]: string[]; + }; + hasAlpha?: { + [MIME_SPECIAL: string]: boolean; + }; + constants?: { + // Contants to assign to the Jimp instance + [MIME_SPECIAL: string]: any; + }; + decoders?: { + [MIME_TYPE: string]: DecoderFn; + }; + encoders?: { + // Jimp Image + [MIME_TYPE: string]: EncoderFn; + }; + // Extend the Jimp class with the following constants, etc + class?: any; +} + +type ClassOrConstantPlugin = WellFormedPlugin & + ( + | Required, "class">> + | Required, "constants">> + ); + +// A Jimp type requires mime, but not class +export type JimpType = WellFormedPlugin & + Required, "mime">>; + +// Jimp plugin either MUST have class OR constant or be illformed +export type JimpPlugin = + | ClassOrConstantPlugin + | IllformedPlugin; diff --git a/node_modules/@jimp/core/types/utils.d.ts b/node_modules/@jimp/core/types/utils.d.ts new file mode 100644 index 00000000..463321b9 --- /dev/null +++ b/node_modules/@jimp/core/types/utils.d.ts @@ -0,0 +1,132 @@ +import { JimpType, JimpPlugin } from "./plugins"; + +// This is required as providing type arrays gives a union of all the generic +// types in the array rather than an intersection +export type UnionToIntersection = ( + U extends any ? (k: U) => void : never +) extends (k: infer I) => void + ? I + : never; + +/** + * The values to be extracted from a WellFormedPlugin to put onto the Jimp instance + * Left loose as "any" in order to enable the GetPluginVal to work properly + */ +export type WellFormedValues = T extends { class: infer Class } + ? Class + : {}; + +/** + * The constants to be extracted from a WellFormedPlugin to put onto the Jimp instance + * Left loose as "any" in order to enable the GetPluginConstants to work properly + */ +export type WellFormedConstants = T extends { + constants: infer Constants; +} + ? Constants + : {}; + +// Util type for the functions that deal with `@jimp/custom` +// Must accept any or no props thanks to typing of the `plugins` intersected function +export type FunctionRet = Array<(...props: any[] | never) => T>; + +/** + * This conditional cannot be flipped. TS assumes that Q is `WellFormed` even + * it does not have the `class` or `constant` props. As a result, it will end + * up `undefined`. Because we're always extending `IllformedPlugin` on the + * plugins, this should work fine + */ +export type GetPluginVal = Q extends + | Required<{ class: any }> + | Required<{ constants: any }> + ? WellFormedValues + : Q; + +export type GetPluginConst = Q extends + | Required<{ class: any }> + | Required<{ constants: any }> + ? WellFormedConstants + : {}; + +export type GetPluginDecoders = Q extends + | Required<{ class: any }> + | Required<{ constants: any }> + ? Q extends { decoders: infer Decoders } + ? Decoders + : {} + : {}; + +export type GetPluginEncoders = Q extends + | Required<{ class: any }> + | Required<{ constants: any }> + ? Q extends { encoders: infer Encoders } + ? Encoders + : {} + : {}; + +type GetPluginFuncArrValues = + // Given an array of types infer `Q` (Q should be the type value) + PluginFuncArr extends ReadonlyArray + ? F extends () => infer Q + ? // Get the plugin value, may be ill-formed or well-formed + GetPluginVal + : // This should never be reached + undefined + : undefined; + +/** + * A helper type to get the values to be intersected with `Jimp` to give + * the proper typing given an array of functions for plugins and types + */ +export type GetIntersectionFromPlugins< + PluginFuncArr extends FunctionRet +> = UnionToIntersection< + Exclude, undefined> +>; + +type GetPluginFuncArrConsts = + // Given an array of types infer `Q` (Q should be the type value) + PluginFuncArr extends ReadonlyArray + ? F extends () => infer Q + ? // Get the plugin constants, may be ill-formed or well-formed + GetPluginConst + : // This should never be reached + undefined + : undefined; + +type GetPluginFuncArrEncoders = + // Given an array of types infer `Q` (Q should be the type value) + PluginFuncArr extends ReadonlyArray + ? F extends () => infer Q + ? // Get the plugin encoders, may be ill-formed or well-formed + GetPluginEncoders + : // This should never be reached + undefined + : undefined; + +type GetPluginFuncArrDecoders = + // Given an array of types infer `Q` (Q should be the type value) + PluginFuncArr extends ReadonlyArray + ? F extends () => infer Q + ? // Get the plugin decoders, may be ill-formed or well-formed + GetPluginDecoders + : // This should never be reached + undefined + : undefined; + +/** + * A helper type to get the statics to be intersected with `Jimp` to give + * the proper typing given an array of functions for plugins and types + */ +export type GetIntersectionFromPluginsStatics< + PluginFuncArr extends FunctionRet +> = UnionToIntersection> & { + encoders: UnionToIntersection>; + decoders: UnionToIntersection>; +}; + +/** + * While this was added to TS 3.5, in order to support down to TS 2.8, we need + * to export this and use it in sub-packges that utilize it + */ +export type Omit = Pick>; diff --git a/node_modules/@jimp/custom/CHANGELOG.md b/node_modules/@jimp/custom/CHANGELOG.md new file mode 100644 index 00000000..5f415137 --- /dev/null +++ b/node_modules/@jimp/custom/CHANGELOG.md @@ -0,0 +1,131 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.18.0 (Sun Feb 05 2023) + +### Release Notes + +#### switch from browserify to webpack ([#1140](https://github.com/jimp-dev/jimp/pull/1140)) + +This PR can be considered a breaking change as it remove the `jimp.min.js` file. + +Instead there is now only the `jimp.js` file and we ship source maps for it. + +We also configured the `browser` field so jimp will be automatically bundled better + +--- + +#### 💥 Breaking Change + +- switch from browserify to webpack [#1140](https://github.com/jimp-dev/jimp/pull/1140) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.10.0 (Mon Mar 30 2020) + +#### 🚀 Enhancement + +- Properly split constructor and instance types [#867](https://github.com/oliver-moran/jimp/pull/867) ([@forivall](https://github.com/forivall)) + +#### Authors: 1 + +- Emily Marigold Klassen ([@forivall](https://github.com/forivall)) + +--- + +# v0.9.6 (Wed Mar 18 2020) + +#### 🏠 Internal + +- Fix TypeScript error on 'next' [#858](https://github.com/oliver-moran/jimp/pull/858) ([@crutchcorn](https://github.com/crutchcorn)) + +#### Authors: 1 + +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/custom/LICENSE b/node_modules/@jimp/custom/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/custom/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/custom/README.md b/node_modules/@jimp/custom/README.md new file mode 100644 index 00000000..961d7333 --- /dev/null +++ b/node_modules/@jimp/custom/README.md @@ -0,0 +1,198 @@ +
+ +

@jimp/custom

+

Configure jimp with types and plugins.

+
+ +## Useful Defaults + +The following wil configure a `jimp` instance with the same functionality as the main `jimp` package. + +```js +import configure from "@jimp/custom"; +// all of jimp's default types +import types from "@jimp/types"; +// all of jimp's default types +import plugins from "@jimp/plugins"; + +configure({ + types: [types], + plugins: [plugins], +}); +``` + +## Available Methods + +### configure + +Takes a Jimp configuration and applies it to `@jimp/core`. + +Sample Jimp configuration: + +```js +import types from '@jimp/types'; + +import bmp from '@jimp/bmp'; +import jpeg from '@jimp/types'; +... + +configure({ + types: [types] +}) + +// or + +configure({ + types: [bmp, jpeg, ...] +}) +``` + +#### Extending Jimp Further + +You can use configure to add more types and plugins to a jimp multiple times. + +```js +let jimp = configure({ + types: [bmp], +}); + +jimp = configure( + { + types: [jpeg], + }, + jimp +); +``` + +## Type Definition + +To define a new Jimp image type write a function the takes the current Jimp configuration. In this function you can extend Jimp's internal data structures. + +This function must return an object whose key is the mime type and value is an array of valid file extensions. + +```js +const special = require('special-js'); + +const MIME_TYPE = 'image/special'; + +export default () => ({ + mime: {[MIME_TYPE], ['spec', 'special']}, + + constants: { + MIME_SPECIAL: MIME_TYPE + }, + + decoders: { + [MIME_TYPE]: data => special.decode(data) + }, + + encoders: { + [MIME_TYPE]: image => special.encode(image.bitmap) + } +}); +``` + +### Constants + +A jimp image type can expose as many constants as it wants. Each jimp type is required to expose a mime type. + +```js +constants: { + MIME_SPECIAL: MIME_TYPE +}, +``` + +### hasAlpha + +A image type can define whether it supports an alpha channel. + +```js +hasAlpha: { + MIME_SPECIAL: true +}, +``` + +### Decoder + +A function that when supplied with a buffer should return a bitmap with height and width. + +```js +decoders: { + [MIME_TYPE]: data => special.decode(data) +}, +``` + +### Encoder + +A function that when supplied with a Jimp image should return an encoded buffer. + +```js +encoders: { + [MIME_TYPE]: image => special.encode(image.bitmap) +} +``` + +### Class + +Add class properties and function to the Jimp constructor. + +```js +class: { + _quality: 100, + quality: function(n, cb) { + if (typeof n !== 'number') { + return throwError.call(this, 'n must be a number', cb); + } + + if (n < 0 || n > 100) { + return throwError.call(this, 'n must be a number 0 - 100', cb); + } + + this._quality = Math.round(n); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + } +}; +``` + +## Plugin Definition + +Defining a plugin has access to all the same things in the type definition. Mainly plugins use just the `constants` and `class` config options. + +Below is the `invert` plugin. If a plugin doesn return an object with `constants` and `class`, all keys are treated as class functions. + +```js +import { isNodePattern } from "@jimp/utils"; + +/** + * Inverts the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + invert(cb) { + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + this.bitmap.data[idx] = 255 - this.bitmap.data[idx]; + this.bitmap.data[idx + 1] = 255 - this.bitmap.data[idx + 1]; + this.bitmap.data[idx + 2] = 255 - this.bitmap.data[idx + 2]; + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); +``` diff --git a/node_modules/@jimp/custom/es/index.js b/node_modules/@jimp/custom/es/index.js new file mode 100644 index 00000000..efc8a97a --- /dev/null +++ b/node_modules/@jimp/custom/es/index.js @@ -0,0 +1,63 @@ +import Jimp, { addType, addJimpMethods, addConstants, jimpEvChange } from "@jimp/core"; +export default function configure(configuration) { + let jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp; + const jimpConfig = { + hasAlpha: {}, + encoders: {}, + decoders: {}, + class: {}, + constants: {} + }; + function addToConfig(newConfig) { + Object.entries(newConfig).forEach(_ref => { + let [key, value] = _ref; + jimpConfig[key] = { + ...jimpConfig[key], + ...value + }; + }); + } + function addImageType(typeModule) { + const type = typeModule(); + if (Array.isArray(type.mime)) { + addType(...type.mime); + } else { + Object.entries(type.mime).forEach(mimeType => addType(...mimeType)); + } + delete type.mime; + addToConfig(type); + } + function addPlugin(pluginModule) { + const plugin = pluginModule(jimpEvChange) || {}; + if (!plugin.class && !plugin.constants) { + // Default to class function + addToConfig({ + class: plugin + }); + } else { + addToConfig(plugin); + } + } + if (configuration.types) { + configuration.types.forEach(addImageType); + jimpInstance.decoders = { + ...jimpInstance.decoders, + ...jimpConfig.decoders + }; + jimpInstance.encoders = { + ...jimpInstance.encoders, + ...jimpConfig.encoders + }; + jimpInstance.hasAlpha = { + ...jimpInstance.hasAlpha, + ...jimpConfig.hasAlpha + }; + } + if (configuration.plugins) { + configuration.plugins.forEach(addPlugin); + } + addJimpMethods(jimpConfig.class, jimpInstance); + addConstants(jimpConfig.constants, jimpInstance); + return Jimp; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/custom/es/index.js.map b/node_modules/@jimp/custom/es/index.js.map new file mode 100644 index 00000000..066194f4 --- /dev/null +++ b/node_modules/@jimp/custom/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["Jimp","addType","addJimpMethods","addConstants","jimpEvChange","configure","configuration","jimpInstance","jimpConfig","hasAlpha","encoders","decoders","class","constants","addToConfig","newConfig","Object","entries","forEach","key","value","addImageType","typeModule","type","Array","isArray","mime","mimeType","addPlugin","pluginModule","plugin","types","plugins"],"sources":["../src/index.js"],"sourcesContent":["import Jimp, {\n addType,\n addJimpMethods,\n addConstants,\n jimpEvChange,\n} from \"@jimp/core\";\n\nexport default function configure(configuration, jimpInstance = Jimp) {\n const jimpConfig = {\n hasAlpha: {},\n encoders: {},\n decoders: {},\n class: {},\n constants: {},\n };\n\n function addToConfig(newConfig) {\n Object.entries(newConfig).forEach(([key, value]) => {\n jimpConfig[key] = {\n ...jimpConfig[key],\n ...value,\n };\n });\n }\n\n function addImageType(typeModule) {\n const type = typeModule();\n\n if (Array.isArray(type.mime)) {\n addType(...type.mime);\n } else {\n Object.entries(type.mime).forEach((mimeType) => addType(...mimeType));\n }\n\n delete type.mime;\n addToConfig(type);\n }\n\n function addPlugin(pluginModule) {\n const plugin = pluginModule(jimpEvChange) || {};\n if (!plugin.class && !plugin.constants) {\n // Default to class function\n addToConfig({ class: plugin });\n } else {\n addToConfig(plugin);\n }\n }\n\n if (configuration.types) {\n configuration.types.forEach(addImageType);\n\n jimpInstance.decoders = {\n ...jimpInstance.decoders,\n ...jimpConfig.decoders,\n };\n jimpInstance.encoders = {\n ...jimpInstance.encoders,\n ...jimpConfig.encoders,\n };\n jimpInstance.hasAlpha = {\n ...jimpInstance.hasAlpha,\n ...jimpConfig.hasAlpha,\n };\n }\n\n if (configuration.plugins) {\n configuration.plugins.forEach(addPlugin);\n }\n\n addJimpMethods(jimpConfig.class, jimpInstance);\n addConstants(jimpConfig.constants, jimpInstance);\n\n return Jimp;\n}\n"],"mappings":"AAAA,OAAOA,IAAI,IACTC,OAAO,EACPC,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AAO,CAAC,CAAC;IAChC,CAAC,MAAM;MACLhB,WAAW,CAACgB,MAAM,CAAC;IACrB;EACF;EAEA,IAAIxB,aAAa,CAACyB,KAAK,EAAE;IACvBzB,aAAa,CAACyB,KAAK,CAACb,OAAO,CAACG,YAAY,CAAC;IAEzCd,YAAY,CAACI,QAAQ,GAAG;MACtB,GAAGJ,YAAY,CAACI,QAAQ;MACxB,GAAGH,UAAU,CAACG;IAChB,CAAC;IACDJ,YAAY,CAACG,QAAQ,GAAG;MACtB,GAAGH,YAAY,CAACG,QAAQ;MACxB,GAAGF,UAAU,CAACE;IAChB,CAAC;IACDH,YAAY,CAACE,QAAQ,GAAG;MACtB,GAAGF,YAAY,CAACE,QAAQ;MACxB,GAAGD,UAAU,CAACC;IAChB,CAAC;EACH;EAEA,IAAIH,aAAa,CAAC0B,OAAO,EAAE;IACzB1B,aAAa,CAAC0B,OAAO,CAACd,OAAO,CAACU,SAAS,CAAC;EAC1C;EAEA1B,cAAc,CAACM,UAAU,CAACI,KAAK,EAAEL,YAAY,CAAC;EAC9CJ,YAAY,CAACK,UAAU,CAACK,SAAS,EAAEN,YAAY,CAAC;EAEhD,OAAOP,IAAI;AACb"} \ No newline at end of file diff --git a/node_modules/@jimp/custom/package.json b/node_modules/@jimp/custom/package.json new file mode 100644 index 00000000..d64fb4be --- /dev/null +++ b/node_modules/@jimp/custom/package.json @@ -0,0 +1,27 @@ +{ + "name": "@jimp/custom", + "version": "0.22.12", + "description": "Interface to customize jimp configuration", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "types/index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/core": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/custom/src/index.js b/node_modules/@jimp/custom/src/index.js new file mode 100644 index 00000000..dddc7d90 --- /dev/null +++ b/node_modules/@jimp/custom/src/index.js @@ -0,0 +1,74 @@ +import Jimp, { + addType, + addJimpMethods, + addConstants, + jimpEvChange, +} from "@jimp/core"; + +export default function configure(configuration, jimpInstance = Jimp) { + const jimpConfig = { + hasAlpha: {}, + encoders: {}, + decoders: {}, + class: {}, + constants: {}, + }; + + function addToConfig(newConfig) { + Object.entries(newConfig).forEach(([key, value]) => { + jimpConfig[key] = { + ...jimpConfig[key], + ...value, + }; + }); + } + + function addImageType(typeModule) { + const type = typeModule(); + + if (Array.isArray(type.mime)) { + addType(...type.mime); + } else { + Object.entries(type.mime).forEach((mimeType) => addType(...mimeType)); + } + + delete type.mime; + addToConfig(type); + } + + function addPlugin(pluginModule) { + const plugin = pluginModule(jimpEvChange) || {}; + if (!plugin.class && !plugin.constants) { + // Default to class function + addToConfig({ class: plugin }); + } else { + addToConfig(plugin); + } + } + + if (configuration.types) { + configuration.types.forEach(addImageType); + + jimpInstance.decoders = { + ...jimpInstance.decoders, + ...jimpConfig.decoders, + }; + jimpInstance.encoders = { + ...jimpInstance.encoders, + ...jimpConfig.encoders, + }; + jimpInstance.hasAlpha = { + ...jimpInstance.hasAlpha, + ...jimpConfig.hasAlpha, + }; + } + + if (configuration.plugins) { + configuration.plugins.forEach(addPlugin); + } + + addJimpMethods(jimpConfig.class, jimpInstance); + addConstants(jimpConfig.constants, jimpInstance); + + return Jimp; +} diff --git a/node_modules/@jimp/custom/types/index.d.ts b/node_modules/@jimp/custom/types/index.d.ts new file mode 100644 index 00000000..dc528878 --- /dev/null +++ b/node_modules/@jimp/custom/types/index.d.ts @@ -0,0 +1,40 @@ +// Minimum TypeScript Version: 3.2 +// See the `jimp` package index.d.ts for why the version is not 2.8 +import { + FunctionRet, + Jimp, + JimpPlugin, + JimpType, + GetIntersectionFromPlugins, + GetIntersectionFromPluginsStatics, + JimpConstructors, +} from "@jimp/core"; + +type JimpInstance< + TypesFuncArr extends FunctionRet | undefined, + PluginFuncArr extends FunctionRet | undefined, + J extends JimpConstructors +> = J & + GetIntersectionFromPluginsStatics< + Exclude + > & { + prototype: JimpType & + GetIntersectionFromPlugins< + Exclude + >; + }; + +declare function configure< + TypesFuncArr extends FunctionRet | undefined = undefined, + PluginFuncArr extends FunctionRet | undefined = undefined, + J extends JimpConstructors = JimpConstructors +>( + configuration: { + types?: TypesFuncArr; + plugins?: PluginFuncArr; + }, + jimpInstance?: J + // Since JimpInstance is required, we want to use the default `Jimp` type +): JimpInstance; + +export default configure; diff --git a/node_modules/@jimp/custom/types/test.ts b/node_modules/@jimp/custom/types/test.ts new file mode 100644 index 00000000..e0f77bb2 --- /dev/null +++ b/node_modules/@jimp/custom/types/test.ts @@ -0,0 +1,401 @@ +import configure from "@jimp/custom"; +import gif from "@jimp/gif"; +import png from "@jimp/png"; +import displace from "@jimp/plugin-displace"; +import resize from "@jimp/plugin-resize"; +import scale from "@jimp/plugin-scale"; +import types from "@jimp/types"; +import plugins from "@jimp/plugins"; +import * as Jimp from "jimp"; + +// configure should return a valid Jimp type with addons +const CustomJimp = configure({ + types: [gif, png], + plugins: [displace, resize], +}); + +test("should function the same as the `jimp` types", () => { + const FullCustomJimp = configure({ + types: [types], + plugins: [plugins], + }); + + const jimpInst = new FullCustomJimp("test"); + + // Main Jimp export should already have all of these already applied + // $ExpectError + jimpInst.read("Test"); + jimpInst.displace(jimpInst, 2); + jimpInst.resize(40, 40); + jimpInst.displace(jimpInst, 2); + jimpInst.shadow((err, val, coords) => {}); + jimpInst.fishEye({ r: 12 }); + jimpInst.circle({ radius: 12, x: 12, y: 12 }); + // $ExpectError + jimpInst.PNG_FILTER_NONE; + + // $ExpectError + jimpInst.test; + + // $ExpectError + jimpInst.func(); + + // Main Jimp export should already have all of these already applied + FullCustomJimp.read("Test"); + + // $ExpectType 0 + FullCustomJimp.PNG_FILTER_NONE; + + // $ExpectError + FullCustomJimp.test; + + // $ExpectError + FullCustomJimp.func(); + + test("can clone properly", async () => { + const baseImage = await FullCustomJimp.read("filename"); + const cloneBaseImage = baseImage.clone(); + + // $ExpectType number + cloneBaseImage._deflateLevel; + + test("can handle `this` returns on the core type properly", () => { + // $ExpectType number + cloneBaseImage.posterize(3)._quality; + }); + + test("can handle `this` returns properly", () => { + cloneBaseImage + .resize(1, 1) + .crop(0, 0, 0, 0) + .mask(cloneBaseImage, 2, 2) + .print("a" as any, 2, 2, "a" as any) + .resize(1, 1) + .quality(1) + .deflateLevel(2)._filterType; + }); + + test("can handle imageCallbacks `this` properly", () => { + cloneBaseImage.rgba(false, (_, jimpCBIn) => { + // $ExpectError + jimpCBIn.read("Test"); + jimpCBIn.displace(jimpInst, 2); + jimpCBIn.resize(40, 40); + // $ExpectType number + jimpCBIn._filterType; + + // $ExpectError + jimpCBIn.test; + + // $ExpectError + jimpCBIn.func(); + }); + }); + }); + + test("Can handle callback with constructor", () => { + const myBmpBuffer: Buffer = {} as any; + + Jimp.read(myBmpBuffer, (err, cbJimpInst) => { + // $ExpectError + cbJimpInst.read("Test"); + cbJimpInst.displace(jimpInst, 2); + cbJimpInst.resize(40, 40); + // $ExpectType number + cbJimpInst._filterType; + + // $ExpectError + cbJimpInst.test; + + // $ExpectError + cbJimpInst.func(); + }); + }); +}); + +test("can handle custom jimp", () => { + // Constants from types should be applied + // $ExpectType 0 + CustomJimp.PNG_FILTER_NONE; + + // Core functions should still work from Jimp + CustomJimp.read("Test"); + + // Constants should not(?) be applied from ill-formed plugins + // $ExpectError + CustomJimp.displace(CustomJimp, 2); + + // Methods should be applied from well-formed plugins only to the instance + // $ExpectError + CustomJimp.resize(40, 40); + + // Constants should be applied from well-formed plugins + CustomJimp.RESIZE_NEAREST_NEIGHBOR; + + // $ExpectError + CustomJimp.test; + + // $ExpectError + CustomJimp.func(); + + const Jiimp = new CustomJimp("test"); + // Methods from types should be applied + Jiimp.deflateLevel(4); + // Constants from types should be applied to the static only + // $ExpectError + Jiimp.PNG_FILTER_NONE; + + // Core functions should still work from Jimp + Jiimp.getPixelColor(1, 1); + + // Constants should be applied from ill-formed plugins + Jiimp.displace(Jiimp, 2); + + // Methods should be applied from well-formed plugins + Jiimp.resize(40, 40); + + // Constants should not be applied to the object + // $ExpectError + Jiimp.RESIZE_NEAREST_NEIGHBOR; + + // $ExpectError + Jiimp.test; + + // $ExpectError + Jiimp.func(); +}); + +test("can compose", () => { + const OtherCustomJimp = configure( + { + plugins: [scale], + }, + CustomJimp + ); + // Constants from types should be applied + // $ExpectType 0 + OtherCustomJimp.PNG_FILTER_NONE; + + // Core functions should still work from Jimp + OtherCustomJimp.read("Test"); + + // Constants should not be applied to the static instance from ill-formed plugins + // $ExpectError + OtherCustomJimp.displace(OtherCustomJimp, 2); + + // Methods should not be applied to the static instance from well-formed plugins + // $ExpectError + OtherCustomJimp.resize(40, 40); + + // Constants should be applied from well-formed plugins + OtherCustomJimp.RESIZE_NEAREST_NEIGHBOR; + + // $ExpectError + OtherCustomJimp.test; + + // $ExpectError + OtherCustomJimp.func(); + + const Jiimp = new OtherCustomJimp("test"); + // Methods from types should be applied + Jiimp.deflateLevel(4); + // Constants from types should not be applied to objects + // $ExpectError + Jiimp.PNG_FILTER_NONE; + + // Methods from new plugins should be applied + Jiimp.scale(3); + + // Methods from types should be applied + Jiimp.filterType(4); + + // Core functions should still work from Jimp + Jiimp.getPixelColor(1, 1); + + // Constants should be applied from ill-formed plugins + Jiimp.displace(Jiimp, 2); + + // Methods should be applied from well-formed plugins + Jiimp.resize(40, 40); + + // Constants should not be applied from well-formed plugins to objects + // $ExpectError + Jiimp.RESIZE_NEAREST_NEIGHBOR; + + // $ExpectError + Jiimp.test; + + // $ExpectError + Jiimp.func(); +}); + +test("can handle only plugins", () => { + const PluginsJimp = configure({ + plugins: [plugins], + }); + + // Core functions should still work from Jimp + PluginsJimp.read("Test"); + + // Constants should not be applied from ill-formed plugins + // $ExpectError + PluginsJimp.displace(PluginsJimp, 2); + + // Methods should be not be applied to from well-formed plugins to the top level + // $ExpectError + PluginsJimp.resize(40, 40); + + // Constants should be applied from well-formed plugins + // $ExpectType "nearestNeighbor" + PluginsJimp.RESIZE_NEAREST_NEIGHBOR; + + // $ExpectError + PluginsJimp.test; + + // $ExpectError + PluginsJimp.func(); + + const Jiimp = new PluginsJimp("test"); + + // Core functions should still work from Jimp + Jiimp.getPixelColor(1, 1); + + // Constants should be applied from ill-formed plugins + Jiimp.displace(Jiimp, 2); + + // Methods should be applied from well-formed plugins + Jiimp.resize(40, 40); + + // Constants should be not applied to objects from well-formed plugins + // $ExpectError + Jiimp.RESIZE_NEAREST_NEIGHBOR; + + // $ExpectError + Jiimp.test; + + // $ExpectError + Jiimp.func(); +}); + +test("can handle only all types", () => { + const TypesJimp = configure({ + types: [types], + }); + + // Methods from types should not be applied + // $ExpectError + TypesJimp.filterType(4); + // Constants from types should be applied + // $ExpectType 0 + TypesJimp.PNG_FILTER_NONE; + + // $ExpectError + TypesJimp.test; + + // $ExpectError + TypesJimp.func(); + + const Jiimp = new TypesJimp("test"); + // Methods from types should be applied + Jiimp.filterType(4); + // Constants from types should be not applied to objects + // $ExpectError + Jiimp.PNG_FILTER_NONE; + + // $ExpectError + Jiimp.test; + + // $ExpectError + Jiimp.func(); +}); + +test("can handle only one type", () => { + const PngJimp = configure({ + types: [png], + }); + + // Constants from other types should be not applied + // $ExpectError + PngJimp.MIME_TIFF; + + // Constants from types should be applied + // $ExpectType 0 + PngJimp.PNG_FILTER_NONE; + + // $ExpectError + PngJimp.test; + + // $ExpectError + PngJimp.func(); + + const Jiimp = new PngJimp("test"); + // Constants from other types should be not applied + // $ExpectError + Jiimp.MIME_TIFF; + + // Constants from types should not be applied to objects + // $ExpectError + Jiimp.PNG_FILTER_NONE; + + // $ExpectError + Jiimp.test; + + // $ExpectError + Jiimp.func(); +}); + +test("can handle only one plugin", () => { + const ResizeJimp = configure({ + plugins: [resize], + }); + + // Constants from other plugins should be not applied + // $ExpectError + ResizeJimp.FONT_SANS_8_BLACK; + + // Constants from plugin should be applied + // $ExpectType "nearestNeighbor" + ResizeJimp.RESIZE_NEAREST_NEIGHBOR; + + // $ExpectError + ResizeJimp.resize(2, 2); + + // $ExpectError + ResizeJimp.test; + + // $ExpectError + ResizeJimp.func(); + + const Jiimp: InstanceType = new ResizeJimp("test"); + // Constants from other plugins should be not applied + // $ExpectError + Jiimp.FONT_SANS_8_BLACK; + + // Constants from plugin should not be applied to the object + // $ExpectError + Jiimp.RESIZE_NEAREST_NEIGHBOR; + + Jiimp.resize(2, 2); + + // $ExpectError + Jiimp.test; + + // $ExpectError + Jiimp.func(); +}); + +test("Can handle appendConstructorOption", () => { + const AppendJimp = configure({}); + + AppendJimp.appendConstructorOption( + "Name of Option", + (args) => args.hasSomeCustomThing, + function (resolve, reject, args) { + // $ExpectError + this.bitmap = 3; + // $ExpectError + AppendJimp.resize(2, 2); + resolve(); + } + ); +}); diff --git a/node_modules/@jimp/custom/types/tsconfig.json b/node_modules/@jimp/custom/types/tsconfig.json new file mode 100644 index 00000000..a2773dce --- /dev/null +++ b/node_modules/@jimp/custom/types/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "skipLibCheck": true, + "noEmit": true, + + // If the library is an external module (uses `export`), this allows your test file to import "mylib" instead of "./index". + // If the library is global (cannot be imported via `import` or `require`), leave this out. + "baseUrl": ".", + "paths": { + "mylib": ["."] + } + } +} diff --git a/node_modules/@jimp/gif/CHANGELOG.md b/node_modules/@jimp/gif/CHANGELOG.md new file mode 100644 index 00000000..e12d31e0 --- /dev/null +++ b/node_modules/@jimp/gif/CHANGELOG.md @@ -0,0 +1,114 @@ +# v0.22.9 (Wed Jul 26 2023) + +:tada: This release contains work from a new contributor! :tada: + +Thank you, Nicolas Morel ([@Marsup](https://github.com/Marsup)), for all your work! + +#### 🚀 Enhancement + +- chore: upgrade gifwrap [#1222](https://github.com/jimp-dev/jimp/pull/1222) ([@Marsup](https://github.com/Marsup)) + +#### Authors: 1 + +- Nicolas Morel ([@Marsup](https://github.com/Marsup)) + +--- + +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.13.0 (Fri Jun 05 2020) + +#### 🚀 Enhancement + +- Add single frame encoder for type-gif [#899](https://github.com/oliver-moran/jimp/pull/899) ([@jeffbseeking](https://github.com/jeffbseeking) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Jeff Bonnes ([@jeffbseeking](https://github.com/jeffbseeking)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/gif/LICENSE b/node_modules/@jimp/gif/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/gif/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/gif/README.md b/node_modules/@jimp/gif/README.md new file mode 100644 index 00000000..9a434927 --- /dev/null +++ b/node_modules/@jimp/gif/README.md @@ -0,0 +1,8 @@ +
+ +

@jimp/gif

+

Default Jimp gif decoder.

+
+ +NOTE: Encoder currently unavailable. diff --git a/node_modules/@jimp/gif/es/index.js b/node_modules/@jimp/gif/es/index.js new file mode 100644 index 00000000..5a527cd0 --- /dev/null +++ b/node_modules/@jimp/gif/es/index.js @@ -0,0 +1,35 @@ +import GIF from "omggif"; +import { GifUtil, GifFrame, BitmapImage, GifCodec } from "gifwrap"; +const MIME_TYPE = "image/gif"; +export default (() => ({ + mime: { + [MIME_TYPE]: ["gif"] + }, + constants: { + MIME_GIF: MIME_TYPE + }, + decoders: { + [MIME_TYPE]: data => { + const gifObj = new GIF.GifReader(data); + const gifData = Buffer.alloc(gifObj.width * gifObj.height * 4); + gifObj.decodeAndBlitFrameRGBA(0, gifData); + return { + data: gifData, + width: gifObj.width, + height: gifObj.height + }; + } + }, + encoders: { + [MIME_TYPE]: data => { + const bitmap = new BitmapImage(data.bitmap); + GifUtil.quantizeDekker(bitmap, 256); + const newFrame = new GifFrame(bitmap); + const gifCodec = new GifCodec(); + return gifCodec.encodeGif([newFrame], {}).then(newGif => { + return newGif.buffer; + }); + } + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/gif/es/index.js.map b/node_modules/@jimp/gif/es/index.js.map new file mode 100644 index 00000000..7ec6fc5c --- /dev/null +++ b/node_modules/@jimp/gif/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["GIF","GifUtil","GifFrame","BitmapImage","GifCodec","MIME_TYPE","mime","constants","MIME_GIF","decoders","data","gifObj","GifReader","gifData","Buffer","alloc","width","height","decodeAndBlitFrameRGBA","encoders","bitmap","quantizeDekker","newFrame","gifCodec","encodeGif","then","newGif","buffer"],"sources":["../src/index.js"],"sourcesContent":["import GIF from \"omggif\";\nimport { GifUtil, GifFrame, BitmapImage, GifCodec } from \"gifwrap\";\n\nconst MIME_TYPE = \"image/gif\";\n\nexport default () => ({\n mime: { [MIME_TYPE]: [\"gif\"] },\n\n constants: {\n MIME_GIF: MIME_TYPE,\n },\n\n decoders: {\n [MIME_TYPE]: (data) => {\n const gifObj = new GIF.GifReader(data);\n const gifData = Buffer.alloc(gifObj.width * gifObj.height * 4);\n\n gifObj.decodeAndBlitFrameRGBA(0, gifData);\n\n return {\n data: gifData,\n width: gifObj.width,\n height: gifObj.height,\n };\n },\n },\n\n encoders: {\n [MIME_TYPE]: (data) => {\n const bitmap = new BitmapImage(data.bitmap);\n GifUtil.quantizeDekker(bitmap, 256);\n const newFrame = new GifFrame(bitmap);\n const gifCodec = new GifCodec();\n return gifCodec.encodeGif([newFrame], {}).then((newGif) => {\n return newGif.buffer;\n });\n },\n },\n});\n"],"mappings":"AAAA,OAAOA,GAAG,MAAM,QAAQ;AACxB,SAASC,OAAO,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,SAAS;AAElE,MAAMC,SAAS,GAAG,WAAW;AAE7B,gBAAe,OAAO;EACpBC,IAAI,EAAE;IAAE,CAACD,SAAS,GAAG,CAAC,KAAK;EAAE,CAAC;EAE9BE,SAAS,EAAE;IACTC,QAAQ,EAAEH;EACZ,CAAC;EAEDI,QAAQ,EAAE;IACR,CAACJ,SAAS,GAAIK,IAAI,IAAK;MACrB,MAAMC,MAAM,GAAG,IAAIX,GAAG,CAACY,SAAS,CAACF,IAAI,CAAC;MACtC,MAAMG,OAAO,GAAGC,MAAM,CAACC,KAAK,CAACJ,MAAM,CAACK,KAAK,GAAGL,MAAM,CAACM,MAAM,GAAG,CAAC,CAAC;MAE9DN,MAAM,CAACO,sBAAsB,CAAC,CAAC,EAAEL,OAAO,CAAC;MAEzC,OAAO;QACLH,IAAI,EAAEG,OAAO;QACbG,KAAK,EAAEL,MAAM,CAACK,KAAK;QACnBC,MAAM,EAAEN,MAAM,CAACM;MACjB,CAAC;IACH;EACF,CAAC;EAEDE,QAAQ,EAAE;IACR,CAACd,SAAS,GAAIK,IAAI,IAAK;MACrB,MAAMU,MAAM,GAAG,IAAIjB,WAAW,CAACO,IAAI,CAACU,MAAM,CAAC;MAC3CnB,OAAO,CAACoB,cAAc,CAACD,MAAM,EAAE,GAAG,CAAC;MACnC,MAAME,QAAQ,GAAG,IAAIpB,QAAQ,CAACkB,MAAM,CAAC;MACrC,MAAMG,QAAQ,GAAG,IAAInB,QAAQ,EAAE;MAC/B,OAAOmB,QAAQ,CAACC,SAAS,CAAC,CAACF,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAACG,IAAI,CAAEC,MAAM,IAAK;QACzD,OAAOA,MAAM,CAACC,MAAM;MACtB,CAAC,CAAC;IACJ;EACF;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/gif/index.d.ts b/node_modules/@jimp/gif/index.d.ts new file mode 100644 index 00000000..d1b1c679 --- /dev/null +++ b/node_modules/@jimp/gif/index.d.ts @@ -0,0 +1,17 @@ +import { DecoderFn } from "@jimp/core"; + +interface Gif { + mime: { + "image/gif": string[]; + }; + + constants: { + MIME_GIF: "image/gif"; + }; + + decoders: { + "image/gif": DecoderFn; + }; +} + +export default function (): Gif; diff --git a/node_modules/@jimp/gif/package.json b/node_modules/@jimp/gif/package.json new file mode 100644 index 00000000..4fe0219f --- /dev/null +++ b/node_modules/@jimp/gif/package.json @@ -0,0 +1,39 @@ +{ + "name": "@jimp/gif", + "version": "0.22.12", + "description": "Default Jimp gif encoder/decoder.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "gifwrap": "^0.10.1", + "omggif": "^1.0.9" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/gif/src/index.js b/node_modules/@jimp/gif/src/index.js new file mode 100644 index 00000000..7acf2ff9 --- /dev/null +++ b/node_modules/@jimp/gif/src/index.js @@ -0,0 +1,39 @@ +import GIF from "omggif"; +import { GifUtil, GifFrame, BitmapImage, GifCodec } from "gifwrap"; + +const MIME_TYPE = "image/gif"; + +export default () => ({ + mime: { [MIME_TYPE]: ["gif"] }, + + constants: { + MIME_GIF: MIME_TYPE, + }, + + decoders: { + [MIME_TYPE]: (data) => { + const gifObj = new GIF.GifReader(data); + const gifData = Buffer.alloc(gifObj.width * gifObj.height * 4); + + gifObj.decodeAndBlitFrameRGBA(0, gifData); + + return { + data: gifData, + width: gifObj.width, + height: gifObj.height, + }; + }, + }, + + encoders: { + [MIME_TYPE]: (data) => { + const bitmap = new BitmapImage(data.bitmap); + GifUtil.quantizeDekker(bitmap, 256); + const newFrame = new GifFrame(bitmap); + const gifCodec = new GifCodec(); + return gifCodec.encodeGif([newFrame], {}).then((newGif) => { + return newGif.buffer; + }); + }, + }, +}); diff --git a/node_modules/@jimp/gif/test/gif.test.js b/node_modules/@jimp/gif/test/gif.test.js new file mode 100644 index 00000000..664fa676 --- /dev/null +++ b/node_modules/@jimp/gif/test/gif.test.js @@ -0,0 +1,27 @@ +import { Jimp, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import expect from "@storybook/expect"; + +import gif from "../src"; + +const jimp = configure({ types: [gif] }, Jimp); + +describe("GIF", () => { + const imagesDir = getTestDir(__dirname) + "/images"; + + it("load GIF", async () => { + const image = await jimp.read(imagesDir + "/flower.gif"); + expect(image.getPixelColor(10, 10)).toBe(0xe5e6d9ff); + }); + + it("load animated GIF", async () => { + const image = await jimp.read(imagesDir + "/animated.gif"); + expect(image.getPixelColor(10, 10)).toBe(0xa1d2f1ff); + }); + + it("export GIF", async () => { + const jgd = await jimp.read(imagesDir + "/flower.gif"); + const buffer = await jgd.getBufferAsync("image/gif"); + expect(buffer.toString()).toMatch(/^GIF/); + }); +}); diff --git a/node_modules/@jimp/gif/test/images/animated.gif b/node_modules/@jimp/gif/test/images/animated.gif new file mode 100644 index 00000000..401ef84a Binary files /dev/null and b/node_modules/@jimp/gif/test/images/animated.gif differ diff --git a/node_modules/@jimp/gif/test/images/flower.gif b/node_modules/@jimp/gif/test/images/flower.gif new file mode 100644 index 00000000..23595dd5 Binary files /dev/null and b/node_modules/@jimp/gif/test/images/flower.gif differ diff --git a/node_modules/@jimp/jpeg/CHANGELOG.md b/node_modules/@jimp/jpeg/CHANGELOG.md new file mode 100644 index 00000000..e4262f45 --- /dev/null +++ b/node_modules/@jimp/jpeg/CHANGELOG.md @@ -0,0 +1,154 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.17.0 (Sat Feb 04 2023) + +### Release Notes + +#### update jpeg-js ([#1131](https://github.com/jimp-dev/jimp/pull/1131)) + +This release changes the minimum node version from 8 to 16 + +--- + +#### 🚀 Enhancement + +- update jpeg-js [#1131](https://github.com/jimp-dev/jimp/pull/1131) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.2 (Thu Sep 15 2022) + +#### 🐛 Bug Fix + +- Bump jpeg-js over 0.4.4 to avoid cve-2022-25851 [#1093](https://github.com/oliver-moran/jimp/pull/1093) ([@melhadad](https://github.com/melhadad)) + +#### Authors: 1 + +- Michael Elhadad ([@melhadad](https://github.com/melhadad)) + +--- + +# v0.16.1 (Fri Aug 28 2020) + +#### 🐛 Bug Fix + +- upgrade jpeg-js dependency [#933](https://github.com/oliver-moran/jimp/pull/933) (vincentdufrasnes@vincent-dufrasnes [@Chupsy](https://github.com/Chupsy)) + +#### Authors: 2 + +- Vincent Dufrasnes ([@Chupsy](https://github.com/Chupsy)) +- vincent dufrasnes (vincentdufrasnes@vincent-dufrasnes) + +--- + +# v0.12.1 (Tue May 19 2020) + +#### 🐛 Bug Fix + +- update jpeg-js [#892](https://github.com/oliver-moran/jimp/pull/892) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.10.0 (Mon Mar 30 2020) + +#### 🚀 Enhancement + +- Properly split constructor and instance types [#867](https://github.com/oliver-moran/jimp/pull/867) ([@forivall](https://github.com/forivall)) + +#### Authors: 1 + +- Emily Marigold Klassen ([@forivall](https://github.com/forivall)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/jpeg/LICENSE b/node_modules/@jimp/jpeg/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/jpeg/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/jpeg/README.md b/node_modules/@jimp/jpeg/README.md new file mode 100644 index 00000000..89255137 --- /dev/null +++ b/node_modules/@jimp/jpeg/README.md @@ -0,0 +1,12 @@ +
+ +

@jimp/jpeg

+

Default Jimp jpeg encoder/decoder.

+
+ +## Available Methods + +### Jimp.quality + +Sets the quality of the image when saving as JPEG format (default is 100) diff --git a/node_modules/@jimp/jpeg/es/index.js b/node_modules/@jimp/jpeg/es/index.js new file mode 100644 index 00000000..f081884b --- /dev/null +++ b/node_modules/@jimp/jpeg/es/index.js @@ -0,0 +1,41 @@ +import JPEG from "jpeg-js"; +import { throwError, isNodePattern } from "@jimp/utils"; +const MIME_TYPE = "image/jpeg"; +export default (() => ({ + mime: { + [MIME_TYPE]: ["jpeg", "jpg", "jpe"] + }, + constants: { + MIME_JPEG: MIME_TYPE + }, + decoders: { + [MIME_TYPE]: JPEG.decode + }, + encoders: { + [MIME_TYPE]: image => JPEG.encode(image.bitmap, image._quality).data + }, + class: { + // The quality to be used when saving JPEG images + _quality: 100, + /** + * Sets the quality of the image when saving as JPEG format (default is 100) + * @param {number} n The quality to use 0-100 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + quality(n, cb) { + if (typeof n !== "number") { + return throwError.call(this, "n must be a number", cb); + } + if (n < 0 || n > 100) { + return throwError.call(this, "n must be a number 0 - 100", cb); + } + this._quality = Math.round(n); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/jpeg/es/index.js.map b/node_modules/@jimp/jpeg/es/index.js.map new file mode 100644 index 00000000..f621d691 --- /dev/null +++ b/node_modules/@jimp/jpeg/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["JPEG","throwError","isNodePattern","MIME_TYPE","mime","constants","MIME_JPEG","decoders","decode","encoders","image","encode","bitmap","_quality","data","class","quality","n","cb","call","Math","round"],"sources":["../src/index.js"],"sourcesContent":["import JPEG from \"jpeg-js\";\nimport { throwError, isNodePattern } from \"@jimp/utils\";\n\nconst MIME_TYPE = \"image/jpeg\";\n\nexport default () => ({\n mime: { [MIME_TYPE]: [\"jpeg\", \"jpg\", \"jpe\"] },\n\n constants: {\n MIME_JPEG: MIME_TYPE,\n },\n\n decoders: {\n [MIME_TYPE]: JPEG.decode,\n },\n\n encoders: {\n [MIME_TYPE]: (image) => JPEG.encode(image.bitmap, image._quality).data,\n },\n\n class: {\n // The quality to be used when saving JPEG images\n _quality: 100,\n /**\n * Sets the quality of the image when saving as JPEG format (default is 100)\n * @param {number} n The quality to use 0-100\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n quality(n, cb) {\n if (typeof n !== \"number\") {\n return throwError.call(this, \"n must be a number\", cb);\n }\n\n if (n < 0 || n > 100) {\n return throwError.call(this, \"n must be a number 0 - 100\", cb);\n }\n\n this._quality = Math.round(n);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n },\n});\n"],"mappings":"AAAA,OAAOA,IAAI,MAAM,SAAS;AAC1B,SAASC,UAAU,EAAEC,aAAa,QAAQ,aAAa;AAEvD,MAAMC,SAAS,GAAG,YAAY;AAE9B,gBAAe,OAAO;EACpBC,IAAI,EAAE;IAAE,CAACD,SAAS,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK;EAAE,CAAC;EAE7CE,SAAS,EAAE;IACTC,SAAS,EAAEH;EACb,CAAC;EAEDI,QAAQ,EAAE;IACR,CAACJ,SAAS,GAAGH,IAAI,CAACQ;EACpB,CAAC;EAEDC,QAAQ,EAAE;IACR,CAACN,SAAS,GAAIO,KAAK,IAAKV,IAAI,CAACW,MAAM,CAACD,KAAK,CAACE,MAAM,EAAEF,KAAK,CAACG,QAAQ,CAAC,CAACC;EACpE,CAAC;EAEDC,KAAK,EAAE;IACL;IACAF,QAAQ,EAAE,GAAG;IACb;AACJ;AACA;AACA;AACA;AACA;IACIG,OAAO,CAACC,CAAC,EAAEC,EAAE,EAAE;MACb,IAAI,OAAOD,CAAC,KAAK,QAAQ,EAAE;QACzB,OAAOhB,UAAU,CAACkB,IAAI,CAAC,IAAI,EAAE,oBAAoB,EAAED,EAAE,CAAC;MACxD;MAEA,IAAID,CAAC,GAAG,CAAC,IAAIA,CAAC,GAAG,GAAG,EAAE;QACpB,OAAOhB,UAAU,CAACkB,IAAI,CAAC,IAAI,EAAE,4BAA4B,EAAED,EAAE,CAAC;MAChE;MAEA,IAAI,CAACL,QAAQ,GAAGO,IAAI,CAACC,KAAK,CAACJ,CAAC,CAAC;MAE7B,IAAIf,aAAa,CAACgB,EAAE,CAAC,EAAE;QACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;MAC3B;MAEA,OAAO,IAAI;IACb;EACF;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/jpeg/index.d.ts b/node_modules/@jimp/jpeg/index.d.ts new file mode 100644 index 00000000..94b86ba2 --- /dev/null +++ b/node_modules/@jimp/jpeg/index.d.ts @@ -0,0 +1,26 @@ +import { DecoderFn, EncoderFn, ImageCallback } from "@jimp/core"; + +interface JpegClass { + _quality: number; + quality: (n: number, cb?: ImageCallback) => this; +} + +interface Jpeg { + mime: { "image/jpeg": string[] }; + + constants: { + MIME_JPEG: "image/jpeg"; + }; + + encoders: { + "image/jpeg": EncoderFn; + }; + + decoders: { + "image/jpeg": DecoderFn; + }; + + class: JpegClass; +} + +export default function (): Jpeg; diff --git a/node_modules/@jimp/jpeg/package.json b/node_modules/@jimp/jpeg/package.json new file mode 100644 index 00000000..f02b8b56 --- /dev/null +++ b/node_modules/@jimp/jpeg/package.json @@ -0,0 +1,38 @@ +{ + "name": "@jimp/jpeg", + "version": "0.22.12", + "description": "Default Jimp jpeg encoder/decoder.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "jpeg-js": "^0.4.4" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/jpeg/src/index.js b/node_modules/@jimp/jpeg/src/index.js new file mode 100644 index 00000000..489c8220 --- /dev/null +++ b/node_modules/@jimp/jpeg/src/index.js @@ -0,0 +1,48 @@ +import JPEG from "jpeg-js"; +import { throwError, isNodePattern } from "@jimp/utils"; + +const MIME_TYPE = "image/jpeg"; + +export default () => ({ + mime: { [MIME_TYPE]: ["jpeg", "jpg", "jpe"] }, + + constants: { + MIME_JPEG: MIME_TYPE, + }, + + decoders: { + [MIME_TYPE]: JPEG.decode, + }, + + encoders: { + [MIME_TYPE]: (image) => JPEG.encode(image.bitmap, image._quality).data, + }, + + class: { + // The quality to be used when saving JPEG images + _quality: 100, + /** + * Sets the quality of the image when saving as JPEG format (default is 100) + * @param {number} n The quality to use 0-100 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + quality(n, cb) { + if (typeof n !== "number") { + return throwError.call(this, "n must be a number", cb); + } + + if (n < 0 || n > 100) { + return throwError.call(this, "n must be a number 0 - 100", cb); + } + + this._quality = Math.round(n); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + }, +}); diff --git a/node_modules/@jimp/jpeg/test/images/cops.jpg b/node_modules/@jimp/jpeg/test/images/cops.jpg new file mode 100644 index 00000000..f843a4f9 Binary files /dev/null and b/node_modules/@jimp/jpeg/test/images/cops.jpg differ diff --git a/node_modules/@jimp/jpeg/test/images/fillbytes.jpg b/node_modules/@jimp/jpeg/test/images/fillbytes.jpg new file mode 100644 index 00000000..981bdd5d Binary files /dev/null and b/node_modules/@jimp/jpeg/test/images/fillbytes.jpg differ diff --git a/node_modules/@jimp/jpeg/test/jpeg.test.js b/node_modules/@jimp/jpeg/test/jpeg.test.js new file mode 100644 index 00000000..5abf22d8 --- /dev/null +++ b/node_modules/@jimp/jpeg/test/jpeg.test.js @@ -0,0 +1,42 @@ +import { Jimp, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import expect from "@storybook/expect"; + +import jpeg from "../src"; + +const jimp = configure({ types: [jpeg] }, Jimp); + +describe("JPEG", () => { + const imagesDir = getTestDir(__dirname) + "/images"; + + it("load JPG", async () => { + const image = await jimp.read(imagesDir + "/cops.jpg"); + + expect(image.getPixelColor(10, 10)).toBe(0x3f4a02ff); + expect(image.getPixelColor(220, 190)).toBe(0x5d94b6ff); + expect(image.getPixelColor(350, 130)).toBe(0xdf7944ff); + }); + + it("load JPG with fill bytes", async () => { + const image = await jimp.read(imagesDir + "/fillbytes.jpg"); + + expect(image.getPixelColor(10, 10)).toBe(0xaeb8c3ff); + expect(image.getPixelColor(220, 190)).toBe(0x262b21ff); + expect(image.getPixelColor(350, 130)).toBe(0x4e5d30ff); + }); + + it("export JPG", async () => { + const image = await jimp.read({ + width: 3, + height: 3, + data: [ + 0xff0000ff, 0xff0080ff, 0xff00ffff, 0xff0080ff, 0xff00ffff, 0x8000ffff, + 0xff00ffff, 0x8000ffff, 0x0000ffff, + ], + }); + image.quality(50); + const buffer = await image.getBufferAsync("image/jpeg"); + + expect(buffer.toString()).toMatch(/^.{3,9}JFIF\u0000/); + }); +}); diff --git a/node_modules/@jimp/plugin-blit/CHANGELOG.md b/node_modules/@jimp/plugin-blit/CHANGELOG.md new file mode 100644 index 00000000..e2a54ff2 --- /dev/null +++ b/node_modules/@jimp/plugin-blit/CHANGELOG.md @@ -0,0 +1,86 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- update linting ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-blit/LICENSE b/node_modules/@jimp/plugin-blit/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-blit/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-blit/README.md b/node_modules/@jimp/plugin-blit/README.md new file mode 100644 index 00000000..7ceb4815 --- /dev/null +++ b/node_modules/@jimp/plugin-blit/README.md @@ -0,0 +1,34 @@ +
+ +

@jimp/plugin-blit

+

Blit an image.

+
+ +> Blit - a data operation commonly used in computer graphics in which several bitmaps are combined into one using a boolean function. + +## Usage + +Blits a source image on to this image + +- @param {Jimp} src image to blit +- @param {number} x the x position to blit the image +- @param {number} y the y position to blit the image +- @param {number} srcx (optional) the x position from which to crop the source image +- @param {number} srcy (optional) the y position from which to crop the source image +- @param {number} srcw (optional) the width to which to crop the source image +- @param {number} srch (optional) the height to which to crop the source image +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + const parrot = await jimp.read("test/party-parrot.png"); + + image.blit(parrot, x, y); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-blit/es/index.js b/node_modules/@jimp/plugin-blit/es/index.js new file mode 100644 index 00000000..a6b8134b --- /dev/null +++ b/node_modules/@jimp/plugin-blit/es/index.js @@ -0,0 +1,78 @@ +import { throwError, isNodePattern } from "@jimp/utils"; +export default (() => ({ + /** + * Blits a source image on to this image + * @param {Jimp} src the source Jimp instance + * @param {number} x the x position to blit the image + * @param {number} y the y position to blit the image + * @param {number} srcx (optional) the x position from which to crop the source image + * @param {number} srcy (optional) the y position from which to crop the source image + * @param {number} srcw (optional) the width to which to crop the source image + * @param {number} srch (optional) the height to which to crop the source image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + blit(src, x, y, srcx, srcy, srcw, srch, cb) { + if (!(src instanceof this.constructor)) { + return throwError.call(this, "The source must be a Jimp image", cb); + } + if (typeof x !== "number" || typeof y !== "number") { + return throwError.call(this, "x and y must be numbers", cb); + } + if (typeof srcx === "function") { + cb = srcx; + srcx = 0; + srcy = 0; + srcw = src.bitmap.width; + srch = src.bitmap.height; + } else if (typeof srcx === typeof srcy && typeof srcy === typeof srcw && typeof srcw === typeof srch) { + srcx = srcx || 0; + srcy = srcy || 0; + srcw = srcw || src.bitmap.width; + srch = srch || src.bitmap.height; + } else { + return throwError.call(this, "srcx, srcy, srcw, srch must be numbers", cb); + } + + // round input + x = Math.round(x); + y = Math.round(y); + + // round input + srcx = Math.round(srcx); + srcy = Math.round(srcy); + srcw = Math.round(srcw); + srch = Math.round(srch); + const maxWidth = this.bitmap.width; + const maxHeight = this.bitmap.height; + const baseImage = this; + src.scanQuiet(srcx, srcy, srcw, srch, function (sx, sy, idx) { + const xOffset = x + sx - srcx; + const yOffset = y + sy - srcy; + if (xOffset >= 0 && yOffset >= 0 && maxWidth - xOffset > 0 && maxHeight - yOffset > 0) { + const dstIdx = baseImage.getPixelIndex(xOffset, yOffset); + const src = { + r: this.bitmap.data[idx], + g: this.bitmap.data[idx + 1], + b: this.bitmap.data[idx + 2], + a: this.bitmap.data[idx + 3] + }; + const dst = { + r: baseImage.bitmap.data[dstIdx], + g: baseImage.bitmap.data[dstIdx + 1], + b: baseImage.bitmap.data[dstIdx + 2], + a: baseImage.bitmap.data[dstIdx + 3] + }; + baseImage.bitmap.data[dstIdx] = (src.a * (src.r - dst.r) - dst.r + 255 >> 8) + dst.r; + baseImage.bitmap.data[dstIdx + 1] = (src.a * (src.g - dst.g) - dst.g + 255 >> 8) + dst.g; + baseImage.bitmap.data[dstIdx + 2] = (src.a * (src.b - dst.b) - dst.b + 255 >> 8) + dst.b; + baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(dst.a + src.a); + } + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-blit/es/index.js.map b/node_modules/@jimp/plugin-blit/es/index.js.map new file mode 100644 index 00000000..43f3277c --- /dev/null +++ b/node_modules/@jimp/plugin-blit/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["throwError","isNodePattern","blit","src","x","y","srcx","srcy","srcw","srch","cb","constructor","call","bitmap","width","height","Math","round","maxWidth","maxHeight","baseImage","scanQuiet","sx","sy","idx","xOffset","yOffset","dstIdx","getPixelIndex","r","data","g","b","a","dst","limit255"],"sources":["../src/index.js"],"sourcesContent":["import { throwError, isNodePattern } from \"@jimp/utils\";\n\nexport default () => ({\n /**\n * Blits a source image on to this image\n * @param {Jimp} src the source Jimp instance\n * @param {number} x the x position to blit the image\n * @param {number} y the y position to blit the image\n * @param {number} srcx (optional) the x position from which to crop the source image\n * @param {number} srcy (optional) the y position from which to crop the source image\n * @param {number} srcw (optional) the width to which to crop the source image\n * @param {number} srch (optional) the height to which to crop the source image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n blit(src, x, y, srcx, srcy, srcw, srch, cb) {\n if (!(src instanceof this.constructor)) {\n return throwError.call(this, \"The source must be a Jimp image\", cb);\n }\n\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n\n if (typeof srcx === \"function\") {\n cb = srcx;\n srcx = 0;\n srcy = 0;\n srcw = src.bitmap.width;\n srch = src.bitmap.height;\n } else if (\n typeof srcx === typeof srcy &&\n typeof srcy === typeof srcw &&\n typeof srcw === typeof srch\n ) {\n srcx = srcx || 0;\n srcy = srcy || 0;\n srcw = srcw || src.bitmap.width;\n srch = srch || src.bitmap.height;\n } else {\n return throwError.call(\n this,\n \"srcx, srcy, srcw, srch must be numbers\",\n cb\n );\n }\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n\n // round input\n srcx = Math.round(srcx);\n srcy = Math.round(srcy);\n srcw = Math.round(srcw);\n srch = Math.round(srch);\n\n const maxWidth = this.bitmap.width;\n const maxHeight = this.bitmap.height;\n const baseImage = this;\n\n src.scanQuiet(srcx, srcy, srcw, srch, function (sx, sy, idx) {\n const xOffset = x + sx - srcx;\n const yOffset = y + sy - srcy;\n\n if (\n xOffset >= 0 &&\n yOffset >= 0 &&\n maxWidth - xOffset > 0 &&\n maxHeight - yOffset > 0\n ) {\n const dstIdx = baseImage.getPixelIndex(xOffset, yOffset);\n const src = {\n r: this.bitmap.data[idx],\n g: this.bitmap.data[idx + 1],\n b: this.bitmap.data[idx + 2],\n a: this.bitmap.data[idx + 3],\n };\n\n const dst = {\n r: baseImage.bitmap.data[dstIdx],\n g: baseImage.bitmap.data[dstIdx + 1],\n b: baseImage.bitmap.data[dstIdx + 2],\n a: baseImage.bitmap.data[dstIdx + 3],\n };\n\n baseImage.bitmap.data[dstIdx] =\n ((src.a * (src.r - dst.r) - dst.r + 255) >> 8) + dst.r;\n baseImage.bitmap.data[dstIdx + 1] =\n ((src.a * (src.g - dst.g) - dst.g + 255) >> 8) + dst.g;\n baseImage.bitmap.data[dstIdx + 2] =\n ((src.a * (src.b - dst.b) - dst.b + 255) >> 8) + dst.b;\n baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(\n dst.a + src.a\n );\n }\n });\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,UAAU,EAAEC,aAAa,QAAQ,aAAa;AAEvD,gBAAe,OAAO;EACpB;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,IAAI,CAACC,GAAG,EAAEC,CAAC,EAAEC,CAAC,EAAEC,IAAI,EAAEC,IAAI,EAAEC,IAAI,EAAEC,IAAI,EAAEC,EAAE,EAAE;IAC1C,IAAI,EAAEP,GAAG,YAAY,IAAI,CAACQ,WAAW,CAAC,EAAE;MACtC,OAAOX,UAAU,CAACY,IAAI,CAAC,IAAI,EAAE,iCAAiC,EAAEF,EAAE,CAAC;IACrE;IAEA,IAAI,OAAON,CAAC,KAAK,QAAQ,IAAI,OAAOC,CAAC,KAAK,QAAQ,EAAE;MAClD,OAAOL,UAAU,CAACY,IAAI,CAAC,IAAI,EAAE,yBAAyB,EAAEF,EAAE,CAAC;IAC7D;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K,GAAG,CAACL,CAAC,CAAC,GAAGK,GAAG,CAACL,CAAC,GAAG,GAAG,IAAK,CAAC,IAAIK,GAAG,CAACL,CAAC;QACxDT,SAAS,CAACP,MAAM,CAACiB,IAAI,CAACH,MAAM,GAAG,CAAC,CAAC,GAC/B,CAAExB,GAAG,CAAC8B,CAAC,IAAI9B,GAAG,CAAC4B,CAAC,GAAGG,GAAG,CAACH,CAAC,CAAC,GAAGG,GAAG,CAACH,CAAC,GAAG,GAAG,IAAK,CAAC,IAAIG,GAAG,CAACH,CAAC;QACxDX,SAAS,CAACP,MAAM,CAACiB,IAAI,CAACH,MAAM,GAAG,CAAC,CAAC,GAC/B,CAAExB,GAAG,CAAC8B,CAAC,IAAI9B,GAAG,CAAC6B,CAAC,GAAGE,GAAG,CAACF,CAAC,CAAC,GAAGE,GAAG,CAACF,CAAC,GAAG,GAAG,IAAK,CAAC,IAAIE,GAAG,CAACF,CAAC;QACxDZ,SAAS,CAACP,MAAM,CAACiB,IAAI,CAACH,MAAM,GAAG,CAAC,CAAC,GAAG,IAAI,CAAChB,WAAW,CAACwB,QAAQ,CAC3DD,GAAG,CAACD,CAAC,GAAG9B,GAAG,CAAC8B,CAAC,CACd;MACH;IACF,CAAC,CAAC;IAEF,IAAIhC,aAAa,CAACS,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-blit/index.d.ts b/node_modules/@jimp/plugin-blit/index.d.ts new file mode 100644 index 00000000..0caad70e --- /dev/null +++ b/node_modules/@jimp/plugin-blit/index.d.ts @@ -0,0 +1,17 @@ +import { Jimp, ImageCallback } from "@jimp/core"; + +interface Blit { + blit(src: Jimp, x: number, y: number, cb?: ImageCallback): this; + blit( + src: Jimp, + x: number, + y: number, + srcx: number, + srcy: number, + srcw: number, + srch: number, + cb?: ImageCallback + ): this; +} + +export default function (): Blit; diff --git a/node_modules/@jimp/plugin-blit/package.json b/node_modules/@jimp/plugin-blit/package.json new file mode 100644 index 00000000..d349e12c --- /dev/null +++ b/node_modules/@jimp/plugin-blit/package.json @@ -0,0 +1,38 @@ +{ + "name": "@jimp/plugin-blit", + "version": "0.22.12", + "description": "Blit an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/jpeg": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-blit/src/index.js b/node_modules/@jimp/plugin-blit/src/index.js new file mode 100644 index 00000000..133a5374 --- /dev/null +++ b/node_modules/@jimp/plugin-blit/src/index.js @@ -0,0 +1,105 @@ +import { throwError, isNodePattern } from "@jimp/utils"; + +export default () => ({ + /** + * Blits a source image on to this image + * @param {Jimp} src the source Jimp instance + * @param {number} x the x position to blit the image + * @param {number} y the y position to blit the image + * @param {number} srcx (optional) the x position from which to crop the source image + * @param {number} srcy (optional) the y position from which to crop the source image + * @param {number} srcw (optional) the width to which to crop the source image + * @param {number} srch (optional) the height to which to crop the source image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + blit(src, x, y, srcx, srcy, srcw, srch, cb) { + if (!(src instanceof this.constructor)) { + return throwError.call(this, "The source must be a Jimp image", cb); + } + + if (typeof x !== "number" || typeof y !== "number") { + return throwError.call(this, "x and y must be numbers", cb); + } + + if (typeof srcx === "function") { + cb = srcx; + srcx = 0; + srcy = 0; + srcw = src.bitmap.width; + srch = src.bitmap.height; + } else if ( + typeof srcx === typeof srcy && + typeof srcy === typeof srcw && + typeof srcw === typeof srch + ) { + srcx = srcx || 0; + srcy = srcy || 0; + srcw = srcw || src.bitmap.width; + srch = srch || src.bitmap.height; + } else { + return throwError.call( + this, + "srcx, srcy, srcw, srch must be numbers", + cb + ); + } + + // round input + x = Math.round(x); + y = Math.round(y); + + // round input + srcx = Math.round(srcx); + srcy = Math.round(srcy); + srcw = Math.round(srcw); + srch = Math.round(srch); + + const maxWidth = this.bitmap.width; + const maxHeight = this.bitmap.height; + const baseImage = this; + + src.scanQuiet(srcx, srcy, srcw, srch, function (sx, sy, idx) { + const xOffset = x + sx - srcx; + const yOffset = y + sy - srcy; + + if ( + xOffset >= 0 && + yOffset >= 0 && + maxWidth - xOffset > 0 && + maxHeight - yOffset > 0 + ) { + const dstIdx = baseImage.getPixelIndex(xOffset, yOffset); + const src = { + r: this.bitmap.data[idx], + g: this.bitmap.data[idx + 1], + b: this.bitmap.data[idx + 2], + a: this.bitmap.data[idx + 3], + }; + + const dst = { + r: baseImage.bitmap.data[dstIdx], + g: baseImage.bitmap.data[dstIdx + 1], + b: baseImage.bitmap.data[dstIdx + 2], + a: baseImage.bitmap.data[dstIdx + 3], + }; + + baseImage.bitmap.data[dstIdx] = + ((src.a * (src.r - dst.r) - dst.r + 255) >> 8) + dst.r; + baseImage.bitmap.data[dstIdx + 1] = + ((src.a * (src.g - dst.g) - dst.g + 255) >> 8) + dst.g; + baseImage.bitmap.data[dstIdx + 2] = + ((src.a * (src.b - dst.b) - dst.b + 255) >> 8) + dst.b; + baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255( + dst.a + src.a + ); + } + }); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-blit/test/blit.test.js b/node_modules/@jimp/plugin-blit/test/blit.test.js new file mode 100644 index 00000000..a9b71cb0 --- /dev/null +++ b/node_modules/@jimp/plugin-blit/test/blit.test.js @@ -0,0 +1,218 @@ +import { Jimp, mkJGD, getTestDir } from "@jimp/test-utils"; +import jpeg from "@jimp/jpeg"; +import configure from "@jimp/custom"; +import expect from "@storybook/expect"; + +import blit from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ types: [jpeg], plugins: [blit] }, Jimp); +const testDir = getTestDir(__dirname); + +describe("Blit over image", function () { + this.timeout(15000); + const targetJGD = mkJGD( + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆" + ); + const srcJGD = mkJGD( + "□□□□□□", + "□▥▥▥▥□", + "□▥■■▥□", + "□▥■■▥□", + "□▥▥▥▥□", + "□□□□□□" + ); + + let targetImg; + let srcImg; // stores the Jimp instances of the JGD images above. + + before((done) => { + const img1 = jimp.read(targetJGD); + const img2 = jimp.read(srcJGD); + Promise.all([img1, img2]) + .then((images) => { + targetImg = images[0]; + srcImg = images[1]; + done(); + }) + .catch(done); + }); + + it("blit on top, with no crop", () => { + expectToBeJGD( + targetImg.clone().blit(srcImg, 0, 0).getJGDSync(), + mkJGD( + "□□□□□□▸▸", + "□▥▥▥▥□▸▸", + "□▥■■▥□▸▸", + "□▥■■▥□▸▸", + "□▥▥▥▥□◆◆", + "□□□□□□◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆" + ) + ); + }); + + it("blit on middle, with no crop", () => { + expectToBeJGD( + targetImg.clone().blit(srcImg, 1, 1).getJGDSync(), + mkJGD( + "▴▴▴▴▸▸▸▸", + "▴□□□□□□▸", + "▴□▥▥▥▥□▸", + "▴□▥■■▥□▸", + "▾□▥■■▥□◆", + "▾□▥▥▥▥□◆", + "▾□□□□□□◆", + "▾▾▾▾◆◆◆◆" + ) + ); + }); + + it("blit on middle, with x,y crop", () => { + expectToBeJGD( + targetImg.clone().blit(srcImg, 2, 2, 1, 1, 5, 5).getJGDSync(), + mkJGD( + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▥▥▥▥□▸", + "▴▴▥■■▥□▸", + "▾▾▥■■▥□◆", + "▾▾▥▥▥▥□◆", + "▾▾□□□□□◆", + "▾▾▾▾◆◆◆◆" + ) + ); + }); + + it("blit on middle, with x,y,w,h crop", () => { + expectToBeJGD( + targetImg.clone().blit(srcImg, 2, 2, 1, 1, 4, 4).getJGDSync(), + mkJGD( + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▥▥▥▥▸▸", + "▴▴▥■■▥▸▸", + "▾▾▥■■▥◆◆", + "▾▾▥▥▥▥◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆" + ) + ); + }); + + it("blit partially out, on top-left", () => { + expectToBeJGD( + targetImg.clone().blit(srcImg, -1, -1).getJGDSync(), + mkJGD( + "▥▥▥▥□▸▸▸", + "▥■■▥□▸▸▸", + "▥■■▥□▸▸▸", + "▥▥▥▥□▸▸▸", + "□□□□□◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆" + ) + ); + }); + + it("blit partially out, on bottom-right", () => { + expectToBeJGD( + targetImg.clone().blit(srcImg, 3, 3).getJGDSync(), + mkJGD( + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴□□□□□", + "▾▾▾□▥▥▥▥", + "▾▾▾□▥■■▥", + "▾▾▾□▥■■▥", + "▾▾▾□▥▥▥▥" + ) + ); + }); + + it("blit alpha", async () => { + const expectedImg = await Jimp.read(testDir + "/images/blit-alpha.png"); + const dice = await Jimp.read(testDir + "/images/dice.png"); + const image = await Jimp.read(testDir + "/images/cops.jpg"); + + expect(image.blit(dice, 0, 0).bitmap.data).toEqual(expectedImg.bitmap.data); + }); + + async function createCat(catNum, len) { + const imgHeight = 60; + + const butt = await Jimp.read(testDir + "/images/cat_butt.png"); + const head = await Jimp.read(testDir + "/images/cat_head.png"); + const fuzz = await Jimp.read(testDir + "/images/cat_fuzz.png"); + + let longCat = len; + longCat = longCat > 20 ? 20 : longCat; + longCat = longCat <= 1 ? 1 : longCat; + + const cat = + Math.floor(catNum * (head.bitmap.height / imgHeight)) * imgHeight; + + const newImage = await Jimp.create( + butt.bitmap.width + head.bitmap.width + fuzz.bitmap.width * longCat, + imgHeight, + 0x00000000 + ); + + newImage.blit(butt, 0, 0, 0, cat, butt.bitmap.width, imgHeight); + for (let i = 0; i < longCat; i++) { + newImage.blit( + fuzz, + butt.bitmap.width + fuzz.bitmap.width * i, + 0, + 0, + cat, + fuzz.bitmap.width, + imgHeight + ); + } + + newImage.blit( + head, + butt.bitmap.width + fuzz.bitmap.width * longCat, + 0, + 0, + cat, + head.bitmap.width, + imgHeight + ); + + return newImage; + } + + it("uses src params correctly", async () => { + const expectedSmall = await Jimp.read( + testDir + "/images/cat-results/small-cat.png" + ); + const small = await createCat(0.3, 1); + + expect(small.bitmap.data).toEqual(expectedSmall.bitmap.data); + + const expectedMedium = await Jimp.read( + testDir + "/images/cat-results/medium-cat.png" + ); + const medium = await createCat(0.6, 7); + expect(medium.bitmap.data).toEqual(expectedMedium.bitmap.data); + + const expectedLarge = await Jimp.read( + testDir + "/images/cat-results/large-cat.png" + ); + const large = await createCat(0.9, 20); + expect(large.bitmap.data).toEqual(expectedLarge.bitmap.data); + }); +}); diff --git a/node_modules/@jimp/plugin-blit/test/images/blit-alpha.png b/node_modules/@jimp/plugin-blit/test/images/blit-alpha.png new file mode 100644 index 00000000..c5995100 Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/blit-alpha.png differ diff --git a/node_modules/@jimp/plugin-blit/test/images/cat-results/large-cat.png b/node_modules/@jimp/plugin-blit/test/images/cat-results/large-cat.png new file mode 100644 index 00000000..059852dc Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/cat-results/large-cat.png differ diff --git a/node_modules/@jimp/plugin-blit/test/images/cat-results/medium-cat.png b/node_modules/@jimp/plugin-blit/test/images/cat-results/medium-cat.png new file mode 100644 index 00000000..7da75acf Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/cat-results/medium-cat.png differ diff --git a/node_modules/@jimp/plugin-blit/test/images/cat-results/small-cat.png b/node_modules/@jimp/plugin-blit/test/images/cat-results/small-cat.png new file mode 100644 index 00000000..1cbc5d63 Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/cat-results/small-cat.png differ diff --git a/node_modules/@jimp/plugin-blit/test/images/cat_butt.png b/node_modules/@jimp/plugin-blit/test/images/cat_butt.png new file mode 100644 index 00000000..a96a1149 Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/cat_butt.png differ diff --git a/node_modules/@jimp/plugin-blit/test/images/cat_fuzz.png b/node_modules/@jimp/plugin-blit/test/images/cat_fuzz.png new file mode 100644 index 00000000..8bce44af Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/cat_fuzz.png differ diff --git a/node_modules/@jimp/plugin-blit/test/images/cat_head.png b/node_modules/@jimp/plugin-blit/test/images/cat_head.png new file mode 100644 index 00000000..c0bf9878 Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/cat_head.png differ diff --git a/node_modules/@jimp/plugin-blit/test/images/cops.jpg b/node_modules/@jimp/plugin-blit/test/images/cops.jpg new file mode 100644 index 00000000..f843a4f9 Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/cops.jpg differ diff --git a/node_modules/@jimp/plugin-blit/test/images/dice.png b/node_modules/@jimp/plugin-blit/test/images/dice.png new file mode 100644 index 00000000..b28653fb Binary files /dev/null and b/node_modules/@jimp/plugin-blit/test/images/dice.png differ diff --git a/node_modules/@jimp/plugin-blur/CHANGELOG.md b/node_modules/@jimp/plugin-blur/CHANGELOG.md new file mode 100644 index 00000000..8d029143 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/CHANGELOG.md @@ -0,0 +1,71 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-blur/LICENSE b/node_modules/@jimp/plugin-blur/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-blur/README.md b/node_modules/@jimp/plugin-blur/README.md new file mode 100644 index 00000000..caa71583 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/README.md @@ -0,0 +1,25 @@ +
+ +

@jimp/plugin-blur

+

Blur an image.

+
+ +A fast blur algorithm that produces similar effect to a Gaussian blur - but MUCH quicker + +## Usage + +- @param {number} r the pixel radius of the blur +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.blur(5); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-blur/es/blur-tables.js b/node_modules/@jimp/plugin-blur/es/blur-tables.js new file mode 100644 index 00000000..9b9b9f21 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/es/blur-tables.js @@ -0,0 +1,3 @@ +export const mulTable = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1]; +export const shgTable = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18]; +//# sourceMappingURL=blur-tables.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-blur/es/blur-tables.js.map b/node_modules/@jimp/plugin-blur/es/blur-tables.js.map new file mode 100644 index 00000000..38dcb085 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/es/blur-tables.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blur-tables.js","names":["mulTable","shgTable"],"sources":["../src/blur-tables.js"],"sourcesContent":["export const mulTable = [\n 1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107,\n 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221,\n 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103,\n 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119,\n 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151,\n 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13,\n 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75,\n 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229,\n 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183,\n 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37,\n 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61,\n 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207,\n 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178,\n 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153,\n 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133,\n 66, 131, 65, 129, 1,\n];\n\nexport const shgTable = [\n 0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18,\n 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20,\n 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21,\n 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20,\n 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22,\n 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18,\n 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22,\n 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24,\n 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24,\n 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22,\n 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23,\n 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25,\n 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25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EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAC1E,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CACnC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-blur/es/index.js b/node_modules/@jimp/plugin-blur/es/index.js new file mode 100644 index 00000000..2e198ecd --- /dev/null +++ b/node_modules/@jimp/plugin-blur/es/index.js @@ -0,0 +1,155 @@ +import { throwError, isNodePattern } from "@jimp/utils"; +import { mulTable, shgTable } from "./blur-tables"; + +/* + Superfast Blur (0.5) + http://www.quasimondo.com/BoxBlurForCanvas/FastBlur.js + + Copyright (c) 2011 Mario Klingemann + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. +*/ + +export default (() => ({ + /** + * A fast blur algorithm that produces similar effect to a Gaussian blur - but MUCH quicker + * @param {number} r the pixel radius of the blur + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + blur(r, cb) { + if (typeof r !== "number") return throwError.call(this, "r must be a number", cb); + if (r < 1) return throwError.call(this, "r must be greater than 0", cb); + let rsum; + let gsum; + let bsum; + let asum; + let x; + let y; + let i; + let p; + let p1; + let p2; + let yp; + let yi; + let yw; + let pa; + const wm = this.bitmap.width - 1; + const hm = this.bitmap.height - 1; + // const wh = this.bitmap.width * this.bitmap.height; + const rad1 = r + 1; + const mulSum = mulTable[r]; + const shgSum = shgTable[r]; + const red = []; + const green = []; + const blue = []; + const alpha = []; + const vmin = []; + const vmax = []; + let iterations = 2; + while (iterations-- > 0) { + yi = 0; + yw = 0; + for (y = 0; y < this.bitmap.height; y++) { + rsum = this.bitmap.data[yw] * rad1; + gsum = this.bitmap.data[yw + 1] * rad1; + bsum = this.bitmap.data[yw + 2] * rad1; + asum = this.bitmap.data[yw + 3] * rad1; + for (i = 1; i <= r; i++) { + p = yw + ((i > wm ? wm : i) << 2); + rsum += this.bitmap.data[p++]; + gsum += this.bitmap.data[p++]; + bsum += this.bitmap.data[p++]; + asum += this.bitmap.data[p]; + } + for (x = 0; x < this.bitmap.width; x++) { + red[yi] = rsum; + green[yi] = gsum; + blue[yi] = bsum; + alpha[yi] = asum; + if (y === 0) { + vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2; + vmax[x] = (p = x - r) > 0 ? p << 2 : 0; + } + p1 = yw + vmin[x]; + p2 = yw + vmax[x]; + rsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + gsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + bsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + asum += this.bitmap.data[p1] - this.bitmap.data[p2]; + yi++; + } + yw += this.bitmap.width << 2; + } + for (x = 0; x < this.bitmap.width; x++) { + yp = x; + rsum = red[yp] * rad1; + gsum = green[yp] * rad1; + bsum = blue[yp] * rad1; + asum = alpha[yp] * rad1; + for (i = 1; i <= r; i++) { + yp += i > hm ? 0 : this.bitmap.width; + rsum += red[yp]; + gsum += green[yp]; + bsum += blue[yp]; + asum += alpha[yp]; + } + yi = x << 2; + for (y = 0; y < this.bitmap.height; y++) { + pa = asum * mulSum >>> shgSum; + this.bitmap.data[yi + 3] = pa; + + // normalize alpha + if (pa > 255) { + this.bitmap.data[yi + 3] = 255; + } + if (pa > 0) { + pa = 255 / pa; + this.bitmap.data[yi] = (rsum * mulSum >>> shgSum) * pa; + this.bitmap.data[yi + 1] = (gsum * mulSum >>> shgSum) * pa; + this.bitmap.data[yi + 2] = (bsum * mulSum >>> shgSum) * pa; + } else { + this.bitmap.data[yi + 2] = 0; + this.bitmap.data[yi + 1] = 0; + this.bitmap.data[yi] = 0; + } + if (x === 0) { + vmin[y] = ((p = y + rad1) < hm ? p : hm) * this.bitmap.width; + vmax[y] = (p = y - r) > 0 ? p * this.bitmap.width : 0; + } + p1 = x + vmin[y]; + p2 = x + vmax[y]; + rsum += red[p1] - red[p2]; + gsum += green[p1] - green[p2]; + bsum += blue[p1] - blue[p2]; + asum += alpha[p1] - alpha[p2]; + yi += this.bitmap.width << 2; + } + } + } + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-blur/es/index.js.map b/node_modules/@jimp/plugin-blur/es/index.js.map new file mode 100644 index 00000000..33a9a6aa --- /dev/null +++ b/node_modules/@jimp/plugin-blur/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["throwError","isNodePattern","mulTable","shgTable","blur","r","cb","call","rsum","gsum","bsum","asum","x","y","i","p","p1","p2","yp","yi","yw","pa","wm","bitmap","width","hm","height","rad1","mulSum","shgSum","red","green","blue","alpha","vmin","vmax","iterations","data"],"sources":["../src/index.js"],"sourcesContent":["import { throwError, isNodePattern } from \"@jimp/utils\";\nimport { mulTable, shgTable } from \"./blur-tables\";\n\n/*\n Superfast Blur (0.5)\n http://www.quasimondo.com/BoxBlurForCanvas/FastBlur.js\n\n Copyright (c) 2011 Mario Klingemann\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n*/\n\nexport default () => ({\n /**\n * A fast blur algorithm that produces similar effect to a Gaussian blur - but MUCH quicker\n * @param {number} r the pixel radius of the blur\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n blur(r, cb) {\n if (typeof r !== \"number\")\n return throwError.call(this, \"r must be a number\", cb);\n if (r < 1) return throwError.call(this, \"r must be greater than 0\", cb);\n\n let rsum;\n let gsum;\n let bsum;\n let asum;\n let x;\n let y;\n let i;\n let p;\n let p1;\n let p2;\n let yp;\n let yi;\n let yw;\n let pa;\n\n const wm = this.bitmap.width - 1;\n const hm = this.bitmap.height - 1;\n // const wh = this.bitmap.width * this.bitmap.height;\n const rad1 = r + 1;\n\n const mulSum = mulTable[r];\n const shgSum = shgTable[r];\n\n const red = [];\n const green = [];\n const blue = [];\n const alpha = [];\n\n const vmin = [];\n const vmax = [];\n\n let iterations = 2;\n\n while (iterations-- > 0) {\n yi = 0;\n yw = 0;\n\n for (y = 0; y < this.bitmap.height; y++) {\n rsum = this.bitmap.data[yw] * rad1;\n gsum = this.bitmap.data[yw + 1] * rad1;\n bsum = this.bitmap.data[yw + 2] * rad1;\n asum = this.bitmap.data[yw + 3] * rad1;\n\n for (i = 1; i <= r; i++) {\n p = yw + ((i > wm ? wm : i) << 2);\n rsum += this.bitmap.data[p++];\n gsum += this.bitmap.data[p++];\n bsum += this.bitmap.data[p++];\n asum += this.bitmap.data[p];\n }\n\n for (x = 0; x < this.bitmap.width; x++) {\n red[yi] = rsum;\n green[yi] = gsum;\n blue[yi] = bsum;\n alpha[yi] = asum;\n\n if (y === 0) {\n vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2;\n vmax[x] = (p = x - r) > 0 ? p << 2 : 0;\n }\n\n p1 = yw + vmin[x];\n p2 = yw + vmax[x];\n\n rsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];\n gsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];\n bsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];\n asum += this.bitmap.data[p1] - this.bitmap.data[p2];\n\n yi++;\n }\n\n yw += this.bitmap.width << 2;\n }\n\n for (x = 0; x < this.bitmap.width; x++) {\n yp = x;\n rsum = red[yp] * rad1;\n gsum = green[yp] * rad1;\n bsum = blue[yp] * rad1;\n asum = alpha[yp] * rad1;\n\n for (i = 1; i <= r; i++) {\n yp += i > hm ? 0 : this.bitmap.width;\n rsum += red[yp];\n gsum += green[yp];\n bsum += blue[yp];\n asum += alpha[yp];\n }\n\n yi = x << 2;\n\n for (y = 0; y < this.bitmap.height; y++) {\n pa = (asum * mulSum) >>> shgSum;\n this.bitmap.data[yi + 3] = pa;\n\n // normalize alpha\n if (pa > 255) {\n this.bitmap.data[yi + 3] = 255;\n }\n\n if (pa > 0) {\n pa = 255 / pa;\n this.bitmap.data[yi] = ((rsum * mulSum) >>> shgSum) * pa;\n this.bitmap.data[yi + 1] = ((gsum * mulSum) >>> shgSum) * pa;\n this.bitmap.data[yi + 2] = ((bsum * mulSum) >>> shgSum) * pa;\n } else {\n this.bitmap.data[yi + 2] = 0;\n this.bitmap.data[yi + 1] = 0;\n this.bitmap.data[yi] = 0;\n }\n\n if (x === 0) {\n vmin[y] = ((p = y + rad1) < hm ? p : hm) * this.bitmap.width;\n vmax[y] = (p = y - r) > 0 ? p * this.bitmap.width : 0;\n }\n\n p1 = x + vmin[y];\n p2 = x + vmax[y];\n\n rsum += red[p1] - red[p2];\n gsum += green[p1] - green[p2];\n bsum += blue[p1] - blue[p2];\n asum += alpha[p1] - alpha[p2];\n\n yi += this.bitmap.width << 2;\n }\n }\n }\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,UAAU,EAAEC,aAAa,QAAQ,aAAa;AACvD,SAASC,QAAQ,EAAEC,QAAQ,QAAQ,eAAe;;AAElD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,gBAAe,OAAO;EACpB;AACF;AACA;AACA;AACA;AACA;EACEC,IAAI,CAACC,CAAC,EAAEC,EAAE,EAAE;IACV,IAAI,OAAOD,CAAC,KAAK,QAAQ,EACvB,OAAOL,UAAU,CAACO,IAAI,CAAC,IAAI,EAAE,oBAAoB,EAAED,EAAE,CAAC;IACxD,IAAID,CAAC,GAAG,CAAC,EAAE,OAAOL,UAAU,CAACO,IAAI,CAAC,IAAI,EAAE,0BAA0B,EAAED,EAAE,CAAC;IAEvE,IAAIE,IAAI;IACR,IAAIC,IAAI;IACR,IAAIC,IAAI;IACR,IAAIC,IAAI;IACR,IAAIC,CAAC;IACL,IAAIC,CAAC;IACL,IAAIC,CAAC;IACL,IAAIC,CAAC;IACL,IAAIC,EAAE;IACN,IAAIC,EAAE;IACN,IAAIC,EAAE;IACN,IAAIC,EAAE;IACN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,CAAC,GAAGU,EAAE,IAAI,IAAI,CAACF,MAAM,CAACC,KAAK;YAC5DW,IAAI,CAACtB,CAAC,CAAC,GAAG,CAACE,CAAC,GAAGF,CAAC,GAAGR,CAAC,IAAI,CAAC,GAAGU,CAAC,GAAG,IAAI,CAACQ,MAAM,CAACC,KAAK,GAAG,CAAC;UACvD;UAEAR,EAAE,GAAGJ,CAAC,GAAGsB,IAAI,CAACrB,CAAC,CAAC;UAChBI,EAAE,GAAGL,CAAC,GAAGuB,IAAI,CAACtB,CAAC,CAAC;UAEhBL,IAAI,IAAIsB,GAAG,CAACd,EAAE,CAAC,GAAGc,GAAG,CAACb,EAAE,CAAC;UACzBR,IAAI,IAAIsB,KAAK,CAACf,EAAE,CAAC,GAAGe,KAAK,CAACd,EAAE,CAAC;UAC7BP,IAAI,IAAIsB,IAAI,CAAChB,EAAE,CAAC,GAAGgB,IAAI,CAACf,EAAE,CAAC;UAC3BN,IAAI,IAAIsB,KAAK,CAACjB,EAAE,CAAC,GAAGiB,KAAK,CAAChB,EAAE,CAAC;UAE7BE,EAAE,IAAI,IAAI,CAACI,MAAM,CAACC,KAAK,IAAI,CAAC;QAC9B;MACF;IACF;IAEA,IAAIvB,aAAa,CAACK,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-blur/index.d.ts b/node_modules/@jimp/plugin-blur/index.d.ts new file mode 100644 index 00000000..8e325774 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/index.d.ts @@ -0,0 +1,7 @@ +import { ImageCallback } from "@jimp/core"; + +interface Blur { + blur(r: number, cb?: ImageCallback): this; +} + +export default function (): Blur; diff --git a/node_modules/@jimp/plugin-blur/package.json b/node_modules/@jimp/plugin-blur/package.json new file mode 100644 index 00000000..d8d9ce22 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/package.json @@ -0,0 +1,30 @@ +{ + "name": "@jimp/plugin-blur", + "version": "0.22.12", + "description": "blur an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-blur/src/blur-tables.js b/node_modules/@jimp/plugin-blur/src/blur-tables.js new file mode 100644 index 00000000..b6300145 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/src/blur-tables.js @@ -0,0 +1,35 @@ +export const mulTable = [ + 1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, + 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, + 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, + 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, + 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, + 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, + 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, + 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, + 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, + 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, + 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, + 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, + 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, + 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, + 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, + 66, 131, 65, 129, 1, +]; + +export const shgTable = [ + 0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, + 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, + 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, + 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, + 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, + 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, + 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, + 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, + 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, + 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, + 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, + 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, + 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, + 22, 25, 25, 25, 24, 25, 24, 25, 18, +]; diff --git a/node_modules/@jimp/plugin-blur/src/index.js b/node_modules/@jimp/plugin-blur/src/index.js new file mode 100644 index 00000000..d97ae3d6 --- /dev/null +++ b/node_modules/@jimp/plugin-blur/src/index.js @@ -0,0 +1,181 @@ +import { throwError, isNodePattern } from "@jimp/utils"; +import { mulTable, shgTable } from "./blur-tables"; + +/* + Superfast Blur (0.5) + http://www.quasimondo.com/BoxBlurForCanvas/FastBlur.js + + Copyright (c) 2011 Mario Klingemann + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. +*/ + +export default () => ({ + /** + * A fast blur algorithm that produces similar effect to a Gaussian blur - but MUCH quicker + * @param {number} r the pixel radius of the blur + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + blur(r, cb) { + if (typeof r !== "number") + return throwError.call(this, "r must be a number", cb); + if (r < 1) return throwError.call(this, "r must be greater than 0", cb); + + let rsum; + let gsum; + let bsum; + let asum; + let x; + let y; + let i; + let p; + let p1; + let p2; + let yp; + let yi; + let yw; + let pa; + + const wm = this.bitmap.width - 1; + const hm = this.bitmap.height - 1; + // const wh = this.bitmap.width * this.bitmap.height; + const rad1 = r + 1; + + const mulSum = mulTable[r]; + const shgSum = shgTable[r]; + + const red = []; + const green = []; + const blue = []; + const alpha = []; + + const vmin = []; + const vmax = []; + + let iterations = 2; + + while (iterations-- > 0) { + yi = 0; + yw = 0; + + for (y = 0; y < this.bitmap.height; y++) { + rsum = this.bitmap.data[yw] * rad1; + gsum = this.bitmap.data[yw + 1] * rad1; + bsum = this.bitmap.data[yw + 2] * rad1; + asum = this.bitmap.data[yw + 3] * rad1; + + for (i = 1; i <= r; i++) { + p = yw + ((i > wm ? wm : i) << 2); + rsum += this.bitmap.data[p++]; + gsum += this.bitmap.data[p++]; + bsum += this.bitmap.data[p++]; + asum += this.bitmap.data[p]; + } + + for (x = 0; x < this.bitmap.width; x++) { + red[yi] = rsum; + green[yi] = gsum; + blue[yi] = bsum; + alpha[yi] = asum; + + if (y === 0) { + vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2; + vmax[x] = (p = x - r) > 0 ? p << 2 : 0; + } + + p1 = yw + vmin[x]; + p2 = yw + vmax[x]; + + rsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + gsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + bsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + asum += this.bitmap.data[p1] - this.bitmap.data[p2]; + + yi++; + } + + yw += this.bitmap.width << 2; + } + + for (x = 0; x < this.bitmap.width; x++) { + yp = x; + rsum = red[yp] * rad1; + gsum = green[yp] * rad1; + bsum = blue[yp] * rad1; + asum = alpha[yp] * rad1; + + for (i = 1; i <= r; i++) { + yp += i > hm ? 0 : this.bitmap.width; + rsum += red[yp]; + gsum += green[yp]; + bsum += blue[yp]; + asum += alpha[yp]; + } + + yi = x << 2; + + for (y = 0; y < this.bitmap.height; y++) { + pa = (asum * mulSum) >>> shgSum; + this.bitmap.data[yi + 3] = pa; + + // normalize alpha + if (pa > 255) { + this.bitmap.data[yi + 3] = 255; + } + + if (pa > 0) { + pa = 255 / pa; + this.bitmap.data[yi] = ((rsum * mulSum) >>> shgSum) * pa; + this.bitmap.data[yi + 1] = ((gsum * mulSum) >>> shgSum) * pa; + this.bitmap.data[yi + 2] = ((bsum * mulSum) >>> shgSum) * pa; + } else { + this.bitmap.data[yi + 2] = 0; + this.bitmap.data[yi + 1] = 0; + this.bitmap.data[yi] = 0; + } + + if (x === 0) { + vmin[y] = ((p = y + rad1) < hm ? p : hm) * this.bitmap.width; + vmax[y] = (p = y - r) > 0 ? p * this.bitmap.width : 0; + } + + p1 = x + vmin[y]; + p2 = x + vmax[y]; + + rsum += red[p1] - red[p2]; + gsum += green[p1] - green[p2]; + bsum += blue[p1] - blue[p2]; + asum += alpha[p1] - alpha[p2]; + + yi += this.bitmap.width << 2; + } + } + } + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-circle/CHANGELOG.md b/node_modules/@jimp/plugin-circle/CHANGELOG.md new file mode 100644 index 00000000..3d839517 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/CHANGELOG.md @@ -0,0 +1,85 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-circle/LICENSE b/node_modules/@jimp/plugin-circle/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-circle/README.md b/node_modules/@jimp/plugin-circle/README.md new file mode 100644 index 00000000..689b3ab8 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/README.md @@ -0,0 +1,25 @@ +
+ +

@jimp/plugin-circle

+

Creates a circle out of an image.

+
+ +## Usage + +- @param {function(Error, Jimp)} options (optional) radius, x, y +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.circle(); + // or + image.circle({ radius: 50, x: 25, y: 25 }); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-circle/es/index.js b/node_modules/@jimp/plugin-circle/es/index.js new file mode 100644 index 00000000..94c8aa11 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/es/index.js @@ -0,0 +1,36 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Creates a circle out of an image. + * @param {function(Error, Jimp)} options (optional) radius, x, y + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + circle() { + let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + let cb = arguments.length > 1 ? arguments[1] : undefined; + if (typeof options === "function") { + cb = options; + options = {}; + } + const radius = options.radius || (this.bitmap.width > this.bitmap.height ? this.bitmap.height : this.bitmap.width) / 2; + const center = { + x: typeof options.x === "number" ? options.x : this.bitmap.width / 2, + y: typeof options.y === "number" ? options.y : this.bitmap.height / 2 + }; + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + const curR = Math.sqrt(Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2)); + if (radius - curR <= 0.0) { + this.bitmap.data[idx + 3] = 0; + } else if (radius - curR < 1.0) { + this.bitmap.data[idx + 3] = 255 * (radius - curR); + } + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-circle/es/index.js.map b/node_modules/@jimp/plugin-circle/es/index.js.map new file mode 100644 index 00000000..89b8675e --- /dev/null +++ b/node_modules/@jimp/plugin-circle/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","circle","options","cb","radius","bitmap","width","height","center","x","y","scanQuiet","idx","curR","Math","sqrt","pow","data","call"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Creates a circle out of an image.\n * @param {function(Error, Jimp)} options (optional) radius, x, y\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n circle(options = {}, cb) {\n if (typeof options === \"function\") {\n cb = options;\n options = {};\n }\n\n const radius =\n options.radius ||\n (this.bitmap.width > this.bitmap.height\n ? this.bitmap.height\n : this.bitmap.width) / 2;\n\n const center = {\n x: typeof options.x === \"number\" ? options.x : this.bitmap.width / 2,\n y: typeof options.y === \"number\" ? options.y : this.bitmap.height / 2,\n };\n\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n const curR = Math.sqrt(\n Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2)\n );\n\n if (radius - curR <= 0.0) {\n this.bitmap.data[idx + 3] = 0;\n } else if (radius - curR < 1.0) {\n this.bitmap.data[idx + 3] = 255 * (radius - curR);\n }\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,aAAa;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe,OAAO;EACpBC,MAAM,GAAmB;IAAA,IAAlBC,OAAO,uEAAG,CAAC,CAAC;IAAA,IAAEC,EAAE;IACrB,IAAI,OAAOD,OAAO,KAAK,UAAU,EAAE;MACjCC,EAAE,GAAGD,OAAO;MACZA,OAAO,GAAG,CAAC,CAAC;IACd;IAEA,MAAME,MAAM,GACVF,OAAO,CAACE,MAAM,IACd,CAAC,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AAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-circle/index.d.ts b/node_modules/@jimp/plugin-circle/index.d.ts new file mode 100644 index 00000000..302dda00 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/index.d.ts @@ -0,0 +1,15 @@ +import { ImageCallback } from "@jimp/core"; + +interface Circle { + circle( + options?: { + radius: number; + x: number; + y: number; + }, + cb?: ImageCallback + ): this; + circle(cb?: ImageCallback): this; +} + +export default function (): Circle; diff --git a/node_modules/@jimp/plugin-circle/package.json b/node_modules/@jimp/plugin-circle/package.json new file mode 100644 index 00000000..8e256cce --- /dev/null +++ b/node_modules/@jimp/plugin-circle/package.json @@ -0,0 +1,37 @@ +{ + "name": "@jimp/plugin-circle", + "version": "0.22.12", + "description": "Creates a circle out of an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-circle/src/index.js b/node_modules/@jimp/plugin-circle/src/index.js new file mode 100644 index 00000000..5d1a5c9c --- /dev/null +++ b/node_modules/@jimp/plugin-circle/src/index.js @@ -0,0 +1,51 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Creates a circle out of an image. + * @param {function(Error, Jimp)} options (optional) radius, x, y + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + circle(options = {}, cb) { + if (typeof options === "function") { + cb = options; + options = {}; + } + + const radius = + options.radius || + (this.bitmap.width > this.bitmap.height + ? this.bitmap.height + : this.bitmap.width) / 2; + + const center = { + x: typeof options.x === "number" ? options.x : this.bitmap.width / 2, + y: typeof options.y === "number" ? options.y : this.bitmap.height / 2, + }; + + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + const curR = Math.sqrt( + Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2) + ); + + if (radius - curR <= 0.0) { + this.bitmap.data[idx + 3] = 0; + } else if (radius - curR < 1.0) { + this.bitmap.data[idx + 3] = 255 * (radius - curR); + } + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-circle/test/circle.test.js b/node_modules/@jimp/plugin-circle/test/circle.test.js new file mode 100644 index 00000000..afeb6c6b --- /dev/null +++ b/node_modules/@jimp/plugin-circle/test/circle.test.js @@ -0,0 +1,79 @@ +import { Jimp, mkJGD, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import expect from "@storybook/expect"; + +import circle from "../src"; + +const jimp = configure({ plugins: [circle] }, Jimp); + +describe("Circle", () => { + it("makes a circle based on image height and width", async () => { + const expectedImg = await Jimp.read( + getTestDir(__dirname) + "/images/circled.png" + ); + const imgSrc = await jimp.read( + mkJGD( + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦" + ) + ); + + expect(imgSrc.circle().bitmap.data).toEqual(expectedImg.bitmap.data); + }); + + it("makes a circle using provided radius", async () => { + const expectedImg = await Jimp.read( + getTestDir(__dirname) + "/images/radius-3-circle.png" + ); + const imgSrc = await jimp.read( + mkJGD( + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦" + ) + ); + + expect(imgSrc.circle({ radius: 3 }).bitmap.data).toEqual( + expectedImg.bitmap.data + ); + }); + + it("should ", async () => { + const expectedImg = await Jimp.read( + getTestDir(__dirname) + "/images/x-y-circle.png" + ); + const imgSrc = await jimp.read( + mkJGD( + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦", + "▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦▦" + ) + ); + + expect(imgSrc.circle({ radius: 5, x: 5, y: 5 }).bitmap.data).toEqual( + expectedImg.bitmap.data + ); + }); +}); diff --git a/node_modules/@jimp/plugin-circle/test/images/circled.png b/node_modules/@jimp/plugin-circle/test/images/circled.png new file mode 100644 index 00000000..8128de03 Binary files /dev/null and b/node_modules/@jimp/plugin-circle/test/images/circled.png differ diff --git a/node_modules/@jimp/plugin-circle/test/images/radius-3-circle.png b/node_modules/@jimp/plugin-circle/test/images/radius-3-circle.png new file mode 100644 index 00000000..79d998d0 Binary files /dev/null and b/node_modules/@jimp/plugin-circle/test/images/radius-3-circle.png differ diff --git a/node_modules/@jimp/plugin-circle/test/images/x-y-circle.png b/node_modules/@jimp/plugin-circle/test/images/x-y-circle.png new file mode 100644 index 00000000..e102b634 Binary files /dev/null and b/node_modules/@jimp/plugin-circle/test/images/x-y-circle.png differ diff --git a/node_modules/@jimp/plugin-color/CHANGELOG.md b/node_modules/@jimp/plugin-color/CHANGELOG.md new file mode 100644 index 00000000..14f0ae49 --- /dev/null +++ b/node_modules/@jimp/plugin-color/CHANGELOG.md @@ -0,0 +1,157 @@ +# v0.22.8 (Thu May 11 2023) + +#### 🚀 Enhancement + +- Fix: convolute not defaulting to 0, 0 as starting point [#1228](https://github.com/jimp-dev/jimp/pull/1228) ([@sjoerd108](https://github.com/sjoerd108)) + +#### Authors: 1 + +- Sjoerd ([@sjoerd108](https://github.com/sjoerd108)) + +--- + +# v0.22.6 (Fri Feb 24 2023) + +:tada: This release contains work from a new contributor! :tada: + +Thank you, Daniell ([@daniellwdb](https://github.com/daniellwdb)), for all your work! + +#### 🐛 Bug Fix + +- Export ColorActionName enum [#1205](https://github.com/jimp-dev/jimp/pull/1205) ([@daniellwdb](https://github.com/daniellwdb)) + +#### Authors: 1 + +- Daniell ([@daniellwdb](https://github.com/daniellwdb)) + +--- + +# v0.22.4 (Tue Feb 07 2023) + +#### 🚀 Enhancement + +- update tinycolor2 [#1187](https://github.com/jimp-dev/jimp/pull/1187) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.17.6 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- Fix types not assignable to 'ColorActionName'. [#1086](https://github.com/jimp-dev/jimp/pull/1086) ([@lucyyyyyyy](https://github.com/lucyyyyyyy) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Lucy ([@lucyyyyyyy](https://github.com/lucyyyyyyy)) + +--- + +# v0.17.3 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- Fix EDGE_WRAP overwriting X with Y when Y < 0 [#1135](https://github.com/jimp-dev/jimp/pull/1135) ([@sjoerd108](https://github.com/sjoerd108) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Sjoerd ([@sjoerd108](https://github.com/sjoerd108)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- Fix edgeHandling types [#1080](https://github.com/jimp-dev/jimp/pull/1080) ([@domdomegg](https://github.com/domdomegg)) + +#### ⚠️ Pushed to `main` + +- update linting ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Adam Jones ([@domdomegg](https://github.com/domdomegg)) +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-color/LICENSE b/node_modules/@jimp/plugin-color/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-color/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-color/README.md b/node_modules/@jimp/plugin-color/README.md new file mode 100644 index 00000000..1b4c800f --- /dev/null +++ b/node_modules/@jimp/plugin-color/README.md @@ -0,0 +1,262 @@ +
+ +

@jimp/plugin-color

+

Jimp color methods.

+
+ +Bitmap manipulation to adjust the color in an image. + +## color + +Apply multiple color modification rules + +- @param {array} actions list of color modification rules, in following format: { apply: '', params: [ ] } +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.color([{ apply: "red", params: [100] }]); +} + +main(); +``` + +Jimp supports advanced colour manipulation using a single method as follows: + +```js +image.color([ + { apply: "hue", params: [-90] }, + { apply: "lighten", params: [50] }, + { apply: "xor", params: ["#06D"] }, +]); +``` + +The method supports the following modifiers: + +| Modifier | Description | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **lighten** {amount} | Lighten the color a given amount, from 0 to 100. Providing 100 will always return white (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **brighten** {amount} | Brighten the color a given amount, from 0 to 100 (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **darken** {amount} | Darken the color a given amount, from 0 to 100. Providing 100 will always return black (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **desaturate** {amount} | Desaturate the color a given amount, from 0 to 100. Providing 100 will is the same as calling greyscale (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **saturate** {amount} | Saturate the color a given amount, from 0 to 100 (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **greyscale** {amount} | Completely desaturates a color into greyscale (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **spin** {degree} | Spin the hue a given amount, from -360 to 360. Calling with 0, 360, or -360 will do nothing - since it sets the hue back to what it was before. (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **hue** {degree} | Alias for **spin** | +| **mix** {color, amount} | Mixes colors by their RGB component values. Amount is opacity of overlaying color | +| **tint** {amount} | Same as applying **mix** with white color | +| **shade** {amount} | Same as applying **mix** with black color | +| **xor** {color} | Treats the two colors as bitfields and applies an XOR operation to the red, green, and blue components | +| **red** {amount} | Modify Red component by a given amount | +| **green** {amount} | Modify Green component by a given amount | +| **blue** {amount} | Modify Blue component by a given amount | + +## brightness + +Adjusts the brightness of the image + +- @param {number} val the amount to adjust the brightness, a number between -1 and +1 +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.brightness(20); +} + +main(); +``` + +## contrast + +Adjusts the contrast of the image + +- @param {number} val the amount to adjust the contrast, a number between -1 and +1 +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.contrast(70); +} + +main(); +``` + +## posterize + +Apply a posterize effect + +- @param {number} n the amount to adjust the contrast, minimum threshold is two +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.posterize(5); +} + +main(); +``` + +## opacity + +Multiplies the opacity of each pixel by a factor between 0 and 1 + +- @param {number} f A number, the factor by which to multiply the opacity of each pixel +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.opacity(80); +} + +main(); +``` + +## sepia + +Applies a sepia tone to the image + +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.sepia(); +} + +main(); +``` + +## fade + +Fades each pixel by a factor between 0 and 1 + +- @param {number} f A number from 0 to 1. 0 will haven no effect. 1 will turn the image completely transparent. +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.fade(0.7); +} + +main(); +``` + +## convolution + +Sum neighbor pixels weighted by the kernel matrix. You can find a nice explanation with examples at [GIMP's Convolution Matrix plugin](https://docs.gimp.org/2.6/en/plug-in-convmatrix.html) + +- @param {array} kernel a matrix to weight the neighbors sum +- @param {number} edgeHandling (optional) define how to sum pixels from outside the border +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.convolution( + [ + [-1, -1, -1], + [-1, 8, -1], + [-1, -1, -1], + ], + jimp.EDGE_EXTEND + ); +} + +main(); +``` + +## opaque + +Set the alpha channel on every pixel to fully opaque + +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.opaque(); +} + +main(); +``` + +## pixelate + +Pixelates the image or a region + +- @param {number} size the size of the pixels +- @param {number} x (optional) the x position of the region to pixelate +- @param {number} y (optional) the y position of the region to pixelate +- @param {number} w (optional) the width of the region to pixelate +- @param {number} h (optional) the height of the region to pixelate +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.pixelate(10); +} + +main(); +``` + +## convolute + +Applies a convolution kernel to the image or a region + +- @param {array} kernel the convolution kernel +- @param {number} x (optional) the x position of the region to apply convolution to +- @param {number} y (optional) the y position of the region to apply convolution to +- @param {number} w (optional) the width of the region to apply convolution to +- @param {number} h (optional) the height of the region to apply convolution to +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + // make me better + image.pixelate(kernal); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-color/es/index.js b/node_modules/@jimp/plugin-color/es/index.js new file mode 100644 index 00000000..a10ba164 --- /dev/null +++ b/node_modules/@jimp/plugin-color/es/index.js @@ -0,0 +1,477 @@ +import tinyColor from "tinycolor2"; +import { throwError, isNodePattern } from "@jimp/utils"; +function applyKernel(im, kernel, x, y) { + const value = [0, 0, 0]; + const size = (kernel.length - 1) / 2; + for (let kx = 0; kx < kernel.length; kx += 1) { + for (let ky = 0; ky < kernel[kx].length; ky += 1) { + const idx = im.getPixelIndex(x + kx - size, y + ky - size); + value[0] += im.bitmap.data[idx] * kernel[kx][ky]; + value[1] += im.bitmap.data[idx + 1] * kernel[kx][ky]; + value[2] += im.bitmap.data[idx + 2] * kernel[kx][ky]; + } + } + return value; +} +const isDef = v => typeof v !== "undefined" && v !== null; +function greyscale(cb) { + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + const grey = parseInt(0.2126 * this.bitmap.data[idx] + 0.7152 * this.bitmap.data[idx + 1] + 0.0722 * this.bitmap.data[idx + 2], 10); + this.bitmap.data[idx] = grey; + this.bitmap.data[idx + 1] = grey; + this.bitmap.data[idx + 2] = grey; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; +} +function mix(clr, clr2) { + let p = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50; + return { + r: (clr2.r - clr.r) * (p / 100) + clr.r, + g: (clr2.g - clr.g) * (p / 100) + clr.g, + b: (clr2.b - clr.b) * (p / 100) + clr.b + }; +} +function colorFn(actions, cb) { + if (!actions || !Array.isArray(actions)) { + return throwError.call(this, "actions must be an array", cb); + } + actions = actions.map(action => { + if (action.apply === "xor" || action.apply === "mix") { + action.params[0] = tinyColor(action.params[0]).toRgb(); + } + return action; + }); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => { + let clr = { + r: this.bitmap.data[idx], + g: this.bitmap.data[idx + 1], + b: this.bitmap.data[idx + 2] + }; + const colorModifier = (i, amount) => this.constructor.limit255(clr[i] + amount); + actions.forEach(action => { + if (action.apply === "mix") { + clr = mix(clr, action.params[0], action.params[1]); + } else if (action.apply === "tint") { + clr = mix(clr, { + r: 255, + g: 255, + b: 255 + }, action.params[0]); + } else if (action.apply === "shade") { + clr = mix(clr, { + r: 0, + g: 0, + b: 0 + }, action.params[0]); + } else if (action.apply === "xor") { + clr = { + r: clr.r ^ action.params[0].r, + g: clr.g ^ action.params[0].g, + b: clr.b ^ action.params[0].b + }; + } else if (action.apply === "red") { + clr.r = colorModifier("r", action.params[0]); + } else if (action.apply === "green") { + clr.g = colorModifier("g", action.params[0]); + } else if (action.apply === "blue") { + clr.b = colorModifier("b", action.params[0]); + } else { + if (action.apply === "hue") { + action.apply = "spin"; + } + clr = tinyColor(clr); + if (!clr[action.apply]) { + return throwError.call(this, "action " + action.apply + " not supported", cb); + } + clr = clr[action.apply](...action.params).toRgb(); + } + }); + this.bitmap.data[idx] = clr.r; + this.bitmap.data[idx + 1] = clr.g; + this.bitmap.data[idx + 2] = clr.b; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; +} +export const ColorActionName = Object.freeze({ + LIGHTEN: "lighten", + BRIGHTEN: "brighten", + DARKEN: "darken", + DESATURATE: "desaturate", + SATURATE: "saturate", + GREYSCALE: "greyscale", + SPIN: "spin", + HUE: "hue", + MIX: "mix", + TINT: "tint", + SHADE: "shade", + XOR: "xor", + RED: "red", + GREEN: "green", + BLUE: "blue" +}); +export default (() => ({ + /** + * Adjusts the brightness of the image + * @param {number} val the amount to adjust the brightness, a number between -1 and +1 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + brightness(val, cb) { + if (typeof val !== "number") { + return throwError.call(this, "val must be numbers", cb); + } + if (val < -1 || val > +1) { + return throwError.call(this, "val must be a number between -1 and +1", cb); + } + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + if (val < 0.0) { + this.bitmap.data[idx] *= 1 + val; + this.bitmap.data[idx + 1] *= 1 + val; + this.bitmap.data[idx + 2] *= 1 + val; + } else { + this.bitmap.data[idx] += (255 - this.bitmap.data[idx]) * val; + this.bitmap.data[idx + 1] += (255 - this.bitmap.data[idx + 1]) * val; + this.bitmap.data[idx + 2] += (255 - this.bitmap.data[idx + 2]) * val; + } + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Adjusts the contrast of the image + * @param {number} val the amount to adjust the contrast, a number between -1 and +1 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + contrast(val, cb) { + if (typeof val !== "number") { + return throwError.call(this, "val must be numbers", cb); + } + if (val < -1 || val > +1) { + return throwError.call(this, "val must be a number between -1 and +1", cb); + } + const factor = (val + 1) / (1 - val); + function adjust(value) { + value = Math.floor(factor * (value - 127) + 127); + return value < 0 ? 0 : value > 255 ? 255 : value; + } + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data[idx] = adjust(this.bitmap.data[idx]); + this.bitmap.data[idx + 1] = adjust(this.bitmap.data[idx + 1]); + this.bitmap.data[idx + 2] = adjust(this.bitmap.data[idx + 2]); + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Apply a posterize effect + * @param {number} n the amount to adjust the contrast, minimum threshold is two + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + posterize(n, cb) { + if (typeof n !== "number") { + return throwError.call(this, "n must be numbers", cb); + } + if (n < 2) { + n = 2; + } // minimum of 2 levels + + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data[idx] = Math.floor(this.bitmap.data[idx] / 255 * (n - 1)) / (n - 1) * 255; + this.bitmap.data[idx + 1] = Math.floor(this.bitmap.data[idx + 1] / 255 * (n - 1)) / (n - 1) * 255; + this.bitmap.data[idx + 2] = Math.floor(this.bitmap.data[idx + 2] / 255 * (n - 1)) / (n - 1) * 255; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Removes colour from the image using ITU Rec 709 luminance values + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + greyscale, + // Alias of greyscale for our American friends + grayscale: greyscale, + /** + * Multiplies the opacity of each pixel by a factor between 0 and 1 + * @param {number} f A number, the factor by which to multiply the opacity of each pixel + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + opacity(f, cb) { + if (typeof f !== "number") return throwError.call(this, "f must be a number", cb); + if (f < 0 || f > 1) return throwError.call(this, "f must be a number from 0 to 1", cb); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + const v = this.bitmap.data[idx + 3] * f; + this.bitmap.data[idx + 3] = v; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Applies a sepia tone to the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + sepia(cb) { + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + let red = this.bitmap.data[idx]; + let green = this.bitmap.data[idx + 1]; + let blue = this.bitmap.data[idx + 2]; + red = red * 0.393 + green * 0.769 + blue * 0.189; + green = red * 0.349 + green * 0.686 + blue * 0.168; + blue = red * 0.272 + green * 0.534 + blue * 0.131; + this.bitmap.data[idx] = red < 255 ? red : 255; + this.bitmap.data[idx + 1] = green < 255 ? green : 255; + this.bitmap.data[idx + 2] = blue < 255 ? blue : 255; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Fades each pixel by a factor between 0 and 1 + * @param {number} f A number from 0 to 1. 0 will haven no effect. 1 will turn the image completely transparent. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + fade(f, cb) { + if (typeof f !== "number") { + return throwError.call(this, "f must be a number", cb); + } + if (f < 0 || f > 1) { + return throwError.call(this, "f must be a number from 0 to 1", cb); + } + + // this method is an alternative to opacity (which may be deprecated) + this.opacity(1 - f); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Adds each element of the image to its local neighbors, weighted by the kernel + * @param {array} kernel a matrix to weight the neighbors sum + * @param {number} edgeHandling (optional) define how to sum pixels from outside the border + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + convolution(kernel, edgeHandling, cb) { + if (typeof edgeHandling === "function" && typeof cb === "undefined") { + cb = edgeHandling; + edgeHandling = null; + } + if (!edgeHandling) { + edgeHandling = this.constructor.EDGE_EXTEND; + } + const newData = Buffer.from(this.bitmap.data); + const kRows = kernel.length; + const kCols = kernel[0].length; + const rowEnd = Math.floor(kRows / 2); + const colEnd = Math.floor(kCols / 2); + const rowIni = -rowEnd; + const colIni = -colEnd; + let weight; + let rSum; + let gSum; + let bSum; + let ri; + let gi; + let bi; + let xi; + let yi; + let idxi; + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + bSum = 0; + gSum = 0; + rSum = 0; + for (let row = rowIni; row <= rowEnd; row++) { + for (let col = colIni; col <= colEnd; col++) { + xi = x + col; + yi = y + row; + weight = kernel[row + rowEnd][col + colEnd]; + idxi = this.getPixelIndex(xi, yi, edgeHandling); + if (idxi === -1) { + bi = 0; + gi = 0; + ri = 0; + } else { + ri = this.bitmap.data[idxi + 0]; + gi = this.bitmap.data[idxi + 1]; + bi = this.bitmap.data[idxi + 2]; + } + rSum += weight * ri; + gSum += weight * gi; + bSum += weight * bi; + } + } + if (rSum < 0) { + rSum = 0; + } + if (gSum < 0) { + gSum = 0; + } + if (bSum < 0) { + bSum = 0; + } + if (rSum > 255) { + rSum = 255; + } + if (gSum > 255) { + gSum = 255; + } + if (bSum > 255) { + bSum = 255; + } + newData[idx + 0] = rSum; + newData[idx + 1] = gSum; + newData[idx + 2] = bSum; + }); + this.bitmap.data = newData; + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Set the alpha channel on every pixel to fully opaque + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + opaque(cb) { + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data[idx + 3] = 255; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Pixelates the image or a region + * @param {number} size the size of the pixels + * @param {number} x (optional) the x position of the region to pixelate + * @param {number} y (optional) the y position of the region to pixelate + * @param {number} w (optional) the width of the region to pixelate + * @param {number} h (optional) the height of the region to pixelate + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + pixelate(size, x, y, w, h, cb) { + if (typeof x === "function") { + cb = x; + h = null; + w = null; + y = null; + x = null; + } else { + if (typeof size !== "number") { + return throwError.call(this, "size must be a number", cb); + } + if (isDef(x) && typeof x !== "number") { + return throwError.call(this, "x must be a number", cb); + } + if (isDef(y) && typeof y !== "number") { + return throwError.call(this, "y must be a number", cb); + } + if (isDef(w) && typeof w !== "number") { + return throwError.call(this, "w must be a number", cb); + } + if (isDef(h) && typeof h !== "number") { + return throwError.call(this, "h must be a number", cb); + } + } + const kernel = [[1 / 16, 2 / 16, 1 / 16], [2 / 16, 4 / 16, 2 / 16], [1 / 16, 2 / 16, 1 / 16]]; + x = x || 0; + y = y || 0; + w = isDef(w) ? w : this.bitmap.width - x; + h = isDef(h) ? h : this.bitmap.height - y; + const source = this.cloneQuiet(); + this.scanQuiet(x, y, w, h, function (xx, yx, idx) { + xx = size * Math.floor(xx / size); + yx = size * Math.floor(yx / size); + const value = applyKernel(source, kernel, xx, yx); + this.bitmap.data[idx] = value[0]; + this.bitmap.data[idx + 1] = value[1]; + this.bitmap.data[idx + 2] = value[2]; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Applies a convolution kernel to the image or a region + * @param {array} kernel the convolution kernel + * @param {number} x (optional) the x position of the region to apply convolution to + * @param {number} y (optional) the y position of the region to apply convolution to + * @param {number} w (optional) the width of the region to apply convolution to + * @param {number} h (optional) the height of the region to apply convolution to + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + convolute(kernel, x, y, w, h, cb) { + if (!Array.isArray(kernel)) return throwError.call(this, "the kernel must be an array", cb); + if (typeof x === "function") { + cb = x; + x = null; + y = null; + w = null; + h = null; + } else { + if (isDef(x) && typeof x !== "number") { + return throwError.call(this, "x must be a number", cb); + } + if (isDef(y) && typeof y !== "number") { + return throwError.call(this, "y must be a number", cb); + } + if (isDef(w) && typeof w !== "number") { + return throwError.call(this, "w must be a number", cb); + } + if (isDef(h) && typeof h !== "number") { + return throwError.call(this, "h must be a number", cb); + } + } + x = isDef(x) ? x : 0; + y = isDef(y) ? y : 0; + w = isDef(w) ? w : this.bitmap.width - x; + h = isDef(h) ? h : this.bitmap.height - y; + const source = this.cloneQuiet(); + this.scanQuiet(x, y, w, h, function (xx, yx, idx) { + const value = applyKernel(source, kernel, xx, yx); + this.bitmap.data[idx] = this.constructor.limit255(value[0]); + this.bitmap.data[idx + 1] = this.constructor.limit255(value[1]); + this.bitmap.data[idx + 2] = this.constructor.limit255(value[2]); + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Apply multiple color modification rules + * @param {array} actions list of color modification rules, in following format: { apply: '', params: [ ] } + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + color: colorFn, + colour: colorFn +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-color/es/index.js.map b/node_modules/@jimp/plugin-color/es/index.js.map new file mode 100644 index 00000000..6af0367a --- /dev/null +++ b/node_modules/@jimp/plugin-color/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["tinyColor","throwError","isNodePattern","applyKernel","im","kernel","x","y","value","size","length","kx","ky","idx","getPixelIndex","bitmap","data","isDef","v","greyscale","cb","scanQuiet","width","height","grey","parseInt","call","mix","clr","clr2","p","r","g","b","colorFn","actions","Array","isArray","map","action","apply","params","toRgb","colorModifier","i","amount","constructor","limit255","forEach","ColorActionName","Object","freeze","LIGHTEN","BRIGHTEN","DARKEN","DESATURATE","SATURATE","GREYSCALE","SPIN","HUE","MIX","TINT","SHADE","XOR","RED","GREEN","BLUE","brightness","val","contrast","factor","adjust","Math","floor","posterize","n","grayscale","opacity","f","sepia","red","green","blue","fade","convolution","edgeHandling","EDGE_EXTEND","newData","Buffer","from","kRows","kCols","rowEnd","colEnd","rowIni","colIni","weight","rSum","gSum","bSum","ri","gi","bi","xi","yi","idxi","row","col","opaque","pixelate","w","h","source","cloneQuiet","xx","yx","convolute","color","colour"],"sources":["../src/index.js"],"sourcesContent":["import tinyColor from \"tinycolor2\";\nimport { throwError, isNodePattern } from \"@jimp/utils\";\n\nfunction applyKernel(im, kernel, x, y) {\n const value = [0, 0, 0];\n const size = (kernel.length - 1) / 2;\n\n for (let kx = 0; kx < kernel.length; kx += 1) {\n for (let ky = 0; ky < kernel[kx].length; ky += 1) {\n const idx = im.getPixelIndex(x + kx - size, y + ky - size);\n\n value[0] += im.bitmap.data[idx] * kernel[kx][ky];\n value[1] += im.bitmap.data[idx + 1] * kernel[kx][ky];\n value[2] += im.bitmap.data[idx + 2] * kernel[kx][ky];\n }\n }\n\n return value;\n}\n\nconst isDef = (v) => typeof v !== \"undefined\" && v !== null;\n\nfunction greyscale(cb) {\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n const grey = parseInt(\n 0.2126 * this.bitmap.data[idx] +\n 0.7152 * this.bitmap.data[idx + 1] +\n 0.0722 * this.bitmap.data[idx + 2],\n 10\n );\n\n this.bitmap.data[idx] = grey;\n this.bitmap.data[idx + 1] = grey;\n this.bitmap.data[idx + 2] = grey;\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n}\n\nfunction mix(clr, clr2, p = 50) {\n return {\n r: (clr2.r - clr.r) * (p / 100) + clr.r,\n g: (clr2.g - clr.g) * (p / 100) + clr.g,\n b: (clr2.b - clr.b) * (p / 100) + clr.b,\n };\n}\n\nfunction colorFn(actions, cb) {\n if (!actions || !Array.isArray(actions)) {\n return throwError.call(this, \"actions must be an array\", cb);\n }\n\n actions = actions.map((action) => {\n if (action.apply === \"xor\" || action.apply === \"mix\") {\n action.params[0] = tinyColor(action.params[0]).toRgb();\n }\n\n return action;\n });\n\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {\n let clr = {\n r: this.bitmap.data[idx],\n g: this.bitmap.data[idx + 1],\n b: this.bitmap.data[idx + 2],\n };\n\n const colorModifier = (i, amount) =>\n this.constructor.limit255(clr[i] + amount);\n\n actions.forEach((action) => {\n if (action.apply === \"mix\") {\n clr = mix(clr, action.params[0], action.params[1]);\n } else if (action.apply === \"tint\") {\n clr = mix(clr, { r: 255, g: 255, b: 255 }, action.params[0]);\n } else if (action.apply === \"shade\") {\n clr = mix(clr, { r: 0, g: 0, b: 0 }, action.params[0]);\n } else if (action.apply === \"xor\") {\n clr = {\n r: clr.r ^ action.params[0].r,\n g: clr.g ^ action.params[0].g,\n b: clr.b ^ action.params[0].b,\n };\n } else if (action.apply === \"red\") {\n clr.r = colorModifier(\"r\", action.params[0]);\n } else if (action.apply === \"green\") {\n clr.g = colorModifier(\"g\", action.params[0]);\n } else if (action.apply === \"blue\") {\n clr.b = colorModifier(\"b\", action.params[0]);\n } else {\n if (action.apply === \"hue\") {\n action.apply = \"spin\";\n }\n\n clr = tinyColor(clr);\n\n if (!clr[action.apply]) {\n return throwError.call(\n this,\n \"action \" + action.apply + \" not supported\",\n cb\n );\n }\n\n clr = clr[action.apply](...action.params).toRgb();\n }\n });\n\n this.bitmap.data[idx] = clr.r;\n this.bitmap.data[idx + 1] = clr.g;\n this.bitmap.data[idx + 2] = clr.b;\n });\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n}\n\nexport const ColorActionName = Object.freeze({\n LIGHTEN: \"lighten\",\n BRIGHTEN: \"brighten\",\n DARKEN: \"darken\",\n DESATURATE: \"desaturate\",\n SATURATE: \"saturate\",\n GREYSCALE: \"greyscale\",\n SPIN: \"spin\",\n HUE: \"hue\",\n MIX: \"mix\",\n TINT: \"tint\",\n SHADE: \"shade\",\n XOR: \"xor\",\n RED: \"red\",\n GREEN: \"green\",\n BLUE: \"blue\",\n});\n\nexport default () => ({\n /**\n * Adjusts the brightness of the image\n * @param {number} val the amount to adjust the brightness, a number between -1 and +1\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n brightness(val, cb) {\n if (typeof val !== \"number\") {\n return throwError.call(this, \"val must be numbers\", cb);\n }\n\n if (val < -1 || val > +1) {\n return throwError.call(\n this,\n \"val must be a number between -1 and +1\",\n cb\n );\n }\n\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n if (val < 0.0) {\n this.bitmap.data[idx] *= 1 + val;\n this.bitmap.data[idx + 1] *= 1 + val;\n this.bitmap.data[idx + 2] *= 1 + val;\n } else {\n this.bitmap.data[idx] += (255 - this.bitmap.data[idx]) * val;\n this.bitmap.data[idx + 1] += (255 - this.bitmap.data[idx + 1]) * val;\n this.bitmap.data[idx + 2] += (255 - this.bitmap.data[idx + 2]) * val;\n }\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Adjusts the contrast of the image\n * @param {number} val the amount to adjust the contrast, a number between -1 and +1\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n contrast(val, cb) {\n if (typeof val !== \"number\") {\n return throwError.call(this, \"val must be numbers\", cb);\n }\n\n if (val < -1 || val > +1) {\n return throwError.call(\n this,\n \"val must be a number between -1 and +1\",\n cb\n );\n }\n\n const factor = (val + 1) / (1 - val);\n\n function adjust(value) {\n value = Math.floor(factor * (value - 127) + 127);\n\n return value < 0 ? 0 : value > 255 ? 255 : value;\n }\n\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n this.bitmap.data[idx] = adjust(this.bitmap.data[idx]);\n this.bitmap.data[idx + 1] = adjust(this.bitmap.data[idx + 1]);\n this.bitmap.data[idx + 2] = adjust(this.bitmap.data[idx + 2]);\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Apply a posterize effect\n * @param {number} n the amount to adjust the contrast, minimum threshold is two\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n posterize(n, cb) {\n if (typeof n !== \"number\") {\n return throwError.call(this, \"n must be numbers\", cb);\n }\n\n if (n < 2) {\n n = 2;\n } // minimum of 2 levels\n\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n this.bitmap.data[idx] =\n (Math.floor((this.bitmap.data[idx] / 255) * (n - 1)) / (n - 1)) * 255;\n this.bitmap.data[idx + 1] =\n (Math.floor((this.bitmap.data[idx + 1] / 255) * (n - 1)) / (n - 1)) *\n 255;\n this.bitmap.data[idx + 2] =\n (Math.floor((this.bitmap.data[idx + 2] / 255) * (n - 1)) / (n - 1)) *\n 255;\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Removes colour from the image using ITU Rec 709 luminance values\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n greyscale,\n\n // Alias of greyscale for our American friends\n grayscale: greyscale,\n\n /**\n * Multiplies the opacity of each pixel by a factor between 0 and 1\n * @param {number} f A number, the factor by which to multiply the opacity of each pixel\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n opacity(f, cb) {\n if (typeof f !== \"number\")\n return throwError.call(this, \"f must be a number\", cb);\n if (f < 0 || f > 1)\n return throwError.call(this, \"f must be a number from 0 to 1\", cb);\n\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n const v = this.bitmap.data[idx + 3] * f;\n this.bitmap.data[idx + 3] = v;\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Applies a sepia tone to the image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n sepia(cb) {\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n let red = this.bitmap.data[idx];\n let green = this.bitmap.data[idx + 1];\n let blue = this.bitmap.data[idx + 2];\n\n red = red * 0.393 + green * 0.769 + blue * 0.189;\n green = red * 0.349 + green * 0.686 + blue * 0.168;\n blue = red * 0.272 + green * 0.534 + blue * 0.131;\n\n this.bitmap.data[idx] = red < 255 ? red : 255;\n this.bitmap.data[idx + 1] = green < 255 ? green : 255;\n this.bitmap.data[idx + 2] = blue < 255 ? blue : 255;\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Fades each pixel by a factor between 0 and 1\n * @param {number} f A number from 0 to 1. 0 will haven no effect. 1 will turn the image completely transparent.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n fade(f, cb) {\n if (typeof f !== \"number\") {\n return throwError.call(this, \"f must be a number\", cb);\n }\n\n if (f < 0 || f > 1) {\n return throwError.call(this, \"f must be a number from 0 to 1\", cb);\n }\n\n // this method is an alternative to opacity (which may be deprecated)\n this.opacity(1 - f);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Adds each element of the image to its local neighbors, weighted by the kernel\n * @param {array} kernel a matrix to weight the neighbors sum\n * @param {number} edgeHandling (optional) define how to sum pixels from outside the border\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n convolution(kernel, edgeHandling, cb) {\n if (typeof edgeHandling === \"function\" && typeof cb === \"undefined\") {\n cb = edgeHandling;\n edgeHandling = null;\n }\n\n if (!edgeHandling) {\n edgeHandling = this.constructor.EDGE_EXTEND;\n }\n\n const newData = Buffer.from(this.bitmap.data);\n const kRows = kernel.length;\n const kCols = kernel[0].length;\n const rowEnd = Math.floor(kRows / 2);\n const colEnd = Math.floor(kCols / 2);\n const rowIni = -rowEnd;\n const colIni = -colEnd;\n\n let weight;\n let rSum;\n let gSum;\n let bSum;\n let ri;\n let gi;\n let bi;\n let xi;\n let yi;\n let idxi;\n\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n bSum = 0;\n gSum = 0;\n rSum = 0;\n\n for (let row = rowIni; row <= rowEnd; row++) {\n for (let col = colIni; col <= colEnd; col++) {\n xi = x + col;\n yi = y + row;\n weight = kernel[row + rowEnd][col + colEnd];\n idxi = this.getPixelIndex(xi, yi, edgeHandling);\n\n if (idxi === -1) {\n bi = 0;\n gi = 0;\n ri = 0;\n } else {\n ri = this.bitmap.data[idxi + 0];\n gi = this.bitmap.data[idxi + 1];\n bi = this.bitmap.data[idxi + 2];\n }\n\n rSum += weight * ri;\n gSum += weight * gi;\n bSum += weight * bi;\n }\n }\n\n if (rSum < 0) {\n rSum = 0;\n }\n\n if (gSum < 0) {\n gSum = 0;\n }\n\n if (bSum < 0) {\n bSum = 0;\n }\n\n if (rSum > 255) {\n rSum = 255;\n }\n\n if (gSum > 255) {\n gSum = 255;\n }\n\n if (bSum > 255) {\n bSum = 255;\n }\n\n newData[idx + 0] = rSum;\n newData[idx + 1] = gSum;\n newData[idx + 2] = bSum;\n }\n );\n\n this.bitmap.data = newData;\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Set the alpha channel on every pixel to fully opaque\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n opaque(cb) {\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n this.bitmap.data[idx + 3] = 255;\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Pixelates the image or a region\n * @param {number} size the size of the pixels\n * @param {number} x (optional) the x position of the region to pixelate\n * @param {number} y (optional) the y position of the region to pixelate\n * @param {number} w (optional) the width of the region to pixelate\n * @param {number} h (optional) the height of the region to pixelate\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n pixelate(size, x, y, w, h, cb) {\n if (typeof x === \"function\") {\n cb = x;\n h = null;\n w = null;\n y = null;\n x = null;\n } else {\n if (typeof size !== \"number\") {\n return throwError.call(this, \"size must be a number\", cb);\n }\n\n if (isDef(x) && typeof x !== \"number\") {\n return throwError.call(this, \"x must be a number\", cb);\n }\n\n if (isDef(y) && typeof y !== \"number\") {\n return throwError.call(this, \"y must be a number\", cb);\n }\n\n if (isDef(w) && typeof w !== \"number\") {\n return throwError.call(this, \"w must be a number\", cb);\n }\n\n if (isDef(h) && typeof h !== \"number\") {\n return throwError.call(this, \"h must be a number\", cb);\n }\n }\n\n const kernel = [\n [1 / 16, 2 / 16, 1 / 16],\n [2 / 16, 4 / 16, 2 / 16],\n [1 / 16, 2 / 16, 1 / 16],\n ];\n\n x = x || 0;\n y = y || 0;\n w = isDef(w) ? w : this.bitmap.width - x;\n h = isDef(h) ? h : this.bitmap.height - y;\n\n const source = this.cloneQuiet();\n\n this.scanQuiet(x, y, w, h, function (xx, yx, idx) {\n xx = size * Math.floor(xx / size);\n yx = size * Math.floor(yx / size);\n\n const value = applyKernel(source, kernel, xx, yx);\n\n this.bitmap.data[idx] = value[0];\n this.bitmap.data[idx + 1] = value[1];\n this.bitmap.data[idx + 2] = value[2];\n });\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Applies a convolution kernel to the image or a region\n * @param {array} kernel the convolution kernel\n * @param {number} x (optional) the x position of the region to apply convolution to\n * @param {number} y (optional) the y position of the region to apply convolution to\n * @param {number} w (optional) the width of the region to apply convolution to\n * @param {number} h (optional) the height of the region to apply convolution to\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n convolute(kernel, x, y, w, h, cb) {\n if (!Array.isArray(kernel))\n return throwError.call(this, \"the kernel must be an array\", cb);\n\n if (typeof x === \"function\") {\n cb = x;\n x = null;\n y = null;\n w = null;\n h = null;\n } else {\n if (isDef(x) && typeof x !== \"number\") {\n return throwError.call(this, \"x must be a number\", cb);\n }\n\n if (isDef(y) && typeof y !== \"number\") {\n return throwError.call(this, \"y must be a number\", cb);\n }\n\n if (isDef(w) && typeof w !== \"number\") {\n return throwError.call(this, \"w must be a number\", cb);\n }\n\n if (isDef(h) && typeof h !== \"number\") {\n return throwError.call(this, \"h must be a number\", cb);\n }\n }\n\n x = isDef(x) ? x : 0;\n y = isDef(y) ? y : 0;\n w = isDef(w) ? w : this.bitmap.width - x;\n h = isDef(h) ? h : this.bitmap.height - y;\n\n const source = this.cloneQuiet();\n\n this.scanQuiet(x, y, w, h, function (xx, yx, idx) {\n const value = applyKernel(source, kernel, xx, yx);\n\n this.bitmap.data[idx] = this.constructor.limit255(value[0]);\n this.bitmap.data[idx + 1] = this.constructor.limit255(value[1]);\n this.bitmap.data[idx + 2] = this.constructor.limit255(value[2]);\n });\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Apply multiple color modification rules\n * @param {array} actions list of color modification rules, in following format: { apply: '', params: [ ] }\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n color: colorFn,\n colour: colorFn,\n});\n"],"mappings":"AAAA,OAAOA,SAAS,MAAM,YAAY;AAClC,SAASC,UAAU,EAAEC,aAAa,QAAQ,aAAa;AAEvD,SAASC,WAAW,CAACC,EAAE,EAAEC,MAAM,EAAEC,CAAC,EAAEC,CAAC,EAAE;EACrC,MAAMC,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;EACvB,MAAMC,IAAI,GAAG,CAACJ,MAAM,CAACK,MAAM,GAAG,CAAC,IAAI,CAAC;EAEpC,KAAK,IAAIC,EAAE,GAAG,CAAC,EAAEA,EAAE,GAAGN,MAAM,CAACK,MAAM,EAAEC,EAAE,IAAI,CAAC,EAAE;IAC5C,KAAK,IAAIC,EAAE,GAAG,CAAC,EAAEA,EAAE,GAAGP,MAAM,CAACM,EAAE,CAAC,CAACD,MAAM,EAAEE,EAAE,IAAI,CAAC,EAAE;MAChD,MAAMC,GAAG,GAAGT,EAAE,CAACU,aAAa,CAACR,CAAC,GAAGK,EAAE,GAAGF,IAAI,EAAEF,CAAC,GAAGK,EAAE,GAAGH,IAAI,CAAC;MAE1DD,KAAK,CAAC,CAAC,CAAC,IAAIJ,EAAE,CAACW,MAAM,CAACC,IAAI,CAACH,GAAG,CAAC,GAAGR,MAAM,CAACM,EAAE,CAAC,CAACC,EAAE,CAAC;MAChDJ,KAAK,CAAC,CAAC,CAAC,IAAIJ,EAAE,CAACW,MAA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C/D,IAAI,CAACO,MAAM,CAACC,IAAI,CAACH,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAACiC,WAAW,CAACC,QAAQ,CAACvC,KAAK,CAAC,CAAC,CAAC,CAAC;IACjE,CAAC,CAAC;IAEF,IAAIN,aAAa,CAACkB,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACM,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb,CAAC;EAED;AACF;AACA;AACA;AACA;AACA;EACE2F,KAAK,EAAEnF,OAAO;EACdoF,MAAM,EAAEpF;AACV,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-color/index.d.ts b/node_modules/@jimp/plugin-color/index.d.ts new file mode 100644 index 00000000..bdf6b3f7 --- /dev/null +++ b/node_modules/@jimp/plugin-color/index.d.ts @@ -0,0 +1,64 @@ +import { ImageCallback } from "@jimp/core"; + +export enum ColorActionName { + LIGHTEN = "lighten", + BRIGHTEN = "brighten", + DARKEN = "darken", + DESATURATE = "desaturate", + SATURATE = "saturate", + GREYSCALE = "greyscale", + SPIN = "spin", + HUE = "hue", + MIX = "mix", + TINT = "tint", + SHADE = "shade", + XOR = "xor", + RED = "red", + GREEN = "green", + BLUE = "blue", +} + +type ColorAction = { + apply: ColorActionName; + params: any; +}; + +interface Color { + brightness(val: number, cb?: ImageCallback): this; + contrast(val: number, cb?: ImageCallback): this; + posterize(n: number, cb?: ImageCallback): this; + greyscale(cb?: ImageCallback): this; + grayscale(cb?: ImageCallback): this; + opacity(f: number, cb?: ImageCallback): this; + sepia(cb?: ImageCallback): this; + fade(f: number, cb?: ImageCallback): this; + convolution(kernel: number[][], cb?: ImageCallback): this; + convolution( + kernel: number[][], + edgeHandling: number, + cb?: ImageCallback + ): this; + opaque(cb?: ImageCallback): this; + pixelate(size: number, cb?: ImageCallback): this; + pixelate( + size: number, + x: number, + y: number, + w: number, + h: number, + cb?: ImageCallback + ): this; + convolute(kernel: number[][], cb?: ImageCallback): this; + convolute( + kernel: number[][], + x: number, + y: number, + w: number, + h: number, + cb?: ImageCallback + ): this; + color(actions: ColorAction[], cb?: ImageCallback): this; + colour(actions: ColorAction[], cb?: ImageCallback): this; +} + +export default function (): Color; diff --git a/node_modules/@jimp/plugin-color/package.json b/node_modules/@jimp/plugin-color/package.json new file mode 100644 index 00000000..e31bb123 --- /dev/null +++ b/node_modules/@jimp/plugin-color/package.json @@ -0,0 +1,39 @@ +{ + "name": "@jimp/plugin-color", + "version": "0.22.12", + "description": "Bitmap manipulation to adjust the color in an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "tinycolor2": "^1.6.0" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12", + "@jimp/types": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-color/src/index.js b/node_modules/@jimp/plugin-color/src/index.js new file mode 100644 index 00000000..451bf2ce --- /dev/null +++ b/node_modules/@jimp/plugin-color/src/index.js @@ -0,0 +1,646 @@ +import tinyColor from "tinycolor2"; +import { throwError, isNodePattern } from "@jimp/utils"; + +function applyKernel(im, kernel, x, y) { + const value = [0, 0, 0]; + const size = (kernel.length - 1) / 2; + + for (let kx = 0; kx < kernel.length; kx += 1) { + for (let ky = 0; ky < kernel[kx].length; ky += 1) { + const idx = im.getPixelIndex(x + kx - size, y + ky - size); + + value[0] += im.bitmap.data[idx] * kernel[kx][ky]; + value[1] += im.bitmap.data[idx + 1] * kernel[kx][ky]; + value[2] += im.bitmap.data[idx + 2] * kernel[kx][ky]; + } + } + + return value; +} + +const isDef = (v) => typeof v !== "undefined" && v !== null; + +function greyscale(cb) { + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + const grey = parseInt( + 0.2126 * this.bitmap.data[idx] + + 0.7152 * this.bitmap.data[idx + 1] + + 0.0722 * this.bitmap.data[idx + 2], + 10 + ); + + this.bitmap.data[idx] = grey; + this.bitmap.data[idx + 1] = grey; + this.bitmap.data[idx + 2] = grey; + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; +} + +function mix(clr, clr2, p = 50) { + return { + r: (clr2.r - clr.r) * (p / 100) + clr.r, + g: (clr2.g - clr.g) * (p / 100) + clr.g, + b: (clr2.b - clr.b) * (p / 100) + clr.b, + }; +} + +function colorFn(actions, cb) { + if (!actions || !Array.isArray(actions)) { + return throwError.call(this, "actions must be an array", cb); + } + + actions = actions.map((action) => { + if (action.apply === "xor" || action.apply === "mix") { + action.params[0] = tinyColor(action.params[0]).toRgb(); + } + + return action; + }); + + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => { + let clr = { + r: this.bitmap.data[idx], + g: this.bitmap.data[idx + 1], + b: this.bitmap.data[idx + 2], + }; + + const colorModifier = (i, amount) => + this.constructor.limit255(clr[i] + amount); + + actions.forEach((action) => { + if (action.apply === "mix") { + clr = mix(clr, action.params[0], action.params[1]); + } else if (action.apply === "tint") { + clr = mix(clr, { r: 255, g: 255, b: 255 }, action.params[0]); + } else if (action.apply === "shade") { + clr = mix(clr, { r: 0, g: 0, b: 0 }, action.params[0]); + } else if (action.apply === "xor") { + clr = { + r: clr.r ^ action.params[0].r, + g: clr.g ^ action.params[0].g, + b: clr.b ^ action.params[0].b, + }; + } else if (action.apply === "red") { + clr.r = colorModifier("r", action.params[0]); + } else if (action.apply === "green") { + clr.g = colorModifier("g", action.params[0]); + } else if (action.apply === "blue") { + clr.b = colorModifier("b", action.params[0]); + } else { + if (action.apply === "hue") { + action.apply = "spin"; + } + + clr = tinyColor(clr); + + if (!clr[action.apply]) { + return throwError.call( + this, + "action " + action.apply + " not supported", + cb + ); + } + + clr = clr[action.apply](...action.params).toRgb(); + } + }); + + this.bitmap.data[idx] = clr.r; + this.bitmap.data[idx + 1] = clr.g; + this.bitmap.data[idx + 2] = clr.b; + }); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; +} + +export const ColorActionName = Object.freeze({ + LIGHTEN: "lighten", + BRIGHTEN: "brighten", + DARKEN: "darken", + DESATURATE: "desaturate", + SATURATE: "saturate", + GREYSCALE: "greyscale", + SPIN: "spin", + HUE: "hue", + MIX: "mix", + TINT: "tint", + SHADE: "shade", + XOR: "xor", + RED: "red", + GREEN: "green", + BLUE: "blue", +}); + +export default () => ({ + /** + * Adjusts the brightness of the image + * @param {number} val the amount to adjust the brightness, a number between -1 and +1 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + brightness(val, cb) { + if (typeof val !== "number") { + return throwError.call(this, "val must be numbers", cb); + } + + if (val < -1 || val > +1) { + return throwError.call( + this, + "val must be a number between -1 and +1", + cb + ); + } + + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + if (val < 0.0) { + this.bitmap.data[idx] *= 1 + val; + this.bitmap.data[idx + 1] *= 1 + val; + this.bitmap.data[idx + 2] *= 1 + val; + } else { + this.bitmap.data[idx] += (255 - this.bitmap.data[idx]) * val; + this.bitmap.data[idx + 1] += (255 - this.bitmap.data[idx + 1]) * val; + this.bitmap.data[idx + 2] += (255 - this.bitmap.data[idx + 2]) * val; + } + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Adjusts the contrast of the image + * @param {number} val the amount to adjust the contrast, a number between -1 and +1 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + contrast(val, cb) { + if (typeof val !== "number") { + return throwError.call(this, "val must be numbers", cb); + } + + if (val < -1 || val > +1) { + return throwError.call( + this, + "val must be a number between -1 and +1", + cb + ); + } + + const factor = (val + 1) / (1 - val); + + function adjust(value) { + value = Math.floor(factor * (value - 127) + 127); + + return value < 0 ? 0 : value > 255 ? 255 : value; + } + + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + this.bitmap.data[idx] = adjust(this.bitmap.data[idx]); + this.bitmap.data[idx + 1] = adjust(this.bitmap.data[idx + 1]); + this.bitmap.data[idx + 2] = adjust(this.bitmap.data[idx + 2]); + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Apply a posterize effect + * @param {number} n the amount to adjust the contrast, minimum threshold is two + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + posterize(n, cb) { + if (typeof n !== "number") { + return throwError.call(this, "n must be numbers", cb); + } + + if (n < 2) { + n = 2; + } // minimum of 2 levels + + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + this.bitmap.data[idx] = + (Math.floor((this.bitmap.data[idx] / 255) * (n - 1)) / (n - 1)) * 255; + this.bitmap.data[idx + 1] = + (Math.floor((this.bitmap.data[idx + 1] / 255) * (n - 1)) / (n - 1)) * + 255; + this.bitmap.data[idx + 2] = + (Math.floor((this.bitmap.data[idx + 2] / 255) * (n - 1)) / (n - 1)) * + 255; + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Removes colour from the image using ITU Rec 709 luminance values + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + greyscale, + + // Alias of greyscale for our American friends + grayscale: greyscale, + + /** + * Multiplies the opacity of each pixel by a factor between 0 and 1 + * @param {number} f A number, the factor by which to multiply the opacity of each pixel + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + opacity(f, cb) { + if (typeof f !== "number") + return throwError.call(this, "f must be a number", cb); + if (f < 0 || f > 1) + return throwError.call(this, "f must be a number from 0 to 1", cb); + + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + const v = this.bitmap.data[idx + 3] * f; + this.bitmap.data[idx + 3] = v; + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Applies a sepia tone to the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + sepia(cb) { + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + let red = this.bitmap.data[idx]; + let green = this.bitmap.data[idx + 1]; + let blue = this.bitmap.data[idx + 2]; + + red = red * 0.393 + green * 0.769 + blue * 0.189; + green = red * 0.349 + green * 0.686 + blue * 0.168; + blue = red * 0.272 + green * 0.534 + blue * 0.131; + + this.bitmap.data[idx] = red < 255 ? red : 255; + this.bitmap.data[idx + 1] = green < 255 ? green : 255; + this.bitmap.data[idx + 2] = blue < 255 ? blue : 255; + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Fades each pixel by a factor between 0 and 1 + * @param {number} f A number from 0 to 1. 0 will haven no effect. 1 will turn the image completely transparent. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + fade(f, cb) { + if (typeof f !== "number") { + return throwError.call(this, "f must be a number", cb); + } + + if (f < 0 || f > 1) { + return throwError.call(this, "f must be a number from 0 to 1", cb); + } + + // this method is an alternative to opacity (which may be deprecated) + this.opacity(1 - f); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Adds each element of the image to its local neighbors, weighted by the kernel + * @param {array} kernel a matrix to weight the neighbors sum + * @param {number} edgeHandling (optional) define how to sum pixels from outside the border + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + convolution(kernel, edgeHandling, cb) { + if (typeof edgeHandling === "function" && typeof cb === "undefined") { + cb = edgeHandling; + edgeHandling = null; + } + + if (!edgeHandling) { + edgeHandling = this.constructor.EDGE_EXTEND; + } + + const newData = Buffer.from(this.bitmap.data); + const kRows = kernel.length; + const kCols = kernel[0].length; + const rowEnd = Math.floor(kRows / 2); + const colEnd = Math.floor(kCols / 2); + const rowIni = -rowEnd; + const colIni = -colEnd; + + let weight; + let rSum; + let gSum; + let bSum; + let ri; + let gi; + let bi; + let xi; + let yi; + let idxi; + + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + bSum = 0; + gSum = 0; + rSum = 0; + + for (let row = rowIni; row <= rowEnd; row++) { + for (let col = colIni; col <= colEnd; col++) { + xi = x + col; + yi = y + row; + weight = kernel[row + rowEnd][col + colEnd]; + idxi = this.getPixelIndex(xi, yi, edgeHandling); + + if (idxi === -1) { + bi = 0; + gi = 0; + ri = 0; + } else { + ri = this.bitmap.data[idxi + 0]; + gi = this.bitmap.data[idxi + 1]; + bi = this.bitmap.data[idxi + 2]; + } + + rSum += weight * ri; + gSum += weight * gi; + bSum += weight * bi; + } + } + + if (rSum < 0) { + rSum = 0; + } + + if (gSum < 0) { + gSum = 0; + } + + if (bSum < 0) { + bSum = 0; + } + + if (rSum > 255) { + rSum = 255; + } + + if (gSum > 255) { + gSum = 255; + } + + if (bSum > 255) { + bSum = 255; + } + + newData[idx + 0] = rSum; + newData[idx + 1] = gSum; + newData[idx + 2] = bSum; + } + ); + + this.bitmap.data = newData; + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Set the alpha channel on every pixel to fully opaque + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + opaque(cb) { + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + this.bitmap.data[idx + 3] = 255; + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Pixelates the image or a region + * @param {number} size the size of the pixels + * @param {number} x (optional) the x position of the region to pixelate + * @param {number} y (optional) the y position of the region to pixelate + * @param {number} w (optional) the width of the region to pixelate + * @param {number} h (optional) the height of the region to pixelate + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + pixelate(size, x, y, w, h, cb) { + if (typeof x === "function") { + cb = x; + h = null; + w = null; + y = null; + x = null; + } else { + if (typeof size !== "number") { + return throwError.call(this, "size must be a number", cb); + } + + if (isDef(x) && typeof x !== "number") { + return throwError.call(this, "x must be a number", cb); + } + + if (isDef(y) && typeof y !== "number") { + return throwError.call(this, "y must be a number", cb); + } + + if (isDef(w) && typeof w !== "number") { + return throwError.call(this, "w must be a number", cb); + } + + if (isDef(h) && typeof h !== "number") { + return throwError.call(this, "h must be a number", cb); + } + } + + const kernel = [ + [1 / 16, 2 / 16, 1 / 16], + [2 / 16, 4 / 16, 2 / 16], + [1 / 16, 2 / 16, 1 / 16], + ]; + + x = x || 0; + y = y || 0; + w = isDef(w) ? w : this.bitmap.width - x; + h = isDef(h) ? h : this.bitmap.height - y; + + const source = this.cloneQuiet(); + + this.scanQuiet(x, y, w, h, function (xx, yx, idx) { + xx = size * Math.floor(xx / size); + yx = size * Math.floor(yx / size); + + const value = applyKernel(source, kernel, xx, yx); + + this.bitmap.data[idx] = value[0]; + this.bitmap.data[idx + 1] = value[1]; + this.bitmap.data[idx + 2] = value[2]; + }); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Applies a convolution kernel to the image or a region + * @param {array} kernel the convolution kernel + * @param {number} x (optional) the x position of the region to apply convolution to + * @param {number} y (optional) the y position of the region to apply convolution to + * @param {number} w (optional) the width of the region to apply convolution to + * @param {number} h (optional) the height of the region to apply convolution to + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + convolute(kernel, x, y, w, h, cb) { + if (!Array.isArray(kernel)) + return throwError.call(this, "the kernel must be an array", cb); + + if (typeof x === "function") { + cb = x; + x = null; + y = null; + w = null; + h = null; + } else { + if (isDef(x) && typeof x !== "number") { + return throwError.call(this, "x must be a number", cb); + } + + if (isDef(y) && typeof y !== "number") { + return throwError.call(this, "y must be a number", cb); + } + + if (isDef(w) && typeof w !== "number") { + return throwError.call(this, "w must be a number", cb); + } + + if (isDef(h) && typeof h !== "number") { + return throwError.call(this, "h must be a number", cb); + } + } + + x = isDef(x) ? x : 0; + y = isDef(y) ? y : 0; + w = isDef(w) ? w : this.bitmap.width - x; + h = isDef(h) ? h : this.bitmap.height - y; + + const source = this.cloneQuiet(); + + this.scanQuiet(x, y, w, h, function (xx, yx, idx) { + const value = applyKernel(source, kernel, xx, yx); + + this.bitmap.data[idx] = this.constructor.limit255(value[0]); + this.bitmap.data[idx + 1] = this.constructor.limit255(value[1]); + this.bitmap.data[idx + 2] = this.constructor.limit255(value[2]); + }); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Apply multiple color modification rules + * @param {array} actions list of color modification rules, in following format: { apply: '', params: [ ] } + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + color: colorFn, + colour: colorFn, +}); diff --git a/node_modules/@jimp/plugin-color/test/color.test.js b/node_modules/@jimp/plugin-color/test/color.test.js new file mode 100644 index 00000000..f7d91e52 --- /dev/null +++ b/node_modules/@jimp/plugin-color/test/color.test.js @@ -0,0 +1,50 @@ +import { Jimp, donutJGD } from "@jimp/test-utils"; +import configure from "@jimp/custom"; + +import color from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [color] }, Jimp); + +describe("canvas color transformation", () => { + const redDonutJGD = donutJGD(0x00000000, 0xff000088, 0xff0000ff); + + it("can apply more than one color transformation", async () => { + const image = await jimp.read(redDonutJGD); + const newJGD = image + .color([ + { apply: "hue", params: [-180] }, + { apply: "lighten", params: [25] }, + ]) + .getJGDSync(); + + expectToBeJGD(newJGD, donutJGD(0x40404000, 0x80ffff88, 0x80ffffff)); + }); + + it("lighten", async () => { + const image = await jimp.read(redDonutJGD); + + expectToBeJGD( + image.color([{ apply: "lighten", params: [25] }]).getJGDSync(), + donutJGD(0x40404000, 0xff808088, 0xff8080ff) + ); + }); + + it("brighten", async () => { + const image = await jimp.read(redDonutJGD); + + expectToBeJGD( + image.color([{ apply: "brighten", params: [25] }]).getJGDSync(), + donutJGD(0x40404000, 0xff404088, 0xff4040ff) + ); + }); + + it("spin hue", async () => { + const image = await jimp.read(redDonutJGD); + + expectToBeJGD( + image.color([{ apply: "hue", params: [150] }]).getJGDSync(), + donutJGD(0x00000000, 0x00ff8088, 0x00ff80ff) + ); + }); +}); diff --git a/node_modules/@jimp/plugin-color/test/convolution.test.js b/node_modules/@jimp/plugin-color/test/convolution.test.js new file mode 100644 index 00000000..e7abca10 --- /dev/null +++ b/node_modules/@jimp/plugin-color/test/convolution.test.js @@ -0,0 +1,185 @@ +import { Jimp, mkJGD, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import types from "@jimp/types"; +import expect from "@storybook/expect"; + +import color from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ types: [types], plugins: [color] }, Jimp); + +describe("Convolution", function () { + this.timeout(15000); + + const imgs = [ + jimp.read( + mkJGD( + "22222222", + "22222222", + "22888822", + "22888822", + "22888822", + "22888822", + "22222222", + "22222222" + ) + ), + jimp.read( + mkJGD( + "88222222", + "88222222", + "22222222", + "22222222", + "22222222", + "22222222", + "22222222", + "22222222" + ) + ), + ]; + + let imgMid; + let imgTopLeft; // stores the Jimp instances of the JGD images above. + + before((done) => { + Promise.all(imgs) + .then((imgs) => { + imgMid = imgs[0]; + imgTopLeft = imgs[1]; + done(); + }) + .catch(done); + }); + + const sharpM = [ + [-1, -1, 0], + [-1, 1, 1], + [0, 1, 1], + ]; + + const blurM = [ + [1 / 9, 1 / 9, 1 / 9], + [1 / 9, 1 / 9, 1 / 9], + [1 / 9, 1 / 9, 1 / 9], + ]; + + it("3x3 sharp matrix on EDGE_EXTEND", (done) => { + expectToBeJGD( + imgMid.clone().convolution(sharpM).getJGDSync(), + mkJGD( + "22222222", + "28EEE822", + "2EFFF802", + "2EF88002", + "2EF88002", + "28800002", + "22000002", + "22222222" + ) + ); + + expectToBeJGD( + imgTopLeft.clone().convolution(sharpM).getJGDSync(), + mkJGD( + "80022222", + "00022222", + "00022222", + "22222222", + "22222222", + "22222222", + "22222222", + "22222222" + ) + ); + done(); + }); + + it("3x3 sharp matrix on EDGE_WRAP", (done) => { + expectToBeJGD( + imgMid.clone().convolution(sharpM, jimp.EDGE_WRAP).getJGDSync(), + mkJGD( + "22222222", + "28EEE822", + "2EFFF802", + "2EF88002", + "2EF88002", + "28800002", + "22000002", + "22222222" + ) + ); + + expectToBeJGD( + imgTopLeft.clone().convolution(sharpM, jimp.EDGE_WRAP).getJGDSync(), + mkJGD( + "F802222E", + "80022228", + "00022222", + "22222222", + "22222222", + "22222222", + "22222222", + "E8222228" + ) + ); + done(); + }); + + it("3x3 sharp matrix on EDGE_CROP", (done) => { + expectToBeJGD( + imgMid.clone().convolution(sharpM, jimp.EDGE_CROP).getJGDSync(), + mkJGD( + "86666662", + "68EEE820", + "6EFFF800", + "6EF88000", + "6EF88000", + "68800000", + "62000000", + "20000000" + ) + ); + + expectToBeJGD( + imgTopLeft.clone().convolution(sharpM, jimp.EDGE_CROP).getJGDSync(), + mkJGD( + "FC066662", + "C0022220", + "00022220", + "62222220", + "62222220", + "62222220", + "62222220", + "20000000" + ) + ); + done(); + }); + + it("3x3 box blur matrix using convolute", async () => { + const expectedImg = await jimp.read( + getTestDir(__dirname) + "/images/tiles-blurred.png" + ); + + const image = await jimp.read(getTestDir(__dirname) + "/images/tiles.jpg"); + + expect(image.convolute(blurM).bitmap.data).toEqual(expectedImg.bitmap.data); + }); + + it("new pixel value is greater than 255", async () => { + const expectedImg = await jimp.read( + getTestDir(__dirname) + "/images/qr-convoluted.png" + ); + const image = await jimp.read(getTestDir(__dirname) + "/images/qr.jpg"); + + expect( + image.convolution([ + [0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0], + ]).bitmap.data + ).toEqual(expectedImg.bitmap.data); + }); +}); diff --git a/node_modules/@jimp/plugin-color/test/images/qr-convoluted.png b/node_modules/@jimp/plugin-color/test/images/qr-convoluted.png new file mode 100644 index 00000000..9b42e016 Binary files /dev/null and b/node_modules/@jimp/plugin-color/test/images/qr-convoluted.png differ diff --git a/node_modules/@jimp/plugin-color/test/images/qr.jpg b/node_modules/@jimp/plugin-color/test/images/qr.jpg new file mode 100644 index 00000000..b2cc618b Binary files /dev/null and b/node_modules/@jimp/plugin-color/test/images/qr.jpg differ diff --git a/node_modules/@jimp/plugin-color/test/images/tiles-blurred.png b/node_modules/@jimp/plugin-color/test/images/tiles-blurred.png new file mode 100644 index 00000000..5b3da9b6 Binary files /dev/null and b/node_modules/@jimp/plugin-color/test/images/tiles-blurred.png differ diff --git a/node_modules/@jimp/plugin-color/test/images/tiles.jpg b/node_modules/@jimp/plugin-color/test/images/tiles.jpg new file mode 100644 index 00000000..538c77e4 Binary files /dev/null and b/node_modules/@jimp/plugin-color/test/images/tiles.jpg differ diff --git a/node_modules/@jimp/plugin-contain/CHANGELOG.md b/node_modules/@jimp/plugin-contain/CHANGELOG.md new file mode 100644 index 00000000..3d839517 --- /dev/null +++ b/node_modules/@jimp/plugin-contain/CHANGELOG.md @@ -0,0 +1,85 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-contain/LICENSE b/node_modules/@jimp/plugin-contain/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-contain/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-contain/README.md b/node_modules/@jimp/plugin-contain/README.md new file mode 100644 index 00000000..187cdc75 --- /dev/null +++ b/node_modules/@jimp/plugin-contain/README.md @@ -0,0 +1,59 @@ +
+ +

@jimp/plugin-contain

+

Contain an image within a height and width.

+
+ +Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed. + +## Usage + +- @param {number} w the width to resize the image to +- @param {number} h the height to resize the image to +- @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment +- @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.contain(150, 100); +} + +main(); +``` + +### Align modes + +The following constants can be passed to `image.contain`: + +```js +Jimp.HORIZONTAL_ALIGN_LEFT; +Jimp.HORIZONTAL_ALIGN_CENTER; +Jimp.HORIZONTAL_ALIGN_RIGHT; + +Jimp.VERTICAL_ALIGN_TOP; +Jimp.VERTICAL_ALIGN_MIDDLE; +Jimp.VERTICAL_ALIGN_BOTTOM; +``` + +For example: + +```js +image.contain(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP); +image.contain( + 250, + 250, + Jimp.HORIZONTAL_ALIGN_RIGHT | Jimp.VERTICAL_ALIGN_BOTTOM +); +``` + +Default align mode for `image.contain` is: + +```js +Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE; +``` diff --git a/node_modules/@jimp/plugin-contain/es/index.js b/node_modules/@jimp/plugin-contain/es/index.js new file mode 100644 index 00000000..837d35d4 --- /dev/null +++ b/node_modules/@jimp/plugin-contain/es/index.js @@ -0,0 +1,57 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + contain(w, h, alignBits, mode, cb) { + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + + // permit any sort of optional parameters combination + if (typeof alignBits === "string") { + if (typeof mode === "function" && typeof cb === "undefined") cb = mode; + mode = alignBits; + alignBits = null; + } + if (typeof alignBits === "function") { + if (typeof cb === "undefined") cb = alignBits; + mode = null; + alignBits = null; + } + if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE; + const hbits = alignBits & (1 << 3) - 1; + const vbits = alignBits >> 3; + + // check if more flags than one is in the bit sets + if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) { + return throwError.call(this, "only use one flag per alignment direction", cb); + } + const alignH = hbits >> 1; // 0, 1, 2 + const alignV = vbits >> 1; // 0, 1, 2 + + const f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width; + const c = this.cloneQuiet().scale(f, mode); + this.resize(w, h, mode); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data.writeUInt32BE(this._background, idx); + }); + this.blit(c, (this.bitmap.width - c.bitmap.width) / 2 * alignH, (this.bitmap.height - c.bitmap.height) / 2 * alignV); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-contain/es/index.js.map b/node_modules/@jimp/plugin-contain/es/index.js.map new file mode 100644 index 00000000..9107a9a5 --- /dev/null +++ b/node_modules/@jimp/plugin-contain/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","contain","w","h","alignBits","mode","cb","call","constructor","HORIZONTAL_ALIGN_CENTER","VERTICAL_ALIGN_MIDDLE","hbits","vbits","alignH","alignV","f","bitmap","width","height","c","cloneQuiet","scale","resize","scanQuiet","x","y","idx","data","writeUInt32BE","_background","blit"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed.\n * @param {number} w the width to resize the image to\n * @param {number} h the height to resize the image to\n * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n contain(w, h, alignBits, mode, cb) {\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n\n // permit any sort of optional parameters combination\n if (typeof alignBits === \"string\") {\n if (typeof mode === \"function\" && typeof cb === \"undefined\") cb = mode;\n mode = alignBits;\n alignBits = null;\n }\n\n if (typeof alignBits === \"function\") {\n if (typeof cb === \"undefined\") cb = alignBits;\n mode = null;\n alignBits = null;\n }\n\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n\n alignBits =\n alignBits ||\n this.constructor.HORIZONTAL_ALIGN_CENTER |\n this.constructor.VERTICAL_ALIGN_MIDDLE;\n const hbits = alignBits & ((1 << 3) - 1);\n const vbits = alignBits >> 3;\n\n // check if more flags than one is in the bit sets\n if (\n !(\n (hbits !== 0 && !(hbits & (hbits - 1))) ||\n (vbits !== 0 && !(vbits & (vbits - 1)))\n )\n ) {\n return throwError.call(\n this,\n \"only use one flag per alignment direction\",\n cb\n );\n }\n\n const alignH = hbits >> 1; // 0, 1, 2\n const alignV = vbits >> 1; // 0, 1, 2\n\n const f =\n w / h > this.bitmap.width / this.bitmap.height\n ? h / this.bitmap.height\n : w / this.bitmap.width;\n const c = this.cloneQuiet().scale(f, mode);\n\n this.resize(w, h, mode);\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n this.bitmap.data.writeUInt32BE(this._background, idx);\n }\n );\n this.blit(\n c,\n ((this.bitmap.width - c.bitmap.width) / 2) * alignH,\n ((this.bitmap.height - c.bitmap.height) / 2) * alignV\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;;AAEvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe,OAAO;EACpBC,OAAO,CAACC,CAAC,EAAEC,CAAC,EAAEC,SAAS,EAAEC,IAAI,EAAEC,EAAE,EAAE;IACjC,IAAI,OAAOJ,CAAC,KAAK,QAAQ,IAAI,OAAOC,CAAC,KAAK,QAAQ,EAAE;MAClD,OAAOH,UAAU,CAACO,IAAI,CAAC,IAAI,EAAE,yBAAyB,EAAED,EAAE,CAAC;IAC7D;;IAEA;IACA,IAAI,OAAOF,SAAS,KAAK,QAAQ,EAAE;MACjC,IAAI,OAAOC,IAAI,KAAK,UAAU,IAAI,OAAOC,EAAE,KAAK,WAAW,EAAEA,EAAE,GAAGD,IAAI;MACtEA,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CAAC,EAAEV,IAAI,CAAC;IAE1C,IAAI,CAACiB,MAAM,CAACpB,CAAC,EAAEC,CAAC,EAAEE,IAAI,CAAC;IACvB,IAAI,CAACkB,SAAS,CACZ,CAAC,EACD,CAAC,EACD,IAAI,CAACP,MAAM,CAACC,KAAK,EACjB,IAAI,CAACD,MAAM,CAACE,MAAM,EAClB,UAAUM,CAAC,EAAEC,CAAC,EAAEC,GAAG,EAAE;MACnB,IAAI,CAACV,MAAM,CAACW,IAAI,CAACC,aAAa,CAAC,IAAI,CAACC,WAAW,EAAEH,GAAG,CAAC;IACvD,CAAC,CACF;IACD,IAAI,CAACI,IAAI,CACPX,CAAC,EACA,CAAC,IAAI,CAACH,MAAM,CAACC,KAAK,GAAGE,CAAC,CAACH,MAAM,CAACC,KAAK,IAAI,CAAC,GAAIJ,MAAM,EAClD,CAAC,IAAI,CAACG,MAAM,CAACE,MAAM,GAAGC,CAAC,CAACH,MAAM,CAACE,MAAM,IAAI,CAAC,GAAIJ,MAAM,CACtD;IAED,IAAIf,aAAa,CAACO,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-contain/index.d.ts b/node_modules/@jimp/plugin-contain/index.d.ts new file mode 100644 index 00000000..8c3306d3 --- /dev/null +++ b/node_modules/@jimp/plugin-contain/index.d.ts @@ -0,0 +1,21 @@ +import { ImageCallback } from "@jimp/core"; + +interface Contain { + contain(w: number, h: number, cb?: ImageCallback): this; + contain(w: number, h: number, mode?: string, cb?: ImageCallback): this; + contain( + w: number, + h: number, + alignBits?: number, + cb?: ImageCallback + ): this; + contain( + w: number, + h: number, + alignBits?: number, + mode?: string, + cb?: ImageCallback + ): this; +} + +export default function (): Contain; diff --git a/node_modules/@jimp/plugin-contain/package.json b/node_modules/@jimp/plugin-contain/package.json new file mode 100644 index 00000000..7f4048fc --- /dev/null +++ b/node_modules/@jimp/plugin-contain/package.json @@ -0,0 +1,43 @@ +{ + "name": "@jimp/plugin-contain", + "version": "0.22.12", + "description": "contain an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-blit": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5", + "@jimp/plugin-scale": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/plugin-blit": "^0.22.12", + "@jimp/plugin-resize": "^0.22.12", + "@jimp/plugin-scale": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-contain/src/index.js b/node_modules/@jimp/plugin-contain/src/index.js new file mode 100644 index 00000000..1736343c --- /dev/null +++ b/node_modules/@jimp/plugin-contain/src/index.js @@ -0,0 +1,88 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + contain(w, h, alignBits, mode, cb) { + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + + // permit any sort of optional parameters combination + if (typeof alignBits === "string") { + if (typeof mode === "function" && typeof cb === "undefined") cb = mode; + mode = alignBits; + alignBits = null; + } + + if (typeof alignBits === "function") { + if (typeof cb === "undefined") cb = alignBits; + mode = null; + alignBits = null; + } + + if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + + alignBits = + alignBits || + this.constructor.HORIZONTAL_ALIGN_CENTER | + this.constructor.VERTICAL_ALIGN_MIDDLE; + const hbits = alignBits & ((1 << 3) - 1); + const vbits = alignBits >> 3; + + // check if more flags than one is in the bit sets + if ( + !( + (hbits !== 0 && !(hbits & (hbits - 1))) || + (vbits !== 0 && !(vbits & (vbits - 1))) + ) + ) { + return throwError.call( + this, + "only use one flag per alignment direction", + cb + ); + } + + const alignH = hbits >> 1; // 0, 1, 2 + const alignV = vbits >> 1; // 0, 1, 2 + + const f = + w / h > this.bitmap.width / this.bitmap.height + ? h / this.bitmap.height + : w / this.bitmap.width; + const c = this.cloneQuiet().scale(f, mode); + + this.resize(w, h, mode); + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + this.bitmap.data.writeUInt32BE(this._background, idx); + } + ); + this.blit( + c, + ((this.bitmap.width - c.bitmap.width) / 2) * alignH, + ((this.bitmap.height - c.bitmap.height) / 2) * alignV + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-contain/test/contain.test.js b/node_modules/@jimp/plugin-contain/test/contain.test.js new file mode 100644 index 00000000..43e0fb42 --- /dev/null +++ b/node_modules/@jimp/plugin-contain/test/contain.test.js @@ -0,0 +1,130 @@ +import { Jimp, mkJGD, hasOwnProp } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import blit from "@jimp/plugin-blit"; +import resize from "@jimp/plugin-resize"; +import scale from "@jimp/plugin-scale"; + +import contain from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [scale, resize, blit, contain] }, Jimp); + +describe("All align combinations for contain", () => { + const verticalJGD = mkJGD( + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆" + ); + + const horizontalJGD = mkJGD( + "▴▴▴▴▴▴▸▸▸▸▸▸", + "▴▴▴▴▴▴▸▸▸▸▸▸", + "▴▴▴▴▴▴▸▸▸▸▸▸", + "▴▴▴▴▴▴▸▸▸▸▸▸", + "▾▾▾▾▾▾◆◆◆◆◆◆", + "▾▾▾▾▾▾◆◆◆◆◆◆", + "▾▾▾▾▾▾◆◆◆◆◆◆", + "▾▾▾▾▾▾◆◆◆◆◆◆" + ); + + let vertical; + let horizontal; // stores the Jimp instances of the JGD images above. + + before((done) => { + const img1 = jimp.read(verticalJGD); + const img2 = jimp.read(horizontalJGD); + Promise.all([img1, img2]) + .then((images) => { + vertical = images[0]; + horizontal = images[1]; + done(); + }) + .catch(done); + }); + + const tests = {}; // Stores the expected result for each alignment combination. + tests["LEFT TOP"] = { + contain: { + verti: mkJGD("▴▴▸▸ ", "▴▴▸▸ ", "▴▴▸▸ ", "▾▾◆◆ ", "▾▾◆◆ ", "▾▾◆◆ "), + horiz: mkJGD("▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆", " ", " "), + }, + }; + tests["CENTER TOP"] = { + contain: { + verti: mkJGD(" ▴▴▸▸ ", " ▴▴▸▸ ", " ▴▴▸▸ ", " ▾▾◆◆ ", " ▾▾◆◆ ", " ▾▾◆◆ "), + horiz: mkJGD("▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆", " ", " "), + }, + }; + tests["RIGHT TOP"] = { + contain: { + verti: mkJGD(" ▴▴▸▸", " ▴▴▸▸", " ▴▴▸▸", " ▾▾◆◆", " ▾▾◆◆", " ▾▾◆◆"), + horiz: mkJGD("▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆", " ", " "), + }, + }; + + tests["LEFT MIDDLE"] = { + contain: { + verti: mkJGD("▴▴▸▸ ", "▴▴▸▸ ", "▴▴▸▸ ", "▾▾◆◆ ", "▾▾◆◆ ", "▾▾◆◆ "), + horiz: mkJGD(" ", "▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆", " "), + }, + }; + tests["CENTER MIDDLE"] = { + contain: { + verti: mkJGD(" ▴▴▸▸ ", " ▴▴▸▸ ", " ▴▴▸▸ ", " ▾▾◆◆ ", " ▾▾◆◆ ", " ▾▾◆◆ "), + horiz: mkJGD(" ", "▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆", " "), + }, + }; + tests["RIGHT MIDDLE"] = { + contain: { + verti: mkJGD(" ▴▴▸▸", " ▴▴▸▸", " ▴▴▸▸", " ▾▾◆◆", " ▾▾◆◆", " ▾▾◆◆"), + horiz: mkJGD(" ", "▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆", " "), + }, + }; + + tests["LEFT BOTTOM"] = { + contain: { + verti: mkJGD("▴▴▸▸ ", "▴▴▸▸ ", "▴▴▸▸ ", "▾▾◆◆ ", "▾▾◆◆ ", "▾▾◆◆ "), + horiz: mkJGD(" ", " ", "▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆"), + }, + }; + tests["CENTER BOTTOM"] = { + contain: { + verti: mkJGD(" ▴▴▸▸ ", " ▴▴▸▸ ", " ▴▴▸▸ ", " ▾▾◆◆ ", " ▾▾◆◆ ", " ▾▾◆◆ "), + horiz: mkJGD(" ", " ", "▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆"), + }, + }; + tests["RIGHT BOTTOM"] = { + contain: { + verti: mkJGD(" ▴▴▸▸", " ▴▴▸▸", " ▴▴▸▸", " ▾▾◆◆", " ▾▾◆◆", " ▾▾◆◆"), + horiz: mkJGD(" ", " ", "▴▴▴▸▸▸", "▴▴▴▸▸▸", "▾▾▾◆◆◆", "▾▾▾◆◆◆"), + }, + }; + + function runAlignTest(align) { + const jgdContainV = tests[align].contain.verti; + const jgdContainH = tests[align].contain.horiz; + let a = align.split(" "); + a = Jimp["HORIZONTAL_ALIGN_" + a[0]] | Jimp["VERTICAL_ALIGN_" + a[1]]; + it("contain aligned to " + align, () => { + expectToBeJGD( + vertical.clone().contain(6, 6, a).getJGDSync(), + jgdContainV + ); + expectToBeJGD( + horizontal.clone().contain(6, 6, a).getJGDSync(), + jgdContainH + ); + }); + } + + for (const align in tests) if (hasOwnProp(tests, align)) runAlignTest(align); +}); diff --git a/node_modules/@jimp/plugin-cover/CHANGELOG.md b/node_modules/@jimp/plugin-cover/CHANGELOG.md new file mode 100644 index 00000000..3d839517 --- /dev/null +++ b/node_modules/@jimp/plugin-cover/CHANGELOG.md @@ -0,0 +1,85 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-cover/LICENSE b/node_modules/@jimp/plugin-cover/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-cover/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-cover/README.md b/node_modules/@jimp/plugin-cover/README.md new file mode 100644 index 00000000..8313aa2c --- /dev/null +++ b/node_modules/@jimp/plugin-cover/README.md @@ -0,0 +1,54 @@ +
+ +

@jimp/plugin-cover

+
+ +Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped. + +## Usage + +- @param {number} w the width to resize the image to +- @param {number} h the height to resize the image to +- @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment +- @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.cover(150, 100); +} + +main(); +``` + +### Align modes + +The following constants can be passed to `image.cover`: + +```js +Jimp.HORIZONTAL_ALIGN_LEFT; +Jimp.HORIZONTAL_ALIGN_CENTER; +Jimp.HORIZONTAL_ALIGN_RIGHT; + +Jimp.VERTICAL_ALIGN_TOP; +Jimp.VERTICAL_ALIGN_MIDDLE; +Jimp.VERTICAL_ALIGN_BOTTOM; +``` + +For example: + +```js +image.cover(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP); +image.cover(250, 250, Jimp.HORIZONTAL_ALIGN_RIGHT | Jimp.VERTICAL_ALIGN_BOTTOM); +``` + +Default align mode for `image.cover` is: + +```js +Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE; +``` diff --git a/node_modules/@jimp/plugin-cover/es/index.js b/node_modules/@jimp/plugin-cover/es/index.js new file mode 100644 index 00000000..165d9178 --- /dev/null +++ b/node_modules/@jimp/plugin-cover/es/index.js @@ -0,0 +1,43 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + cover(w, h, alignBits, mode, cb) { + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + if (alignBits && typeof alignBits === "function" && typeof cb === "undefined") { + cb = alignBits; + alignBits = null; + mode = null; + } else if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE; + const hbits = alignBits & (1 << 3) - 1; + const vbits = alignBits >> 3; + + // check if more flags than one is in the bit sets + if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) return throwError.call(this, "only use one flag per alignment direction", cb); + const alignH = hbits >> 1; // 0, 1, 2 + const alignV = vbits >> 1; // 0, 1, 2 + + const f = w / h > this.bitmap.width / this.bitmap.height ? w / this.bitmap.width : h / this.bitmap.height; + this.scale(f, mode); + this.crop((this.bitmap.width - w) / 2 * alignH, (this.bitmap.height - h) / 2 * alignV, w, h); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-cover/es/index.js.map b/node_modules/@jimp/plugin-cover/es/index.js.map new file mode 100644 index 00000000..edc1c548 --- /dev/null +++ b/node_modules/@jimp/plugin-cover/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","cover","w","h","alignBits","mode","cb","call","constructor","HORIZONTAL_ALIGN_CENTER","VERTICAL_ALIGN_MIDDLE","hbits","vbits","alignH","alignV","f","bitmap","width","height","scale","crop"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped.\n * @param {number} w the width to resize the image to\n * @param {number} h the height to resize the image to\n * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n cover(w, h, alignBits, mode, cb) {\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n\n if (\n alignBits &&\n typeof alignBits === \"function\" &&\n typeof cb === \"undefined\"\n ) {\n cb = alignBits;\n alignBits = null;\n mode = null;\n } else if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n\n alignBits =\n alignBits ||\n this.constructor.HORIZONTAL_ALIGN_CENTER |\n this.constructor.VERTICAL_ALIGN_MIDDLE;\n const hbits = alignBits & ((1 << 3) - 1);\n const vbits = alignBits >> 3;\n\n // check if more flags than one is in the bit sets\n if (\n !(\n (hbits !== 0 && !(hbits & (hbits - 1))) ||\n (vbits !== 0 && !(vbits & (vbits - 1)))\n )\n )\n return throwError.call(\n this,\n \"only use one flag per alignment direction\",\n cb\n );\n\n const alignH = hbits >> 1; // 0, 1, 2\n const alignV = vbits >> 1; // 0, 1, 2\n\n const f =\n w / h > this.bitmap.width / this.bitmap.height\n ? w / this.bitmap.width\n : h / this.bitmap.height;\n this.scale(f, mode);\n this.crop(\n ((this.bitmap.width - w) / 2) * alignH,\n ((this.bitmap.height - h) / 2) * alignV,\n w,\n h\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;;AAEvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAA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G,IAAI,CAACD,MAAM,CAACE,MAAM,GAC1ChB,CAAC,GAAG,IAAI,CAACc,MAAM,CAACC,KAAK,GACrBd,CAAC,GAAG,IAAI,CAACa,MAAM,CAACE,MAAM;IAC5B,IAAI,CAACC,KAAK,CAACJ,CAAC,EAAEV,IAAI,CAAC;IACnB,IAAI,CAACe,IAAI,CACN,CAAC,IAAI,CAACJ,MAAM,CAACC,KAAK,GAAGf,CAAC,IAAI,CAAC,GAAIW,MAAM,EACrC,CAAC,IAAI,CAACG,MAAM,CAACE,MAAM,GAAGf,CAAC,IAAI,CAAC,GAAIW,MAAM,EACvCZ,CAAC,EACDC,CAAC,CACF;IAED,IAAIJ,aAAa,CAACO,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-cover/index.d.ts b/node_modules/@jimp/plugin-cover/index.d.ts new file mode 100644 index 00000000..6a9e5d1c --- /dev/null +++ b/node_modules/@jimp/plugin-cover/index.d.ts @@ -0,0 +1,20 @@ +import { ImageCallback } from "@jimp/core"; + +interface Cover { + cover(w: number, h: number, cb?: ImageCallback): this; + cover( + w: number, + h: number, + alignBits?: number, + cb?: ImageCallback + ): this; + cover( + w: number, + h: number, + alignBits?: number, + mode?: string, + cb?: ImageCallback + ): this; +} + +export default function (): Cover; diff --git a/node_modules/@jimp/plugin-cover/package.json b/node_modules/@jimp/plugin-cover/package.json new file mode 100644 index 00000000..708db221 --- /dev/null +++ b/node_modules/@jimp/plugin-cover/package.json @@ -0,0 +1,43 @@ +{ + "name": "@jimp/plugin-cover", + "version": "0.22.12", + "description": "cover an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-crop": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5", + "@jimp/plugin-scale": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/plugin-crop": "^0.22.12", + "@jimp/plugin-resize": "^0.22.12", + "@jimp/plugin-scale": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-cover/src/index.js b/node_modules/@jimp/plugin-cover/src/index.js new file mode 100644 index 00000000..37a0f1b7 --- /dev/null +++ b/node_modules/@jimp/plugin-cover/src/index.js @@ -0,0 +1,72 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + cover(w, h, alignBits, mode, cb) { + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + + if ( + alignBits && + typeof alignBits === "function" && + typeof cb === "undefined" + ) { + cb = alignBits; + alignBits = null; + mode = null; + } else if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + + alignBits = + alignBits || + this.constructor.HORIZONTAL_ALIGN_CENTER | + this.constructor.VERTICAL_ALIGN_MIDDLE; + const hbits = alignBits & ((1 << 3) - 1); + const vbits = alignBits >> 3; + + // check if more flags than one is in the bit sets + if ( + !( + (hbits !== 0 && !(hbits & (hbits - 1))) || + (vbits !== 0 && !(vbits & (vbits - 1))) + ) + ) + return throwError.call( + this, + "only use one flag per alignment direction", + cb + ); + + const alignH = hbits >> 1; // 0, 1, 2 + const alignV = vbits >> 1; // 0, 1, 2 + + const f = + w / h > this.bitmap.width / this.bitmap.height + ? w / this.bitmap.width + : h / this.bitmap.height; + this.scale(f, mode); + this.crop( + ((this.bitmap.width - w) / 2) * alignH, + ((this.bitmap.height - h) / 2) * alignV, + w, + h + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-cover/test/cover.test.js b/node_modules/@jimp/plugin-cover/test/cover.test.js new file mode 100644 index 00000000..ba61d3bb --- /dev/null +++ b/node_modules/@jimp/plugin-cover/test/cover.test.js @@ -0,0 +1,124 @@ +import { Jimp, mkJGD, hasOwnProp } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import crop from "@jimp/plugin-crop"; +import scale from "@jimp/plugin-scale"; +import resize from "@jimp/plugin-resize"; + +import cover from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [resize, scale, crop, cover] }, Jimp); + +describe("All align combinations for cover", () => { + const verticalJGD = mkJGD( + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▴▴▴▴▸▸▸▸", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆", + "▾▾▾▾◆◆◆◆" + ); + + const horizontalJGD = mkJGD( + "▴▴▴▴▴▴▸▸▸▸▸▸", + "▴▴▴▴▴▴▸▸▸▸▸▸", + "▴▴▴▴▴▴▸▸▸▸▸▸", + "▴▴▴▴▴▴▸▸▸▸▸▸", + "▾▾▾▾▾▾◆◆◆◆◆◆", + "▾▾▾▾▾▾◆◆◆◆◆◆", + "▾▾▾▾▾▾◆◆◆◆◆◆", + "▾▾▾▾▾▾◆◆◆◆◆◆" + ); + + let vertical; + let horizontal; // stores the Jimp instances of the JGD images above. + + before((done) => { + const img1 = jimp.read(verticalJGD); + const img2 = jimp.read(horizontalJGD); + Promise.all([img1, img2]) + .then((images) => { + vertical = images[0]; + horizontal = images[1]; + done(); + }) + .catch(done); + }); + + const tests = {}; // Stores the expected result for each alignment combination. + tests["LEFT TOP"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▴▴▸▸", "▴▴▸▸", "▾▾◆◆"), + horiz: mkJGD("▴▴▴▸", "▴▴▴▸", "▾▾▾◆", "▾▾▾◆"), + }, + }; + tests["CENTER TOP"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▴▴▸▸", "▴▴▸▸", "▾▾◆◆"), + horiz: mkJGD("▴▴▸▸", "▴▴▸▸", "▾▾◆◆", "▾▾◆◆"), + }, + }; + tests["RIGHT TOP"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▴▴▸▸", "▴▴▸▸", "▾▾◆◆"), + horiz: mkJGD("▴▸▸▸", "▴▸▸▸", "▾◆◆◆", "▾◆◆◆"), + }, + }; + + tests["LEFT MIDDLE"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▴▴▸▸", "▾▾◆◆", "▾▾◆◆"), + horiz: mkJGD("▴▴▴▸", "▴▴▴▸", "▾▾▾◆", "▾▾▾◆"), + }, + }; + tests["CENTER MIDDLE"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▴▴▸▸", "▾▾◆◆", "▾▾◆◆"), + horiz: mkJGD("▴▴▸▸", "▴▴▸▸", "▾▾◆◆", "▾▾◆◆"), + }, + }; + tests["RIGHT MIDDLE"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▴▴▸▸", "▾▾◆◆", "▾▾◆◆"), + horiz: mkJGD("▴▸▸▸", "▴▸▸▸", "▾◆◆◆", "▾◆◆◆"), + }, + }; + + tests["LEFT BOTTOM"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▾▾◆◆", "▾▾◆◆", "▾▾◆◆"), + horiz: mkJGD("▴▴▴▸", "▴▴▴▸", "▾▾▾◆", "▾▾▾◆"), + }, + }; + tests["CENTER BOTTOM"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▾▾◆◆", "▾▾◆◆", "▾▾◆◆"), + horiz: mkJGD("▴▴▸▸", "▴▴▸▸", "▾▾◆◆", "▾▾◆◆"), + }, + }; + tests["RIGHT BOTTOM"] = { + cover: { + verti: mkJGD("▴▴▸▸", "▾▾◆◆", "▾▾◆◆", "▾▾◆◆"), + horiz: mkJGD("▴▸▸▸", "▴▸▸▸", "▾◆◆◆", "▾◆◆◆"), + }, + }; + + function runAlignTest(align) { + const jgdCoverV = tests[align].cover.verti; + const jgdCoverH = tests[align].cover.horiz; + let a = align.split(" "); + a = Jimp["HORIZONTAL_ALIGN_" + a[0]] | Jimp["VERTICAL_ALIGN_" + a[1]]; + it("cover aligned to " + align, () => { + expectToBeJGD(vertical.clone().cover(4, 4, a).getJGDSync(), jgdCoverV); + expectToBeJGD(horizontal.clone().cover(4, 4, a).getJGDSync(), jgdCoverH); + }); + } + + for (const align in tests) if (hasOwnProp(tests, align)) runAlignTest(align); +}); diff --git a/node_modules/@jimp/plugin-crop/CHANGELOG.md b/node_modules/@jimp/plugin-crop/CHANGELOG.md new file mode 100644 index 00000000..ffe751ec --- /dev/null +++ b/node_modules/@jimp/plugin-crop/CHANGELOG.md @@ -0,0 +1,118 @@ +# v0.22.8 (Thu May 11 2023) + +:tada: This release contains work from a new contributor! :tada: + +Thank you, Sjoerd ([@sjoerd108](https://github.com/sjoerd108)), for all your work! + +#### 🐛 Bug Fix + +- Fix autocrop mixing up east and west [#1227](https://github.com/jimp-dev/jimp/pull/1227) ([@sjoerd108](https://github.com/sjoerd108)) + +#### Authors: 1 + +- Sjoerd ([@sjoerd108](https://github.com/sjoerd108)) + +--- + +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- fixed plugin-crop full width slices math [#1073](https://github.com/jimp-dev/jimp/pull/1073) ([@endreszabo](https://github.com/endreszabo)) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Endre Szabo ([@endreszabo](https://github.com/endreszabo)) + +--- + +# v0.16.0 (Sat Aug 08 2020) + +#### 🚀 Enhancement + +- added ability to ignore sides on autocrop [#924](https://github.com/oliver-moran/jimp/pull/924) ([@cbanfiel](https://github.com/cbanfiel)) + +#### Authors: 1 + +- Chad Banfield ([@cbanfiel](https://github.com/cbanfiel)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-crop/LICENSE b/node_modules/@jimp/plugin-crop/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-crop/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-crop/README.md b/node_modules/@jimp/plugin-crop/README.md new file mode 100644 index 00000000..64689368 --- /dev/null +++ b/node_modules/@jimp/plugin-crop/README.md @@ -0,0 +1,56 @@ +
+ +

@jimp/plugin-crop

+

Crop an image.

+
+ +## Crop + +Crops the image at a given point to a give size + +- @param {number} x the x coordinate to crop form +- @param {number} y the y coordinate to crop form +- @param w the width of the crop region +- @param h the height of the crop region +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.crop(150, 150); +} + +main(); +``` + +## AutoCrop + +AutoCrop same color borders from this image + +- @param {number} tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%) +- @param {boolean} cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true) + +or + +- @param {object} options object + - tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%) + - cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true) + - cropSymmetric (optional): flag to force cropping top be symmetric. north and south / east and west are cropped by the same value + - leaveBorder (optional): integer of how many pixels of the background color to leave around the image + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.autocrop(); + image.autocrop({ cropOnlyFrames: false, cropSymmetric: true }); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-crop/es/index.js b/node_modules/@jimp/plugin-crop/es/index.js new file mode 100644 index 00000000..d4d040fd --- /dev/null +++ b/node_modules/@jimp/plugin-crop/es/index.js @@ -0,0 +1,255 @@ +/* eslint-disable no-labels */ + +import { throwError, isNodePattern } from "@jimp/utils"; +export default function pluginCrop(event) { + /** + * Crops the image at a given point to a give size + * @param {number} x the x coordinate to crop form + * @param {number} y the y coordinate to crop form + * @param w the width of the crop region + * @param h the height of the crop region + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + event("crop", function (x, y, w, h, cb) { + if (typeof x !== "number" || typeof y !== "number") return throwError.call(this, "x and y must be numbers", cb); + if (typeof w !== "number" || typeof h !== "number") return throwError.call(this, "w and h must be numbers", cb); + + // round input + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + if (x === 0 && w === this.bitmap.width) { + // shortcut + const start = w * y + x << 2; + const end = start + (h * w << 2); + this.bitmap.data = this.bitmap.data.slice(start, end); + } else { + const bitmap = Buffer.allocUnsafe(w * h * 4); + let offset = 0; + this.scanQuiet(x, y, w, h, function (x, y, idx) { + const data = this.bitmap.data.readUInt32BE(idx, true); + bitmap.writeUInt32BE(data, offset, true); + offset += 4; + }); + this.bitmap.data = bitmap; + } + this.bitmap.width = w; + this.bitmap.height = h; + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }); + return { + class: { + /** + * Autocrop same color borders from this image + * @param {number} tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%) + * @param {boolean} cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true) + * @param {function(Error, Jimp)} cb (optional): a callback for when complete (default: no callback) + * @returns {Jimp} this for chaining of methods + */ + autocrop() { + const w = this.bitmap.width; + const h = this.bitmap.height; + const minPixelsPerSide = 1; // to avoid cropping completely the image, resulting in an invalid 0 sized image + + let cb; // callback + let leaveBorder = 0; // Amount of pixels in border to leave + let tolerance = 0.0002; // percent of color difference tolerance (default value) + let cropOnlyFrames = true; // flag to force cropping only if the image has a real "frame" + // i.e. all 4 sides have some border (default value) + let cropSymmetric = false; // flag to force cropping top be symmetric. + // i.e. north and south / east and west are cropped by the same value + let ignoreSides = { + north: false, + south: false, + east: false, + west: false + }; + + // parse arguments + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + for (let a = 0, len = args.length; a < len; a++) { + if (typeof args[a] === "number") { + // tolerance value passed + tolerance = args[a]; + } + if (typeof args[a] === "boolean") { + // cropOnlyFrames value passed + cropOnlyFrames = args[a]; + } + if (typeof args[a] === "function") { + // callback value passed + cb = args[a]; + } + if (typeof args[a] === "object") { + // config object passed + const config = args[a]; + if (typeof config.tolerance !== "undefined") { + ({ + tolerance + } = config); + } + if (typeof config.cropOnlyFrames !== "undefined") { + ({ + cropOnlyFrames + } = config); + } + if (typeof config.cropSymmetric !== "undefined") { + ({ + cropSymmetric + } = config); + } + if (typeof config.leaveBorder !== "undefined") { + ({ + leaveBorder + } = config); + } + if (typeof config.ignoreSides !== "undefined") { + ({ + ignoreSides + } = config); + } + } + } + + /** + * All borders must be of the same color as the top left pixel, to be cropped. + * It should be possible to crop borders each with a different color, + * but since there are many ways for corners to intersect, it would + * introduce unnecessary complexity to the algorithm. + */ + + // scan each side for same color borders + let colorTarget = this.getPixelColor(0, 0); // top left pixel color is the target color + const rgba1 = this.constructor.intToRGBA(colorTarget); + + // for north and east sides + let northPixelsToCrop = 0; + let eastPixelsToCrop = 0; + let southPixelsToCrop = 0; + let westPixelsToCrop = 0; + + // north side (scan rows from north to south) + colorTarget = this.getPixelColor(0, 0); + if (!ignoreSides.north) { + north: for (let y = 0; y < h - minPixelsPerSide; y++) { + for (let x = 0; x < w; x++) { + const colorXY = this.getPixelColor(x, y); + const rgba2 = this.constructor.intToRGBA(colorXY); + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break north; + } + } + + // this row contains all pixels with the same color: increment this side pixels to crop + northPixelsToCrop++; + } + } + + // west side (scan columns from west to east) + colorTarget = this.getPixelColor(w, 0); + if (!ignoreSides.west) { + west: for (let x = 0; x < w - minPixelsPerSide; x++) { + for (let y = 0 + northPixelsToCrop; y < h; y++) { + const colorXY = this.getPixelColor(x, y); + const rgba2 = this.constructor.intToRGBA(colorXY); + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break west; + } + } + + // this column contains all pixels with the same color: increment this side pixels to crop + westPixelsToCrop++; + } + } + + // south side (scan rows from south to north) + colorTarget = this.getPixelColor(0, h); + if (!ignoreSides.south) { + south: for (let y = h - 1; y >= northPixelsToCrop + minPixelsPerSide; y--) { + for (let x = w - eastPixelsToCrop - 1; x >= 0; x--) { + const colorXY = this.getPixelColor(x, y); + const rgba2 = this.constructor.intToRGBA(colorXY); + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break south; + } + } + + // this row contains all pixels with the same color: increment this side pixels to crop + southPixelsToCrop++; + } + } + + // east side (scan columns from east to west) + colorTarget = this.getPixelColor(w, h); + if (!ignoreSides.east) { + east: for (let x = w - 1; x >= 0 + westPixelsToCrop + minPixelsPerSide; x--) { + for (let y = h - 1; y >= 0 + northPixelsToCrop; y--) { + const colorXY = this.getPixelColor(x, y); + const rgba2 = this.constructor.intToRGBA(colorXY); + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break east; + } + } + + // this column contains all pixels with the same color: increment this side pixels to crop + eastPixelsToCrop++; + } + } + + // decide if a crop is needed + let doCrop = false; + + // apply leaveBorder + westPixelsToCrop -= leaveBorder; + eastPixelsToCrop -= leaveBorder; + northPixelsToCrop -= leaveBorder; + southPixelsToCrop -= leaveBorder; + if (cropSymmetric) { + const horizontal = Math.min(eastPixelsToCrop, westPixelsToCrop); + const vertical = Math.min(northPixelsToCrop, southPixelsToCrop); + westPixelsToCrop = horizontal; + eastPixelsToCrop = horizontal; + northPixelsToCrop = vertical; + southPixelsToCrop = vertical; + } + + // make sure that crops are >= 0 + westPixelsToCrop = westPixelsToCrop >= 0 ? westPixelsToCrop : 0; + eastPixelsToCrop = eastPixelsToCrop >= 0 ? eastPixelsToCrop : 0; + northPixelsToCrop = northPixelsToCrop >= 0 ? northPixelsToCrop : 0; + southPixelsToCrop = southPixelsToCrop >= 0 ? southPixelsToCrop : 0; + + // safety checks + const widthOfRemainingPixels = w - (westPixelsToCrop + eastPixelsToCrop); + const heightOfRemainingPixels = h - (southPixelsToCrop + northPixelsToCrop); + if (cropOnlyFrames) { + // crop image if all sides should be cropped + doCrop = eastPixelsToCrop !== 0 && northPixelsToCrop !== 0 && westPixelsToCrop !== 0 && southPixelsToCrop !== 0; + } else { + // crop image if at least one side should be cropped + doCrop = eastPixelsToCrop !== 0 || northPixelsToCrop !== 0 || westPixelsToCrop !== 0 || southPixelsToCrop !== 0; + } + if (doCrop) { + // do the real crop + this.crop(westPixelsToCrop, northPixelsToCrop, widthOfRemainingPixels, heightOfRemainingPixels); + } + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } + } + }; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-crop/es/index.js.map b/node_modules/@jimp/plugin-crop/es/index.js.map new file mode 100644 index 00000000..6f8e4e20 --- /dev/null +++ b/node_modules/@jimp/plugin-crop/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["throwError","isNodePattern","pluginCrop","event","x","y","w","h","cb","call","Math","round","bitmap","width","start","end","data","slice","Buffer","allocUnsafe","offset","scanQuiet","idx","readUInt32BE","writeUInt32BE","height","class","autocrop","minPixelsPerSide","leaveBorder","tolerance","cropOnlyFrames","cropSymmetric","ignoreSides","north","south","east","west","args","a","len","length","config","colorTarget","getPixelColor","rgba1","constructor","intToRGBA","northPixelsToCrop","eastPixelsToCrop","southPixelsToCrop","westPixelsToCrop","colorXY","rgba2","colorDiff","doCrop","horizontal","min","vertical","widthOfRemainingPixels","heightOfRemainingPixels","crop"],"sources":["../src/index.js"],"sourcesContent":["/* eslint-disable no-labels */\n\nimport { throwError, isNodePattern } from \"@jimp/utils\";\n\nexport default function pluginCrop(event) {\n /**\n * Crops the image at a given point to a give size\n * @param {number} x the x coordinate to crop form\n * @param {number} y the y coordinate to crop form\n * @param w the width of the crop region\n * @param h the height of the crop region\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n event(\"crop\", function (x, y, w, h, cb) {\n if (typeof x !== \"number\" || typeof y !== \"number\")\n return throwError.call(this, \"x and y must be numbers\", cb);\n if (typeof w !== \"number\" || typeof h !== \"number\")\n return throwError.call(this, \"w and h must be numbers\", cb);\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n w = Math.round(w);\n h = Math.round(h);\n\n if (x === 0 && w === this.bitmap.width) {\n // shortcut\n const start = (w * y + x) << 2;\n const end = start + ((h * w) << 2);\n\n this.bitmap.data = this.bitmap.data.slice(start, end);\n } else {\n const bitmap = Buffer.allocUnsafe(w * h * 4);\n let offset = 0;\n\n this.scanQuiet(x, y, w, h, function (x, y, idx) {\n const data = this.bitmap.data.readUInt32BE(idx, true);\n bitmap.writeUInt32BE(data, offset, true);\n offset += 4;\n });\n\n this.bitmap.data = bitmap;\n }\n\n this.bitmap.width = w;\n this.bitmap.height = h;\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n });\n\n return {\n class: {\n /**\n * Autocrop same color borders from this image\n * @param {number} tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%)\n * @param {boolean} cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true)\n * @param {function(Error, Jimp)} cb (optional): a callback for when complete (default: no callback)\n * @returns {Jimp} this for chaining of methods\n */\n autocrop(...args) {\n const w = this.bitmap.width;\n const h = this.bitmap.height;\n const minPixelsPerSide = 1; // to avoid cropping completely the image, resulting in an invalid 0 sized image\n\n let cb; // callback\n let leaveBorder = 0; // Amount of pixels in border to leave\n let tolerance = 0.0002; // percent of color difference tolerance (default value)\n let cropOnlyFrames = true; // flag to force cropping only if the image has a real \"frame\"\n // i.e. all 4 sides have some border (default value)\n let cropSymmetric = false; // flag to force cropping top be symmetric.\n // i.e. north and south / east and west are cropped by the same value\n let ignoreSides = {\n north: false,\n south: false,\n east: false,\n west: false,\n };\n\n // parse arguments\n for (let a = 0, len = args.length; a < len; a++) {\n if (typeof args[a] === \"number\") {\n // tolerance value passed\n tolerance = args[a];\n }\n\n if (typeof args[a] === \"boolean\") {\n // cropOnlyFrames value passed\n cropOnlyFrames = args[a];\n }\n\n if (typeof args[a] === \"function\") {\n // callback value passed\n cb = args[a];\n }\n\n if (typeof args[a] === \"object\") {\n // config object passed\n const config = args[a];\n\n if (typeof config.tolerance !== \"undefined\") {\n ({ tolerance } = config);\n }\n\n if (typeof config.cropOnlyFrames !== \"undefined\") {\n ({ cropOnlyFrames } = config);\n }\n\n if (typeof config.cropSymmetric !== \"undefined\") {\n ({ cropSymmetric } = config);\n }\n\n if (typeof config.leaveBorder !== \"undefined\") {\n ({ leaveBorder } = config);\n }\n\n if (typeof config.ignoreSides !== \"undefined\") {\n ({ ignoreSides } = config);\n }\n }\n }\n\n /**\n * All borders must be of the same color as the top left pixel, to be cropped.\n * It should be possible to crop borders each with a different color,\n * but since there are many ways for corners to intersect, it would\n * introduce unnecessary complexity to the algorithm.\n */\n\n // scan each side for same color borders\n let colorTarget = this.getPixelColor(0, 0); // top left pixel color is the target color\n const rgba1 = this.constructor.intToRGBA(colorTarget);\n\n // for north and east sides\n let northPixelsToCrop = 0;\n let eastPixelsToCrop = 0;\n let southPixelsToCrop = 0;\n let westPixelsToCrop = 0;\n\n // north side (scan rows from north to south)\n colorTarget = this.getPixelColor(0, 0);\n if (!ignoreSides.north) {\n north: for (let y = 0; y < h - minPixelsPerSide; y++) {\n for (let x = 0; x < w; x++) {\n const colorXY = this.getPixelColor(x, y);\n const rgba2 = this.constructor.intToRGBA(colorXY);\n\n if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {\n // this pixel is too distant from the first one: abort this side scan\n break north;\n }\n }\n\n // this row contains all pixels with the same color: increment this side pixels to crop\n northPixelsToCrop++;\n }\n }\n\n // west side (scan columns from west to east)\n colorTarget = this.getPixelColor(w, 0);\n if (!ignoreSides.west) {\n west: for (let x = 0; x < w - minPixelsPerSide; x++) {\n for (let y = 0 + northPixelsToCrop; y < h; y++) {\n const colorXY = this.getPixelColor(x, y);\n const rgba2 = this.constructor.intToRGBA(colorXY);\n\n if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {\n // this pixel is too distant from the first one: abort this side scan\n break west;\n }\n }\n\n // this column contains all pixels with the same color: increment this side pixels to crop\n westPixelsToCrop++;\n }\n }\n\n // south side (scan rows from south to north)\n colorTarget = this.getPixelColor(0, h);\n\n if (!ignoreSides.south) {\n south: for (\n let y = h - 1;\n y >= northPixelsToCrop + minPixelsPerSide;\n y--\n ) {\n for (let x = w - eastPixelsToCrop - 1; x >= 0; x--) {\n const colorXY = this.getPixelColor(x, y);\n const rgba2 = this.constructor.intToRGBA(colorXY);\n\n if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {\n // this pixel is too distant from the first one: abort this side scan\n break south;\n }\n }\n\n // this row contains all pixels with the same color: increment this side pixels to crop\n southPixelsToCrop++;\n }\n }\n\n // east side (scan columns from east to west)\n colorTarget = this.getPixelColor(w, h);\n if (!ignoreSides.east) {\n east: for (\n let x = w - 1;\n x >= 0 + westPixelsToCrop + minPixelsPerSide;\n x--\n ) {\n for (let y = h - 1; y >= 0 + northPixelsToCrop; y--) {\n const colorXY = this.getPixelColor(x, y);\n const rgba2 = this.constructor.intToRGBA(colorXY);\n\n if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {\n // this pixel is too distant from the first one: abort this side scan\n break east;\n }\n }\n\n // this column contains all pixels with the same color: increment this side pixels to crop\n eastPixelsToCrop++;\n }\n }\n\n // decide if a crop is needed\n let doCrop = false;\n\n // apply leaveBorder\n westPixelsToCrop -= leaveBorder;\n eastPixelsToCrop -= leaveBorder;\n northPixelsToCrop -= leaveBorder;\n southPixelsToCrop -= leaveBorder;\n\n if (cropSymmetric) {\n const horizontal = Math.min(eastPixelsToCrop, westPixelsToCrop);\n const vertical = Math.min(northPixelsToCrop, southPixelsToCrop);\n westPixelsToCrop = horizontal;\n eastPixelsToCrop = horizontal;\n northPixelsToCrop = vertical;\n southPixelsToCrop = vertical;\n }\n\n // make sure that crops are >= 0\n westPixelsToCrop = westPixelsToCrop >= 0 ? westPixelsToCrop : 0;\n eastPixelsToCrop = eastPixelsToCrop >= 0 ? eastPixelsToCrop : 0;\n northPixelsToCrop = northPixelsToCrop >= 0 ? northPixelsToCrop : 0;\n southPixelsToCrop = southPixelsToCrop >= 0 ? southPixelsToCrop : 0;\n\n // safety checks\n const widthOfRemainingPixels =\n w - (westPixelsToCrop + eastPixelsToCrop);\n const heightOfRemainingPixels =\n h - (southPixelsToCrop + northPixelsToCrop);\n\n if (cropOnlyFrames) {\n // crop image if all sides should be cropped\n doCrop =\n eastPixelsToCrop !== 0 &&\n northPixelsToCrop !== 0 &&\n westPixelsToCrop !== 0 &&\n southPixelsToCrop !== 0;\n } else {\n // crop image if at least one side should be cropped\n doCrop =\n eastPixelsToCrop !== 0 ||\n northPixelsToCrop !== 0 ||\n westPixelsToCrop !== 0 ||\n southPixelsToCrop !== 0;\n }\n\n if (doCrop) {\n // do the real crop\n this.crop(\n westPixelsToCrop,\n northPixelsToCrop,\n widthOfRemainingPixels,\n heightOfRemainingPixels\n );\n }\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n },\n };\n}\n"],"mappings":"AAAA;;AAEA,SAASA,UAAU,EAAEC,aAAa,QAAQ,aAAa;AAEvD,eAAe,SAASC,UAAU,CAACC,KAAK,EAAE;EACxC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEA,KAAK,CAAC,MAAM,EAAE,UAAUC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,EAAE,EAAE;IACtC,IAAI,OAAOJ,CAAC,KAAK,QAAQ,IAAI,OAAOC,CAAC,KAAK,QAAQ,EAChD,OAAOL,UAAU,CAACS,IAAI,CAAC,IAAI,EAAE,yBAAyB,EAAED,EAAE,CAAC;IAC7D,IAAI,OAAOF,CAAC,KAAK,QAAQ,IAAI,OAAOC,CAAC,KAAK,QAAQ,EAChD,OAAOP,UAAU,CAACS,IAAI,CAAC,IAAI,EAAE,yBAAyB,EAAED,EAAE,CAAC;;IAE7D;IACAJ,CAAC,GAAGM,IAAI,CAACC,KAAK,CAACP,CAAC,CAAC;IACjBC,CAAC,GAAGK,IAAI,CAACC,KAAK,CAACN,CAAC,CAAC;IACjBC,CAAC,GAAGI,IAAI,CAACC,KAAK,CAACL,CAAC,CAAC;IACjBC,CAAC,GAAGG,IAAI,CAACC,KAAK,CAACJ,CAAC,CAAC;IAEjB,IAAIH,CAAC,KAAK,CAAC,IAAIE,CAAC,KAAK,IAAI,CAACM,MAAM,CAACC,KAAK,EAAE;MACtC;MACA,MAAMC,KAAK,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AAI,CAAC;QAC3B;QAEA,OAAO,IAAI;MACb;IACF;EACF,CAAC;AACH"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-crop/index.d.ts b/node_modules/@jimp/plugin-crop/index.d.ts new file mode 100644 index 00000000..48550b4f --- /dev/null +++ b/node_modules/@jimp/plugin-crop/index.d.ts @@ -0,0 +1,46 @@ +import { Jimp, ImageCallback } from "@jimp/core"; + +interface CropClass { + crop( + x: number, + y: number, + w: number, + h: number, + cb?: ImageCallback + ): this; + cropQuiet( + x: number, + y: number, + w: number, + h: number, + cb?: ImageCallback + ): this; + autocrop(tolerance?: number, cb?: ImageCallback): this; + autocrop(cropOnlyFrames?: boolean, cb?: ImageCallback): this; + autocrop( + tolerance?: number, + cropOnlyFrames?: boolean, + cb?: ImageCallback + ): this; + autocrop( + options: { + tolerance?: number; + cropOnlyFrames?: boolean; + cropSymmetric?: boolean; + leaveBorder?: number; + ignoreSides?: { + north: boolean; + south: boolean; + east: boolean; + west: boolean; + }; + }, + cb?: ImageCallback + ): this; +} + +interface Crop { + class: CropClass; +} + +export default function (): Crop; diff --git a/node_modules/@jimp/plugin-crop/package.json b/node_modules/@jimp/plugin-crop/package.json new file mode 100644 index 00000000..15d98501 --- /dev/null +++ b/node_modules/@jimp/plugin-crop/package.json @@ -0,0 +1,37 @@ +{ + "name": "@jimp/plugin-crop", + "version": "0.22.12", + "description": "crop an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-crop/src/index.js b/node_modules/@jimp/plugin-crop/src/index.js new file mode 100644 index 00000000..7528d2b8 --- /dev/null +++ b/node_modules/@jimp/plugin-crop/src/index.js @@ -0,0 +1,293 @@ +/* eslint-disable no-labels */ + +import { throwError, isNodePattern } from "@jimp/utils"; + +export default function pluginCrop(event) { + /** + * Crops the image at a given point to a give size + * @param {number} x the x coordinate to crop form + * @param {number} y the y coordinate to crop form + * @param w the width of the crop region + * @param h the height of the crop region + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + event("crop", function (x, y, w, h, cb) { + if (typeof x !== "number" || typeof y !== "number") + return throwError.call(this, "x and y must be numbers", cb); + if (typeof w !== "number" || typeof h !== "number") + return throwError.call(this, "w and h must be numbers", cb); + + // round input + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + + if (x === 0 && w === this.bitmap.width) { + // shortcut + const start = (w * y + x) << 2; + const end = start + ((h * w) << 2); + + this.bitmap.data = this.bitmap.data.slice(start, end); + } else { + const bitmap = Buffer.allocUnsafe(w * h * 4); + let offset = 0; + + this.scanQuiet(x, y, w, h, function (x, y, idx) { + const data = this.bitmap.data.readUInt32BE(idx, true); + bitmap.writeUInt32BE(data, offset, true); + offset += 4; + }); + + this.bitmap.data = bitmap; + } + + this.bitmap.width = w; + this.bitmap.height = h; + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }); + + return { + class: { + /** + * Autocrop same color borders from this image + * @param {number} tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%) + * @param {boolean} cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true) + * @param {function(Error, Jimp)} cb (optional): a callback for when complete (default: no callback) + * @returns {Jimp} this for chaining of methods + */ + autocrop(...args) { + const w = this.bitmap.width; + const h = this.bitmap.height; + const minPixelsPerSide = 1; // to avoid cropping completely the image, resulting in an invalid 0 sized image + + let cb; // callback + let leaveBorder = 0; // Amount of pixels in border to leave + let tolerance = 0.0002; // percent of color difference tolerance (default value) + let cropOnlyFrames = true; // flag to force cropping only if the image has a real "frame" + // i.e. all 4 sides have some border (default value) + let cropSymmetric = false; // flag to force cropping top be symmetric. + // i.e. north and south / east and west are cropped by the same value + let ignoreSides = { + north: false, + south: false, + east: false, + west: false, + }; + + // parse arguments + for (let a = 0, len = args.length; a < len; a++) { + if (typeof args[a] === "number") { + // tolerance value passed + tolerance = args[a]; + } + + if (typeof args[a] === "boolean") { + // cropOnlyFrames value passed + cropOnlyFrames = args[a]; + } + + if (typeof args[a] === "function") { + // callback value passed + cb = args[a]; + } + + if (typeof args[a] === "object") { + // config object passed + const config = args[a]; + + if (typeof config.tolerance !== "undefined") { + ({ tolerance } = config); + } + + if (typeof config.cropOnlyFrames !== "undefined") { + ({ cropOnlyFrames } = config); + } + + if (typeof config.cropSymmetric !== "undefined") { + ({ cropSymmetric } = config); + } + + if (typeof config.leaveBorder !== "undefined") { + ({ leaveBorder } = config); + } + + if (typeof config.ignoreSides !== "undefined") { + ({ ignoreSides } = config); + } + } + } + + /** + * All borders must be of the same color as the top left pixel, to be cropped. + * It should be possible to crop borders each with a different color, + * but since there are many ways for corners to intersect, it would + * introduce unnecessary complexity to the algorithm. + */ + + // scan each side for same color borders + let colorTarget = this.getPixelColor(0, 0); // top left pixel color is the target color + const rgba1 = this.constructor.intToRGBA(colorTarget); + + // for north and east sides + let northPixelsToCrop = 0; + let eastPixelsToCrop = 0; + let southPixelsToCrop = 0; + let westPixelsToCrop = 0; + + // north side (scan rows from north to south) + colorTarget = this.getPixelColor(0, 0); + if (!ignoreSides.north) { + north: for (let y = 0; y < h - minPixelsPerSide; y++) { + for (let x = 0; x < w; x++) { + const colorXY = this.getPixelColor(x, y); + const rgba2 = this.constructor.intToRGBA(colorXY); + + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break north; + } + } + + // this row contains all pixels with the same color: increment this side pixels to crop + northPixelsToCrop++; + } + } + + // west side (scan columns from west to east) + colorTarget = this.getPixelColor(w, 0); + if (!ignoreSides.west) { + west: for (let x = 0; x < w - minPixelsPerSide; x++) { + for (let y = 0 + northPixelsToCrop; y < h; y++) { + const colorXY = this.getPixelColor(x, y); + const rgba2 = this.constructor.intToRGBA(colorXY); + + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break west; + } + } + + // this column contains all pixels with the same color: increment this side pixels to crop + westPixelsToCrop++; + } + } + + // south side (scan rows from south to north) + colorTarget = this.getPixelColor(0, h); + + if (!ignoreSides.south) { + south: for ( + let y = h - 1; + y >= northPixelsToCrop + minPixelsPerSide; + y-- + ) { + for (let x = w - eastPixelsToCrop - 1; x >= 0; x--) { + const colorXY = this.getPixelColor(x, y); + const rgba2 = this.constructor.intToRGBA(colorXY); + + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break south; + } + } + + // this row contains all pixels with the same color: increment this side pixels to crop + southPixelsToCrop++; + } + } + + // east side (scan columns from east to west) + colorTarget = this.getPixelColor(w, h); + if (!ignoreSides.east) { + east: for ( + let x = w - 1; + x >= 0 + westPixelsToCrop + minPixelsPerSide; + x-- + ) { + for (let y = h - 1; y >= 0 + northPixelsToCrop; y--) { + const colorXY = this.getPixelColor(x, y); + const rgba2 = this.constructor.intToRGBA(colorXY); + + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break east; + } + } + + // this column contains all pixels with the same color: increment this side pixels to crop + eastPixelsToCrop++; + } + } + + // decide if a crop is needed + let doCrop = false; + + // apply leaveBorder + westPixelsToCrop -= leaveBorder; + eastPixelsToCrop -= leaveBorder; + northPixelsToCrop -= leaveBorder; + southPixelsToCrop -= leaveBorder; + + if (cropSymmetric) { + const horizontal = Math.min(eastPixelsToCrop, westPixelsToCrop); + const vertical = Math.min(northPixelsToCrop, southPixelsToCrop); + westPixelsToCrop = horizontal; + eastPixelsToCrop = horizontal; + northPixelsToCrop = vertical; + southPixelsToCrop = vertical; + } + + // make sure that crops are >= 0 + westPixelsToCrop = westPixelsToCrop >= 0 ? westPixelsToCrop : 0; + eastPixelsToCrop = eastPixelsToCrop >= 0 ? eastPixelsToCrop : 0; + northPixelsToCrop = northPixelsToCrop >= 0 ? northPixelsToCrop : 0; + southPixelsToCrop = southPixelsToCrop >= 0 ? southPixelsToCrop : 0; + + // safety checks + const widthOfRemainingPixels = + w - (westPixelsToCrop + eastPixelsToCrop); + const heightOfRemainingPixels = + h - (southPixelsToCrop + northPixelsToCrop); + + if (cropOnlyFrames) { + // crop image if all sides should be cropped + doCrop = + eastPixelsToCrop !== 0 && + northPixelsToCrop !== 0 && + westPixelsToCrop !== 0 && + southPixelsToCrop !== 0; + } else { + // crop image if at least one side should be cropped + doCrop = + eastPixelsToCrop !== 0 || + northPixelsToCrop !== 0 || + westPixelsToCrop !== 0 || + southPixelsToCrop !== 0; + } + + if (doCrop) { + // do the real crop + this.crop( + westPixelsToCrop, + northPixelsToCrop, + widthOfRemainingPixels, + heightOfRemainingPixels + ); + } + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + }, + }; +} diff --git a/node_modules/@jimp/plugin-crop/test/autocrop.test.js b/node_modules/@jimp/plugin-crop/test/autocrop.test.js new file mode 100644 index 00000000..9fe2b3a7 --- /dev/null +++ b/node_modules/@jimp/plugin-crop/test/autocrop.test.js @@ -0,0 +1,408 @@ +import { Jimp, mkJGD } from "@jimp/test-utils"; +import configure from "@jimp/custom"; + +import crop from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [crop] }, Jimp); + +describe("Autocrop", () => { + it("image with transparent surround color", async () => { + const imgSrc = await jimp.read( + mkJGD( + " ", + " ◆◆ ", + " ◆▦▦◆ ", + " ◆▦▦▦▦◆ ", + " ◆▦▦◆ ", + " ◆◆ ", + " " + ) + ); + + expectToBeJGD( + imgSrc.autocrop().getJGDSync(), + mkJGD(" ◆◆ ", " ◆▦▦◆ ", "◆▦▦▦▦◆", " ◆▦▦◆ ", " ◆◆ ") + ); + }); + + it("image with opaque surround color", async () => { + const imgSrc = await jimp.read( + mkJGD( + "▥▥▥▥▥▥▥▥▥▥", + "▥▥▥▥◆◆▥▥▥▥", + "▥▥▥◆▦▦◆▥▥▥", + "▥▥◆▦▦▦▦◆▥▥", + "▥▥▥◆▦▦◆▥▥▥", + "▥▥▥▥◆◆▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥" + ) + ); + + expectToBeJGD( + imgSrc.autocrop().getJGDSync(), + mkJGD("▥▥◆◆▥▥", "▥◆▦▦◆▥", "◆▦▦▦▦◆", "▥◆▦▦◆▥", "▥▥◆◆▥▥") + ); + }); + + it("image with one color border", async () => { + const imgSrc = await jimp.read( + mkJGD( + "▥▥▥▥▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥▥▥", + "▥▥ ◆◆ ▥▥", + "▥▥ ◆▦▦◆ ▥▥", + "▥▥ ◆▦▦▦▦◆ ▥▥", + "▥▥ ◆▦▦◆ ▥▥", + "▥▥ ◆◆ ▥▥", + "▥▥▥▥▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥▥▥" + ) + ); + + expectToBeJGD( + imgSrc.autocrop().getJGDSync(), + mkJGD(" ◆◆ ", " ◆▦▦◆ ", " ◆▦▦▦▦◆ ", " ◆▦▦◆ ", " ◆◆ ") + ); + }); + + it("image border with small variation", async () => { + const imgSrc = await jimp.read( + mkJGD( + "323232323232", + "232323232323", + "32 ◆◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆▦▦▦▦◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆◆ 32", + "232323232323", + "323232323232" + ) + ); + expectToBeJGD( + imgSrc.clone().autocrop().getJGDSync(), + mkJGD( + "323232323232", + "232323232323", + "32 ◆◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆▦▦▦▦◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆◆ 32", + "232323232323", + "323232323232" + ) + ); + expectToBeJGD( + imgSrc.clone().autocrop(0.005).getJGDSync(), + mkJGD(" ◆◆ ", " ◆▦▦◆ ", " ◆▦▦▦▦◆ ", " ◆▦▦◆ ", " ◆◆ ") + ); + }); + + it("image border with small variation configured by options", async () => { + const imgSrc = await Jimp.read( + mkJGD( + "323232323232", + "232323232323", + "32 ◆◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆▦▦▦▦◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆◆ 32", + "232323232323", + "323232323232" + ) + ); + expectToBeJGD( + imgSrc.clone().autocrop().getJGDSync(), + mkJGD( + "323232323232", + "232323232323", + "32 ◆◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆▦▦▦▦◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆◆ 32", + "232323232323", + "323232323232" + ) + ); + expectToBeJGD( + imgSrc.clone().autocrop({ tolerance: 0.005 }).getJGDSync(), + mkJGD(" ◆◆ ", " ◆▦▦◆ ", " ◆▦▦▦▦◆ ", " ◆▦▦◆ ", " ◆◆ ") + ); + }); + + it("image without frame", async () => { + const imgSrc = await Jimp.read( + mkJGD( + "▥▥ ◆◆ ", + "▥▥ ◆▦▦◆ ", + "▥▥ ◆▦▦▦▦◆ ", + "▥▥ ◆▦▦◆ ", + "▥▥ ◆◆ ", + "▥▥▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥" + ) + ); + + expectToBeJGD( + imgSrc.autocrop(false).getJGDSync(), + mkJGD(" ◆◆ ", " ◆▦▦◆ ", " ◆▦▦▦▦◆ ", " ◆▦▦◆ ", " ◆◆ ") + ); + }); + + it("image without frame configured by options", async () => { + const imgSrc = await Jimp.read( + mkJGD( + "▥▥ ◆◆ ", + "▥▥ ◆▦▦◆ ", + "▥▥ ◆▦▦▦▦◆ ", + "▥▥ ◆▦▦◆ ", + "▥▥ ◆◆ ", + "▥▥▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥" + ) + ); + + expectToBeJGD( + imgSrc.autocrop({ cropOnlyFrames: false }).getJGDSync(), + mkJGD(" ◆◆ ", " ◆▦▦◆ ", " ◆▦▦▦▦◆ ", " ◆▦▦◆ ", " ◆◆ ") + ); + }); + + it("image with symmetric border configured by options", async () => { + const imgSrc = await Jimp.read( + mkJGD( + "▥▥▥▥▥▥▥▥▥▥▥▥▥▥", + "▥▥ ◆◆ ▥▥▥▥", + "▥▥ ◆▦▦◆ ▥▥▥▥", + "▥▥ ◆▦▦▦▦◆ ▥▥▥▥", + "▥▥ ◆▦▦◆ ▥▥▥▥", + "▥▥ ◆◆ ▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥▥▥▥▥" + ) + ); + + expectToBeJGD( + imgSrc.autocrop({ cropSymmetric: true }).getJGDSync(), + mkJGD( + " ◆◆ ▥▥", + " ◆▦▦◆ ▥▥", + " ◆▦▦▦▦◆ ▥▥", + " ◆▦▦◆ ▥▥", + " ◆◆ ▥▥", + "▥▥▥▥▥▥▥▥▥▥" + ) + ); + }); + + it("image without frame and with symmetric border configured by options", async () => { + const imgSrc = await Jimp.read( + mkJGD( + "▥▥ ◆◆ ▥▥▥▥", + "▥▥ ◆▦▦◆ ▥▥▥▥", + "▥▥ ◆▦▦▦▦◆ ▥▥▥▥", + "▥▥ ◆▦▦◆ ▥▥▥▥", + "▥▥ ◆◆ ▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥▥▥▥▥" + ) + ); + expectToBeJGD( + imgSrc + .autocrop({ cropSymmetric: true, cropOnlyFrames: false }) + .getJGDSync(), + mkJGD( + " ◆◆ ▥▥", + " ◆▦▦◆ ▥▥", + " ◆▦▦▦▦◆ ▥▥", + " ◆▦▦◆ ▥▥", + " ◆◆ ▥▥", + "▥▥▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥▥▥" + ) + ); + }); + + it("image without frame and with some border left", async () => { + const imgSrc = await Jimp.read( + mkJGD( + "323232323232", + "232323232323", + "32 ◆◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆▦▦▦▦◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆◆ 32", + "232323232323", + "323232323232" + ) + ); + + expectToBeJGD( + imgSrc + .autocrop({ + tolerance: 0.005, + leaveBorder: 1, + }) + .getJGDSync(), + mkJGD( + "3232323232", + "2 ◆◆ 3", + "3 ◆▦▦◆ 2", + "2 ◆▦▦▦▦◆ 3", + "3 ◆▦▦◆ 2", + "2 ◆◆ 3", + "3232323232" + ) + ); + }); + + it('image not cropped given an out of bounds "leaveBorder" value ', async () => { + const imgSrc = await Jimp.read( + mkJGD( + "323232323232", + "232323232323", + "32 ◆◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆▦▦▦▦◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆◆ 32", + "232323232323", + "323232323232" + ) + ); + expectToBeJGD( + imgSrc + .autocrop({ + tolerance: 0.005, + leaveBorder: 100, + }) + .getJGDSync(), + mkJGD( + "323232323232", + "232323232323", + "32 ◆◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆▦▦▦▦◆ 32", + "23 ◆▦▦◆ 23", + "32 ◆◆ 32", + "232323232323", + "323232323232" + ) + ); + }); + + it("image with top and bottom frame and leaveBorder", async () => { + const imgSrc = await Jimp.read( + mkJGD( + "▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥", + " ◆◆ ", + " ◆▦▦◆ ", + " ◆▦▦▦▦◆ ", + " ◆▦▦◆ ", + " ◆◆ ", + "▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥" + ) + ); + expectToBeJGD( + imgSrc + .autocrop({ + cropSymmetric: true, + cropOnlyFrames: false, + leaveBorder: 2, + }) + .getJGDSync(), + mkJGD( + "▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥", + " ◆◆ ", + " ◆▦▦◆ ", + " ◆▦▦▦▦◆ ", + " ◆▦▦◆ ", + " ◆◆ ", + "▥▥▥▥▥▥▥▥", + "▥▥▥▥▥▥▥▥" + ) + ); + }); + + it("ignore sides north", async () => { + const imgSrc = await jimp.read( + mkJGD( + " ", + " ◆◆ ", + " ◆▦▦◆ ", + " ◆▦▦▦▦◆ ", + " ◆▦▦◆ ", + " ◆◆ ", + " " + ) + ); + expectToBeJGD( + imgSrc + .autocrop({ cropOnlyFrames: false, ignoreSides: { north: true } }) + .getJGDSync(), + mkJGD(" ", " ◆◆ ", " ◆▦▦◆ ", "◆▦▦▦▦◆", " ◆▦▦◆ ", " ◆◆ ") + ); + }); + + it("ignore sides south and west", async () => { + const imgSrc = await jimp.read( + mkJGD( + " ", + " ◆◆ ", + " ◆▦▦◆ ", + " ◆▦▦▦▦◆ ", + " ◆▦▦◆ ", + " ◆◆ ", + " " + ) + ); + + expectToBeJGD( + imgSrc + .autocrop({ + cropOnlyFrames: false, + ignoreSides: { west: true, south: true }, + }) + .getJGDSync(), + mkJGD( + " ◆◆ ", + " ◆▦▦◆ ", + " ◆▦▦▦▦◆", + " ◆▦▦◆ ", + " ◆◆ ", + " " + ) + ); + }); + + it("ignore sides east", async () => { + const imgSrc = await jimp.read( + mkJGD( + " ", + " ◆◆ ", + " ◆▦▦◆ ", + " ◆▦▦▦▦◆ ", + " ◆▦▦◆ ", + " ◆◆ ", + " " + ) + ); + + expectToBeJGD( + imgSrc + .autocrop({ cropOnlyFrames: false, ignoreSides: { east: true } }) + .getJGDSync(), + mkJGD(" ◆◆ ", " ◆▦▦◆ ", "◆▦▦▦▦◆ ", " ◆▦▦◆ ", " ◆◆ ") + ); + }); +}); diff --git a/node_modules/@jimp/plugin-crop/test/crop.test.js b/node_modules/@jimp/plugin-crop/test/crop.test.js new file mode 100644 index 00000000..a6bb5002 --- /dev/null +++ b/node_modules/@jimp/plugin-crop/test/crop.test.js @@ -0,0 +1,66 @@ +import { Jimp, mkJGD } from "@jimp/test-utils"; +import configure from "@jimp/custom"; + +import crop from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [crop] }, Jimp); + +describe("crop", () => { + // 6x5 size + const testImage = mkJGD(" ◆◆ ", " ◆▦▦◆ ", "◆▦▦▦▦◆", " ◆▦▦◆ ", " ◆◆ "); + + it("full width from top", async () => { + const imgSrc = await jimp.read(testImage); + + expectToBeJGD( + imgSrc.crop(0, 0, 6, 2).getJGDSync(), + mkJGD(" ◆◆ ", " ◆▦▦◆ ") + ); + }); + + it("full width from bottom", async () => { + const imgSrc = await jimp.read(testImage); + + expectToBeJGD( + imgSrc.crop(0, 3, 6, 2).getJGDSync(), + mkJGD(" ◆▦▦◆ ", " ◆◆ ") + ); + }); + + it("full width from middle", async () => { + const imgSrc = await jimp.read(testImage); + + expectToBeJGD( + imgSrc.crop(0, 2, 6, 2).getJGDSync(), + mkJGD("◆▦▦▦▦◆", " ◆▦▦◆ ") + ); + }); + + it("full height from left", async () => { + const imgSrc = await jimp.read(testImage); + + expectToBeJGD( + imgSrc.crop(0, 0, 2, 5).getJGDSync(), + mkJGD(" ", " ◆", "◆▦", " ◆", " ") + ); + }); + + it("full height from right", async () => { + const imgSrc = await jimp.read(testImage); + + expectToBeJGD( + imgSrc.crop(4, 0, 2, 5).getJGDSync(), + mkJGD(" ", "◆ ", "▦◆", "◆ ", " ") + ); + }); + + it("full height from middle", async () => { + const imgSrc = await jimp.read(testImage); + + expectToBeJGD( + imgSrc.crop(2, 0, 2, 5).getJGDSync(), + mkJGD("◆◆", "▦▦", "▦▦", "▦▦", "◆◆") + ); + }); +}); diff --git a/node_modules/@jimp/plugin-displace/CHANGELOG.md b/node_modules/@jimp/plugin-displace/CHANGELOG.md new file mode 100644 index 00000000..8d029143 --- /dev/null +++ b/node_modules/@jimp/plugin-displace/CHANGELOG.md @@ -0,0 +1,71 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-displace/LICENSE b/node_modules/@jimp/plugin-displace/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-displace/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-displace/README.md b/node_modules/@jimp/plugin-displace/README.md new file mode 100644 index 00000000..d74a2447 --- /dev/null +++ b/node_modules/@jimp/plugin-displace/README.md @@ -0,0 +1,27 @@ +
+ +

@jimp/plugin-displace

+

Displace an image.

+
+ +Displaces the image based on the provided displacement map + +## Usage + +- @param {object} map the source Jimp instance +- @param {number} offset the maximum displacement value +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + // Make me better! + image.displace(map, 10); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-displace/es/index.js b/node_modules/@jimp/plugin-displace/es/index.js new file mode 100644 index 00000000..acdc290c --- /dev/null +++ b/node_modules/@jimp/plugin-displace/es/index.js @@ -0,0 +1,33 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Displaces the image based on the provided displacement map + * @param {object} map the source Jimp instance + * @param {number} offset the maximum displacement value + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + displace(map, offset, cb) { + if (typeof map !== "object" || map.constructor !== this.constructor) { + return throwError.call(this, "The source must be a Jimp image", cb); + } + if (typeof offset !== "number") { + return throwError.call(this, "factor must be a number", cb); + } + const source = this.cloneQuiet(); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + let displacement = map.bitmap.data[idx] / 256 * offset; + displacement = Math.round(displacement); + const ids = this.getPixelIndex(x + displacement, y); + this.bitmap.data[ids] = source.bitmap.data[idx]; + this.bitmap.data[ids + 1] = source.bitmap.data[idx + 1]; + this.bitmap.data[ids + 2] = source.bitmap.data[idx + 2]; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-displace/es/index.js.map b/node_modules/@jimp/plugin-displace/es/index.js.map new file mode 100644 index 00000000..3c4a069d --- /dev/null +++ b/node_modules/@jimp/plugin-displace/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","displace","map","offset","cb","constructor","call","source","cloneQuiet","scanQuiet","bitmap","width","height","x","y","idx","displacement","data","Math","round","ids","getPixelIndex"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Displaces the image based on the provided displacement map\n * @param {object} map the source Jimp instance\n * @param {number} offset the maximum displacement value\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n displace(map, offset, cb) {\n if (typeof map !== \"object\" || map.constructor !== this.constructor) {\n return throwError.call(this, \"The source must be a Jimp image\", cb);\n }\n\n if (typeof offset !== \"number\") {\n return throwError.call(this, \"factor must be a number\", cb);\n }\n\n const source = this.cloneQuiet();\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n let displacement = (map.bitmap.data[idx] / 256) * offset;\n displacement = Math.round(displacement);\n\n const ids = this.getPixelIndex(x + displacement, y);\n this.bitmap.data[ids] = source.bitmap.data[idx];\n this.bitmap.data[ids + 1] = source.bitmap.data[idx + 1];\n this.bitmap.data[ids + 2] = source.bitmap.data[idx + 2];\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;;AAEvD;AACA;AACA;AACA;A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AC,CAAC;IACzD,CAAC,CACF;IAED,IAAIhB,aAAa,CAACK,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-displace/index.d.ts b/node_modules/@jimp/plugin-displace/index.d.ts new file mode 100644 index 00000000..d2ea79bf --- /dev/null +++ b/node_modules/@jimp/plugin-displace/index.d.ts @@ -0,0 +1,7 @@ +import { Jimp, ImageCallback } from "@jimp/core"; + +interface Displace { + displace(map: Jimp, offset: number, cb?: ImageCallback): this; +} + +export default function (): Displace; diff --git a/node_modules/@jimp/plugin-displace/package.json b/node_modules/@jimp/plugin-displace/package.json new file mode 100644 index 00000000..3f4eaa1a --- /dev/null +++ b/node_modules/@jimp/plugin-displace/package.json @@ -0,0 +1,30 @@ +{ + "name": "@jimp/plugin-displace", + "version": "0.22.12", + "description": "displace an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-displace/src/index.js b/node_modules/@jimp/plugin-displace/src/index.js new file mode 100644 index 00000000..4dcd4403 --- /dev/null +++ b/node_modules/@jimp/plugin-displace/src/index.js @@ -0,0 +1,43 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Displaces the image based on the provided displacement map + * @param {object} map the source Jimp instance + * @param {number} offset the maximum displacement value + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + displace(map, offset, cb) { + if (typeof map !== "object" || map.constructor !== this.constructor) { + return throwError.call(this, "The source must be a Jimp image", cb); + } + + if (typeof offset !== "number") { + return throwError.call(this, "factor must be a number", cb); + } + + const source = this.cloneQuiet(); + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + let displacement = (map.bitmap.data[idx] / 256) * offset; + displacement = Math.round(displacement); + + const ids = this.getPixelIndex(x + displacement, y); + this.bitmap.data[ids] = source.bitmap.data[idx]; + this.bitmap.data[ids + 1] = source.bitmap.data[idx + 1]; + this.bitmap.data[ids + 2] = source.bitmap.data[idx + 2]; + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-dither/CHANGELOG.md b/node_modules/@jimp/plugin-dither/CHANGELOG.md new file mode 100644 index 00000000..8d029143 --- /dev/null +++ b/node_modules/@jimp/plugin-dither/CHANGELOG.md @@ -0,0 +1,71 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-dither/LICENSE b/node_modules/@jimp/plugin-dither/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-dither/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-dither/README.md b/node_modules/@jimp/plugin-dither/README.md new file mode 100644 index 00000000..b384599d --- /dev/null +++ b/node_modules/@jimp/plugin-dither/README.md @@ -0,0 +1,26 @@ +
+ +

@jimp/plugin-dither

+

Apply a dither effect to an image.

+
+ +> Dither - is an intentionally applied form of noise used to randomize quantization error, preventing large-scale patterns such as color banding in images. Dither is routinely used in processing of both digital audio and video data, and is often one of the last stages of mastering audio to a CD. + +## Usage + +Apply a ordered dithering effect + +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.dither565(); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-dither/es/index.js b/node_modules/@jimp/plugin-dither/es/index.js new file mode 100644 index 00000000..0dcc1360 --- /dev/null +++ b/node_modules/@jimp/plugin-dither/es/index.js @@ -0,0 +1,26 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Apply a ordered dithering effect + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +function dither(cb) { + const rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6]; + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + const thresholdId = ((y & 3) << 2) + x % 4; + const dither = rgb565Matrix[thresholdId]; + this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff); + this.bitmap.data[idx + 1] = Math.min(this.bitmap.data[idx + 1] + dither, 0xff); + this.bitmap.data[idx + 2] = Math.min(this.bitmap.data[idx + 2] + dither, 0xff); + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; +} +export default (() => ({ + dither565: dither, + dither16: dither +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-dither/es/index.js.map b/node_modules/@jimp/plugin-dither/es/index.js.map new file mode 100644 index 00000000..f3ec9697 --- /dev/null +++ b/node_modules/@jimp/plugin-dither/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","dither","cb","rgb565Matrix","scanQuiet","bitmap","width","height","x","y","idx","thresholdId","data","Math","min","call","dither565","dither16"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Apply a ordered dithering effect\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nfunction dither(cb) {\n const rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6];\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n const thresholdId = ((y & 3) << 2) + (x % 4);\n const dither = rgb565Matrix[thresholdId];\n this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff);\n this.bitmap.data[idx + 1] = Math.min(\n this.bitmap.data[idx + 1] + dither,\n 0xff\n );\n this.bitmap.data[idx + 2] = Math.min(\n this.bitmap.data[idx + 2] + dither,\n 0xff\n );\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n}\n\nexport default () => ({\n dither565: dither,\n dither16: dither,\n});\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,aAAa;;AAE3C;AACA;AACA;AACA;AACA;AACA,SAASC,MAAM,CAACC,EAAE,EAAE;EAClB,MAAMC,YAAY,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;EAC5E,IAAI,CAACC,SAAS,CACZ,CAAC,EACD,CAAC,EACD,IAAI,CAACC,MAAM,CAACC,KAAK,EACjB,IAAI,CAACD,MAAM,CAACE,MAAM,EAClB,UAAUC,CAAC,EAAEC,CAAC,EAAEC,GAAG,EAAE;IACnB,MAAMC,WAAW,GAAG,CAAC,CAACF,CAAC,GAAG,CAAC,KAAK,CAAC,IAAKD,CAAC,GAAG,CAAE;IAC5C,MAAMP,MAAM,GAAGE,YAAY,CAACQ,WAAW,CAAC;IACxC,IAAI,CAACN,MAAM,CAACO,IAAI,CAACF,GAAG,CAAC,GAAGG,IAAI,CAACC,GAAG,CAAC,IAAI,CAACT,MAAM,CAACO,IAAI,CAACF,GAAG,CAAC,GAAGT,MAAM,EAAE,IAAI,CAAC;IACtE,IAAI,CAACI,MAAM,CAACO,IAAI,CAACF,GAAG,GAAG,CAAC,CAAC,GAAGG,IAAI,CAACC,GAAG,CAClC,IAAI,CAACT,MAAM,CAACO,IAAI,CAACF,GAAG,GAAG,CAAC,CAAC,GAAGT,MAAM,EAClC,IAAI,CACL;IACD,IAAI,CAACI,MAAM,CAACO,IAAI,CAACF,GAAG,GAAG,CAAC,CAAC,GAAGG,IAAI,CAACC,GAAG,CAClC,IAAI,CAACT,MAAM,CAACO,IAAI,CAACF,GAAG,GAAG,CAAC,CAAC,GAAGT,MAAM,EAClC,IAAI,CACL;EACH,CAAC,CACF;EAED,IAAID,aAAa,CAACE,EAAE,CAAC,EAAE;IACrBA,EAAE,CAACa,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;EAC3B;EAEA,OAAO,IAAI;AACb;AAEA,gBAAe,OAAO;EACpBC,SAAS,EAAEf,MAAM;EACjBgB,QAAQ,EAAEhB;AACZ,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-dither/index.d.ts b/node_modules/@jimp/plugin-dither/index.d.ts new file mode 100644 index 00000000..9f2415df --- /dev/null +++ b/node_modules/@jimp/plugin-dither/index.d.ts @@ -0,0 +1,8 @@ +import { ImageCallback } from "@jimp/core"; + +interface Dither { + dither565(cb?: ImageCallback): this; + dither16(cb?: ImageCallback): this; +} + +export default function (): Dither; diff --git a/node_modules/@jimp/plugin-dither/package.json b/node_modules/@jimp/plugin-dither/package.json new file mode 100644 index 00000000..0f65daff --- /dev/null +++ b/node_modules/@jimp/plugin-dither/package.json @@ -0,0 +1,30 @@ +{ + "name": "@jimp/plugin-dither", + "version": "0.22.12", + "description": "Dither an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-dither/src/index.js b/node_modules/@jimp/plugin-dither/src/index.js new file mode 100644 index 00000000..c5ce9ece --- /dev/null +++ b/node_modules/@jimp/plugin-dither/src/index.js @@ -0,0 +1,40 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Apply a ordered dithering effect + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +function dither(cb) { + const rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6]; + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + const thresholdId = ((y & 3) << 2) + (x % 4); + const dither = rgb565Matrix[thresholdId]; + this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff); + this.bitmap.data[idx + 1] = Math.min( + this.bitmap.data[idx + 1] + dither, + 0xff + ); + this.bitmap.data[idx + 2] = Math.min( + this.bitmap.data[idx + 2] + dither, + 0xff + ); + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; +} + +export default () => ({ + dither565: dither, + dither16: dither, +}); diff --git a/node_modules/@jimp/plugin-fisheye/CHANGELOG.md b/node_modules/@jimp/plugin-fisheye/CHANGELOG.md new file mode 100644 index 00000000..a3763830 --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/CHANGELOG.md @@ -0,0 +1,97 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.2 (Thu Sep 15 2022) + +#### 📝 Documentation + +- added the "e" back to @jimp/plugin-fisheye [#947](https://github.com/oliver-moran/jimp/pull/947) ([@mynameismax](https://github.com/mynameismax)) + +#### Authors: 1 + +- Max ([@mynameismax](https://github.com/mynameismax)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-fisheye/LICENSE b/node_modules/@jimp/plugin-fisheye/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-fisheye/README.md b/node_modules/@jimp/plugin-fisheye/README.md new file mode 100644 index 00000000..3a1ae13c --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/README.md @@ -0,0 +1,27 @@ +
+ +

@jimp/plugin-fisheye

+

Apply a fisheye effect to an image

+
+ +## Usage + +- @param {function(Error, Jimp)} options (optional) radius +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.fisheye(); + // or + image.fisheye({ r: 1.6 }); +} + +main(); +``` + +Produces nice images with [@jimp/plugin-circle](../plugin-circle). diff --git a/node_modules/@jimp/plugin-fisheye/babel.config.js b/node_modules/@jimp/plugin-fisheye/babel.config.js new file mode 100644 index 00000000..13e2603a --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/babel.config.js @@ -0,0 +1,38 @@ +module.exports = (api) => { + api.cache(true); + + return { + presets: [ + [ + "@babel/env", + { + useBuiltIns: "usage", + }, + ], + ], + + plugins: [ + "@babel/proposal-class-properties", + "@babel/syntax-object-rest-spread", + process.env.BABEL_ENV !== "module" && "add-module-exports", + [ + "transform-inline-environment-variables", + { include: ["BABEL_ENV", "ENV"] }, + ], + ].filter(Boolean), + + env: { + test: { + plugins: ["istanbul"], + }, + development: { + plugins: [process.env.ENV !== "browser" && "source-map-support"].filter( + Boolean + ), + }, + module: { + presets: [["@babel/env", { modules: false }]], + }, + }, + }; +}; diff --git a/node_modules/@jimp/plugin-fisheye/es/index.js b/node_modules/@jimp/plugin-fisheye/es/index.js new file mode 100644 index 00000000..f50b9458 --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/es/index.js @@ -0,0 +1,47 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Creates a circle out of an image. + * @param {object} options (optional) r: radius of effect + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + fisheye() { + let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + r: 2.5 + }; + let cb = arguments.length > 1 ? arguments[1] : undefined; + if (typeof options === "function") { + cb = options; + options = { + r: 2.5 + }; + } + const source = this.cloneQuiet(); + const { + width, + height + } = source.bitmap; + source.scanQuiet(0, 0, width, height, (x, y) => { + const hx = x / width; + const hy = y / height; + const r = Math.sqrt(Math.pow(hx - 0.5, 2) + Math.pow(hy - 0.5, 2)); + const rn = 2 * Math.pow(r, options.r); + const cosA = (hx - 0.5) / r; + const sinA = (hy - 0.5) / r; + const newX = Math.round((rn * cosA + 0.5) * width); + const newY = Math.round((rn * sinA + 0.5) * height); + const color = source.getPixelColor(newX, newY); + this.setPixelColor(color, x, y); + }); + + /* Set center pixel color, otherwise it will be transparent */ + this.setPixelColor(source.getPixelColor(width / 2, height / 2), width / 2, height / 2); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-fisheye/es/index.js.map b/node_modules/@jimp/plugin-fisheye/es/index.js.map new file mode 100644 index 00000000..19b713df --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","fisheye","options","r","cb","source","cloneQuiet","width","height","bitmap","scanQuiet","x","y","hx","hy","Math","sqrt","pow","rn","cosA","sinA","newX","round","newY","color","getPixelColor","setPixelColor","call"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Creates a circle out of an image.\n * @param {object} options (optional) r: radius of effect\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n fisheye(options = { r: 2.5 }, cb) {\n if (typeof options === \"function\") {\n cb = options;\n options = { r: 2.5 };\n }\n\n const source = this.cloneQuiet();\n const { width, height } = source.bitmap;\n\n source.scanQuiet(0, 0, width, height, (x, y) => {\n const hx = x / width;\n const hy = y / height;\n const r = Math.sqrt(Math.pow(hx - 0.5, 2) + Math.pow(hy - 0.5, 2));\n const rn = 2 * Math.pow(r, options.r);\n const cosA = (hx - 0.5) / r;\n const sinA = (hy - 0.5) / r;\n const newX = Math.round((rn * cosA + 0.5) * width);\n const newY = Math.round((rn * sinA + 0.5) * height);\n const color = source.getPixelColor(newX, newY);\n\n this.setPixelColor(color, x, y);\n });\n\n /* Set center pixel color, otherwise it will be transparent */\n this.setPixelColor(\n source.getPixelColor(width / 2, height / 2),\n width / 2,\n height / 2\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,aAAa;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe,OAAO;EACpBC,OAAO,GAA2B;IAAA,IAA1BC,OAAO,uEAAG;MAAEC,CAAC,EAAE;IAAI,CAAC;IAAA,IAAEC,EAAE;IAC9B,IAAI,OAAOF,OAAO,KAAK,UAAU,EAAE;MACjCE,EAAE,GAAGF,OAAO;MACZA,OAAO,GAAG;QAAEC,CAAC,EAAE;MAAI,CAAC;IACtB;IAEA,MAAME,MAAM,GAAG,IAAI,CAACC,UAAU,EAAE;IAChC,MAAM;MAAEC,KAAK;MAAEC;IAAO,CAAC,GAAGH,MAAM,CAACI,MAAM;IAEvCJ,MAAM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AAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-fisheye/index.d.ts b/node_modules/@jimp/plugin-fisheye/index.d.ts new file mode 100644 index 00000000..693b6f33 --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/index.d.ts @@ -0,0 +1,8 @@ +import { ImageCallback } from "@jimp/core"; + +interface Fisheye { + fishEye(opts?: { r: number }, cb?: ImageCallback): this; + fishEye(cb?: ImageCallback): this; +} + +export default function (): Fisheye; diff --git a/node_modules/@jimp/plugin-fisheye/package.json b/node_modules/@jimp/plugin-fisheye/package.json new file mode 100644 index 00000000..53e8d7c8 --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/package.json @@ -0,0 +1,37 @@ +{ + "name": "@jimp/plugin-fisheye", + "version": "0.22.12", + "description": "Apply a fisheye effect to an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-fisheye/src/index.js b/node_modules/@jimp/plugin-fisheye/src/index.js new file mode 100644 index 00000000..15c5b51d --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/src/index.js @@ -0,0 +1,46 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Creates a circle out of an image. + * @param {object} options (optional) r: radius of effect + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + fisheye(options = { r: 2.5 }, cb) { + if (typeof options === "function") { + cb = options; + options = { r: 2.5 }; + } + + const source = this.cloneQuiet(); + const { width, height } = source.bitmap; + + source.scanQuiet(0, 0, width, height, (x, y) => { + const hx = x / width; + const hy = y / height; + const r = Math.sqrt(Math.pow(hx - 0.5, 2) + Math.pow(hy - 0.5, 2)); + const rn = 2 * Math.pow(r, options.r); + const cosA = (hx - 0.5) / r; + const sinA = (hy - 0.5) / r; + const newX = Math.round((rn * cosA + 0.5) * width); + const newY = Math.round((rn * sinA + 0.5) * height); + const color = source.getPixelColor(newX, newY); + + this.setPixelColor(color, x, y); + }); + + /* Set center pixel color, otherwise it will be transparent */ + this.setPixelColor( + source.getPixelColor(width / 2, height / 2), + width / 2, + height / 2 + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-fisheye/test/fisheye.test.js b/node_modules/@jimp/plugin-fisheye/test/fisheye.test.js new file mode 100644 index 00000000..537b4f45 --- /dev/null +++ b/node_modules/@jimp/plugin-fisheye/test/fisheye.test.js @@ -0,0 +1,78 @@ +import { Jimp, mkJGD } from "@jimp/test-utils"; +import configure from "@jimp/custom"; + +import fisheye from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [fisheye] }, Jimp); + +describe("Fisheye", () => { + it("should create fisheye lens to image", async () => { + const imgNormal = await jimp.read( + mkJGD( + "0000000000", + "0001221000", + "0022222200", + "0122112210", + "0221001220", + "0221001220", + "0122112210", + "0022222200", + "0001221000", + "0000000000" + ) + ); + const imgBulged = await jimp.read( + mkJGD( + "0001221000", + "0221112220", + "0220000121", + "1100000112", + "2100000012", + "2100000012", + "1200000012", + "0211000222", + "0221111220", + "0012222200" + ) + ); + + expectToBeJGD(imgNormal.fisheye().getJGDSync(), imgBulged.getJGDSync()); + }); + + it("should create fisheye lens to image with radius", async () => { + const imgNormal = await jimp.read( + mkJGD( + "0000000000", + "0000000000", + "0000000000", + "0000000000", + "0001111000", + "0001111000", + "0000000000", + "0000000000", + "0000000000", + "0000000000" + ) + ); + const imgBulged = await jimp.read( + mkJGD( + "■■■■■■■■■■", + "■■■■■■■■■■", + "■■■■■■■■■■", + "■■■11111■■", + "■■111111■■", + "■■111111■■", + "■■■■111■■■", + "■■■■■■■■■■", + "■■■■■■■■■■", + "■■■■■■■■■■" + ) + ); + + expectToBeJGD( + imgNormal.fisheye({ r: 1.8 }).getJGDSync(), + imgBulged.getJGDSync() + ); + }); +}); diff --git a/node_modules/@jimp/plugin-flip/CHANGELOG.md b/node_modules/@jimp/plugin-flip/CHANGELOG.md new file mode 100644 index 00000000..16844d0a --- /dev/null +++ b/node_modules/@jimp/plugin-flip/CHANGELOG.md @@ -0,0 +1,97 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.10.3 (Mon Apr 20 2020) + +#### 🐛 Bug Fix + +- Simplify and fix flip [#879](https://github.com/oliver-moran/jimp/pull/879) ([@skalee](https://github.com/skalee)) + +#### Authors: 1 + +- Sebastian Skałacki ([@skalee](https://github.com/skalee)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-flip/LICENSE b/node_modules/@jimp/plugin-flip/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-flip/README.md b/node_modules/@jimp/plugin-flip/README.md new file mode 100644 index 00000000..dd7ecaf5 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/README.md @@ -0,0 +1,30 @@ +
+ +

@jimp/plugin-flip

+

flip an image.

+
+ +Flip the image horizontally or vertically. Defaults to horizontal. + +Also aliased as `mirror` + +## Usage + +- @param {boolean} horizontal a Boolean, if true the image will be flipped horizontally +- @param {boolean} vertical a Boolean, if true the image will be flipped vertically +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.flip(); + image.mirror(); + image.flip(false, true); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-flip/es/flipping.test.js b/node_modules/@jimp/plugin-flip/es/flipping.test.js new file mode 100644 index 00000000..685a13f9 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/es/flipping.test.js @@ -0,0 +1,25 @@ +import { Jimp, mkJGD } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import flip from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; +const jimp = configure({ + plugins: [flip] +}, Jimp); +describe("Flipping plugin", () => { + it("can flip horizontally", async () => { + const src = await jimp.read(mkJGD("AAAABBBB", "AAABAAAB", "ABABABAB", "CCCCCCCC", "CCCCCCCC", "CCCCCCCC", "AACCCCAA")); + const result = src.flip(true, false); + expectToBeJGD(result.getJGDSync(), mkJGD("BBBBAAAA", "BAAABAAA", "BABABABA", "CCCCCCCC", "CCCCCCCC", "CCCCCCCC", "AACCCCAA")); + }); + it("can flip vertically", async () => { + const src = await jimp.read(mkJGD("AAAABBBB", "AAABAAAB", "ABABABAB", "CCCCCCCC", "CCCCCCCC", "CCCCCCCC", "AACCCCAA")); + const result = src.flip(false, true); + expectToBeJGD(result.getJGDSync(), mkJGD("AACCCCAA", "CCCCCCCC", "CCCCCCCC", "CCCCCCCC", "ABABABAB", "AAABAAAB", "AAAABBBB")); + }); + it("can flip both horizontally and vertically at once", async () => { + const src = await jimp.read(mkJGD("AAAABBBB", "AAABAAAB", "ABABABAB", "CCCCCCCC", "CCCCCCCC", "CCCCCCCC", "AACCCCAA")); + const result = src.flip(true, true); + expectToBeJGD(result.getJGDSync(), mkJGD("AACCCCAA", "CCCCCCCC", "CCCCCCCC", "CCCCCCCC", "BABABABA", "BAAABAAA", "BBBBAAAA")); + }); +}); +//# sourceMappingURL=flipping.test.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-flip/es/flipping.test.js.map b/node_modules/@jimp/plugin-flip/es/flipping.test.js.map new file mode 100644 index 00000000..e38c9f54 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/es/flipping.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"flipping.test.js","names":["Jimp","mkJGD","configure","flip","expectToBeJGD","jimp","plugins","describe","it","src","read","result","getJGDSync"],"sources":["../test/flipping.test.js"],"sourcesContent":["import { Jimp, mkJGD } from \"@jimp/test-utils\";\n\nimport configure from \"@jimp/custom\";\n\nimport flip from \"../src\";\nimport { expectToBeJGD } from \"@jimp/test-utils/src\";\n\nconst jimp = configure({ plugins: [flip] }, Jimp);\n\ndescribe(\"Flipping plugin\", () => {\n it(\"can flip horizontally\", async () => {\n const src = await jimp.read(\n mkJGD(\n \"AAAABBBB\",\n \"AAABAAAB\",\n \"ABABABAB\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"AACCCCAA\"\n )\n );\n\n const result = src.flip(true, false);\n\n expectToBeJGD(\n result.getJGDSync(),\n mkJGD(\n \"BBBBAAAA\",\n \"BAAABAAA\",\n \"BABABABA\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"AACCCCAA\"\n )\n );\n });\n\n it(\"can flip vertically\", async () => {\n const src = await jimp.read(\n mkJGD(\n \"AAAABBBB\",\n \"AAABAAAB\",\n \"ABABABAB\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"AACCCCAA\"\n )\n );\n\n const result = src.flip(false, true);\n\n expectToBeJGD(\n result.getJGDSync(),\n mkJGD(\n \"AACCCCAA\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"ABABABAB\",\n \"AAABAAAB\",\n \"AAAABBBB\"\n )\n );\n });\n\n it(\"can flip both horizontally and vertically at once\", async () => {\n const src = await jimp.read(\n mkJGD(\n \"AAAABBBB\",\n \"AAABAAAB\",\n \"ABABABAB\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"AACCCCAA\"\n )\n );\n\n const result = src.flip(true, true);\n\n expectToBeJGD(\n result.getJGDSync(),\n mkJGD(\n \"AACCCCAA\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"CCCCCCCC\",\n \"BABABABA\",\n \"BAAABAAA\",\n \"BBBBAAAA\"\n )\n );\n });\n});\n"],"mappings":"AAAA,SAASA,IAAI,EAAEC,KAAK,QAAQ,kBAAkB;AAE9C,OAAOC,SAAS,MAAM,cAAc;AAEpC,OAAOC,IAAI,MAAM,QAAQ;AACzB,SAASC,aAAa,QAAQ,sBAAsB;AAEpD,MAAMC,IAAI,GAAGH,SAAS,CAAC;EAAEI,OAAO,EAAE,CAACH,IAAI;AAAE,CAAC,EAAEH,IAAI,CAAC;AAEjDO,QAAQ,CAAC,iBAAiB,EAAE,MAAM;EAChCC,EAAE,CAAC,uBAAuB,EAAE,YAAY;IACtC,MAAMC,GAAG,GAAG,MAAMJ,IAAI,CAACK,IAAI,CACzBT,KAAK,CACH,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,CACX,CACF;IAED,MAAMU,MAAM,GAAGF,GAAG,CAACN,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC;IAEpCC,aAAa,CACXO,MAAM,CAACC,UAAU,EAAE,EACnBX,KAAK,CACH,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,CACX,CACF;EACH,CAAC,CAAC;EAEFO,EAAE,CAAC,qBAAqB,EAAE,YAAY;IACpC,MAAMC,GAAG,GAAG,MAAMJ,IAAI,CAACK,IAAI,CACzBT,KAAK,CACH,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,CACX,CACF;IAED,MAAMU,MAAM,GAAGF,GAAG,CAACN,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC;IAEpCC,aAAa,CACXO,MAAM,CAACC,UAAU,EAAE,EACnBX,KAAK,CACH,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,CACX,CACF;EACH,CAAC,CAAC;EAEFO,EAAE,CAAC,mDAAmD,EAAE,YAAY;IAClE,MAAMC,GAAG,GAAG,MAAMJ,IAAI,CAACK,IAAI,CACzBT,KAAK,CACH,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,CACX,CACF;IAED,MAAMU,MAAM,GAAGF,GAAG,CAACN,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;IAEnCC,aAAa,CACXO,MAAM,CAACC,UAAU,EAAE,EACnBX,KAAK,CACH,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,CACX,CACF;EACH,CAAC,CAAC;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-flip/es/index.js b/node_modules/@jimp/plugin-flip/es/index.js new file mode 100644 index 00000000..64931680 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/es/index.js @@ -0,0 +1,30 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Flip the image horizontally + * @param {boolean} horizontal a Boolean, if true the image will be flipped horizontally + * @param {boolean} vertical a Boolean, if true the image will be flipped vertically + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +function flipFn(horizontal, vertical, cb) { + if (typeof horizontal !== "boolean" || typeof vertical !== "boolean") return throwError.call(this, "horizontal and vertical must be Booleans", cb); + const bitmap = Buffer.alloc(this.bitmap.data.length); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + const _x = horizontal ? this.bitmap.width - 1 - x : x; + const _y = vertical ? this.bitmap.height - 1 - y : y; + const _idx = this.bitmap.width * _y + _x << 2; + const data = this.bitmap.data.readUInt32BE(idx); + bitmap.writeUInt32BE(data, _idx); + }); + this.bitmap.data = Buffer.from(bitmap); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; +} +export default (() => ({ + flip: flipFn, + mirror: flipFn +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-flip/es/index.js.map b/node_modules/@jimp/plugin-flip/es/index.js.map new file mode 100644 index 00000000..c8499213 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","flipFn","horizontal","vertical","cb","call","bitmap","Buffer","alloc","data","length","scanQuiet","width","height","x","y","idx","_x","_y","_idx","readUInt32BE","writeUInt32BE","from","flip","mirror"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Flip the image horizontally\n * @param {boolean} horizontal a Boolean, if true the image will be flipped horizontally\n * @param {boolean} vertical a Boolean, if true the image will be flipped vertically\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nfunction flipFn(horizontal, vertical, cb) {\n if (typeof horizontal !== \"boolean\" || typeof vertical !== \"boolean\")\n return throwError.call(\n this,\n \"horizontal and vertical must be Booleans\",\n cb\n );\n\n const bitmap = Buffer.alloc(this.bitmap.data.length);\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n const _x = horizontal ? this.bitmap.width - 1 - x : x;\n const _y = vertical ? this.bitmap.height - 1 - y : y;\n const _idx = (this.bitmap.width * _y + _x) << 2;\n const data = this.bitmap.data.readUInt32BE(idx);\n\n bitmap.writeUInt32BE(data, _idx);\n }\n );\n\n this.bitmap.data = Buffer.from(bitmap);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n}\n\nexport default () => ({\n flip: flipFn,\n mirror: flipFn,\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;;AAEvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,MAAM,CAACC,UAAU,EAAEC,QAAQ,EAAEC,EAAE,EAAE;EACxC,IAAI,OAAOF,UAAU,KAAK,SAAS,IAAI,OAAOC,QAAQ,KAAK,SAAS,EAClE,OAAOH,UAAU,CAACK,IAAI,CACpB,IAAI,EACJ,0CAA0C,EAC1CD,EAAE,CACH;EAEH,MAAME,MAAM,GAAGC,MAAM,CAACC,KAAK,CAAC,IAAI,CAACF,MAAM,CAACG,IAAI,CAACC,MAAM,CAAC;EACpD,IAAI,CAACC,SAAS,CACZ,CAAC,EACD,CAAC,EACD,IAAI,CAACL,MAAM,CAACM,KAAK,EACjB,IAAI,CAACN,MAAM,CAACO,MAAM,EAClB,UAAUC,CAAC,EAAEC,CAAC,EAAEC,GAAG,EAAE;IACnB,MAAMC,EAAE,GAAGf,UAAU,GAAG,IAAI,CAACI,MAAM,CAACM,KAAK,GAAG,CAAC,GAAGE,CAAC,GAAGA,CAAC;IACrD,MAAMI,EAAE,GAAGf,QAAQ,GAAG,IAAI,CAACG,MAAM,CAACO,MAAM,GAAG,CAAC,GAAGE,CAAC,GAAGA,CAAC;IACpD,MAAMI,IAAI,GAAI,IAAI,CAACb,MAAM,CAACM,KAAK,GAAGM,EAAE,GAAGD,EAAE,IAAK,CAAC;IAC/C,MAAMR,IAAI,GAAG,IAAI,CAACH,MAAM,CAACG,IAAI,CAACW,YAAY,CAACJ,GAAG,CAAC;IAE/CV,MAAM,CAACe,aAAa,CAACZ,IAAI,EAAEU,IAAI,CAAC;EAClC,CAAC,CACF;EAED,IAAI,CAACb,MAAM,CAACG,IAAI,GAAGF,MAAM,CAACe,IAAI,CAAChB,MAAM,CAAC;EAEtC,IAAIP,aAAa,CAACK,EAAE,CAAC,EAAE;IACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;EAC3B;EAEA,OAAO,IAAI;AACb;AAEA,gBAAe,OAAO;EACpBkB,IAAI,EAAEtB,MAAM;EACZuB,MAAM,EAAEvB;AACV,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-flip/index.d.ts b/node_modules/@jimp/plugin-flip/index.d.ts new file mode 100644 index 00000000..3f1efd66 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/index.d.ts @@ -0,0 +1,12 @@ +import { ImageCallback } from "@jimp/core"; + +interface Flip { + flip(horizontal: boolean, vertical: boolean, cb?: ImageCallback): this; + mirror( + horizontal: boolean, + vertical: boolean, + cb?: ImageCallback + ): this; +} + +export default function (): Flip; diff --git a/node_modules/@jimp/plugin-flip/package.json b/node_modules/@jimp/plugin-flip/package.json new file mode 100644 index 00000000..21e4c468 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/package.json @@ -0,0 +1,31 @@ +{ + "name": "@jimp/plugin-flip", + "version": "0.22.12", + "description": "flip an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module --recursive test", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-rotate": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-flip/src/index.js b/node_modules/@jimp/plugin-flip/src/index.js new file mode 100644 index 00000000..01064ac1 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/src/index.js @@ -0,0 +1,46 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Flip the image horizontally + * @param {boolean} horizontal a Boolean, if true the image will be flipped horizontally + * @param {boolean} vertical a Boolean, if true the image will be flipped vertically + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +function flipFn(horizontal, vertical, cb) { + if (typeof horizontal !== "boolean" || typeof vertical !== "boolean") + return throwError.call( + this, + "horizontal and vertical must be Booleans", + cb + ); + + const bitmap = Buffer.alloc(this.bitmap.data.length); + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + const _x = horizontal ? this.bitmap.width - 1 - x : x; + const _y = vertical ? this.bitmap.height - 1 - y : y; + const _idx = (this.bitmap.width * _y + _x) << 2; + const data = this.bitmap.data.readUInt32BE(idx); + + bitmap.writeUInt32BE(data, _idx); + } + ); + + this.bitmap.data = Buffer.from(bitmap); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; +} + +export default () => ({ + flip: flipFn, + mirror: flipFn, +}); diff --git a/node_modules/@jimp/plugin-flip/test/flipping.test.js b/node_modules/@jimp/plugin-flip/test/flipping.test.js new file mode 100644 index 00000000..6866acf6 --- /dev/null +++ b/node_modules/@jimp/plugin-flip/test/flipping.test.js @@ -0,0 +1,97 @@ +import { Jimp, mkJGD } from "@jimp/test-utils"; + +import configure from "@jimp/custom"; + +import flip from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [flip] }, Jimp); + +describe("Flipping plugin", () => { + it("can flip horizontally", async () => { + const src = await jimp.read( + mkJGD( + "AAAABBBB", + "AAABAAAB", + "ABABABAB", + "CCCCCCCC", + "CCCCCCCC", + "CCCCCCCC", + "AACCCCAA" + ) + ); + + const result = src.flip(true, false); + + expectToBeJGD( + result.getJGDSync(), + mkJGD( + "BBBBAAAA", + "BAAABAAA", + "BABABABA", + "CCCCCCCC", + "CCCCCCCC", + "CCCCCCCC", + "AACCCCAA" + ) + ); + }); + + it("can flip vertically", async () => { + const src = await jimp.read( + mkJGD( + "AAAABBBB", + "AAABAAAB", + "ABABABAB", + "CCCCCCCC", + "CCCCCCCC", + "CCCCCCCC", + "AACCCCAA" + ) + ); + + const result = src.flip(false, true); + + expectToBeJGD( + result.getJGDSync(), + mkJGD( + "AACCCCAA", + "CCCCCCCC", + "CCCCCCCC", + "CCCCCCCC", + "ABABABAB", + "AAABAAAB", + "AAAABBBB" + ) + ); + }); + + it("can flip both horizontally and vertically at once", async () => { + const src = await jimp.read( + mkJGD( + "AAAABBBB", + "AAABAAAB", + "ABABABAB", + "CCCCCCCC", + "CCCCCCCC", + "CCCCCCCC", + "AACCCCAA" + ) + ); + + const result = src.flip(true, true); + + expectToBeJGD( + result.getJGDSync(), + mkJGD( + "AACCCCAA", + "CCCCCCCC", + "CCCCCCCC", + "CCCCCCCC", + "BABABABA", + "BAAABAAA", + "BBBBAAAA" + ) + ); + }); +}); diff --git a/node_modules/@jimp/plugin-gaussian/CHANGELOG.md b/node_modules/@jimp/plugin-gaussian/CHANGELOG.md new file mode 100644 index 00000000..8d029143 --- /dev/null +++ b/node_modules/@jimp/plugin-gaussian/CHANGELOG.md @@ -0,0 +1,71 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-gaussian/LICENSE b/node_modules/@jimp/plugin-gaussian/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-gaussian/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-gaussian/README.md b/node_modules/@jimp/plugin-gaussian/README.md new file mode 100644 index 00000000..0f15ca98 --- /dev/null +++ b/node_modules/@jimp/plugin-gaussian/README.md @@ -0,0 +1,25 @@ +
+ +

@jimp/plugin-gaussian

+

Gaussian blur an image.

+
+ +Applies a true Gaussian blur to the image (warning: this is VERY slow) + +## Usage + +- @param {number} r the pixel radius of the blur +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.gaussian(15); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-gaussian/es/index.js b/node_modules/@jimp/plugin-gaussian/es/index.js new file mode 100644 index 00000000..06ea20c5 --- /dev/null +++ b/node_modules/@jimp/plugin-gaussian/es/index.js @@ -0,0 +1,63 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Applies a true Gaussian blur to the image (warning: this is VERY slow) + * @param {number} r the pixel radius of the blur + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + gaussian(r, cb) { + // http://blog.ivank.net/fastest-gaussian-blur.html + if (typeof r !== "number") { + return throwError.call(this, "r must be a number", cb); + } + if (r < 1) { + return throwError.call(this, "r must be greater than 0", cb); + } + const rs = Math.ceil(r * 2.57); // significant radius + const range = rs * 2 + 1; + const rr2 = r * r * 2; + const rr2pi = rr2 * Math.PI; + const weights = []; + for (let y = 0; y < range; y++) { + weights[y] = []; + for (let x = 0; x < range; x++) { + const dsq = (x - rs) ** 2 + (y - rs) ** 2; + weights[y][x] = Math.exp(-dsq / rr2) / rr2pi; + } + } + for (let y = 0; y < this.bitmap.height; y++) { + for (let x = 0; x < this.bitmap.width; x++) { + let red = 0; + let green = 0; + let blue = 0; + let alpha = 0; + let wsum = 0; + for (let iy = 0; iy < range; iy++) { + for (let ix = 0; ix < range; ix++) { + const x1 = Math.min(this.bitmap.width - 1, Math.max(0, ix + x - rs)); + const y1 = Math.min(this.bitmap.height - 1, Math.max(0, iy + y - rs)); + const weight = weights[iy][ix]; + const idx = y1 * this.bitmap.width + x1 << 2; + red += this.bitmap.data[idx] * weight; + green += this.bitmap.data[idx + 1] * weight; + blue += this.bitmap.data[idx + 2] * weight; + alpha += this.bitmap.data[idx + 3] * weight; + wsum += weight; + } + const idx = y * this.bitmap.width + x << 2; + this.bitmap.data[idx] = Math.round(red / wsum); + this.bitmap.data[idx + 1] = Math.round(green / wsum); + this.bitmap.data[idx + 2] = Math.round(blue / wsum); + this.bitmap.data[idx + 3] = Math.round(alpha / wsum); + } + } + } + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-gaussian/es/index.js.map b/node_modules/@jimp/plugin-gaussian/es/index.js.map new file mode 100644 index 00000000..00b7b0f8 --- /dev/null +++ b/node_modules/@jimp/plugin-gaussian/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","gaussian","r","cb","call","rs","Math","ceil","range","rr2","rr2pi","PI","weights","y","x","dsq","exp","bitmap","height","width","red","green","blue","alpha","wsum","iy","ix","x1","min","max","y1","weight","idx","data","round"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Applies a true Gaussian blur to the image (warning: this is VERY slow)\n * @param {number} r the pixel radius of the blur\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n gaussian(r, cb) {\n // http://blog.ivank.net/fastest-gaussian-blur.html\n if (typeof r !== \"number\") {\n return throwError.call(this, \"r must be a number\", cb);\n }\n\n if (r < 1) {\n return throwError.call(this, \"r must be greater than 0\", cb);\n }\n\n const rs = Math.ceil(r * 2.57); // significant radius\n const range = rs * 2 + 1;\n const rr2 = r * r * 2;\n const rr2pi = rr2 * Math.PI;\n\n const weights = [];\n\n for (let y = 0; y < range; y++) {\n weights[y] = [];\n for (let x = 0; x < range; x++) {\n const dsq = (x - rs) ** 2 + (y - rs) ** 2;\n weights[y][x] = Math.exp(-dsq / rr2) / rr2pi;\n }\n }\n\n for (let y = 0; y < this.bitmap.height; y++) {\n for (let x = 0; x < this.bitmap.width; x++) {\n let red = 0;\n let green = 0;\n let blue = 0;\n let alpha = 0;\n let wsum = 0;\n\n for (let iy = 0; iy < range; iy++) {\n for (let ix = 0; ix < range; ix++) {\n const x1 = Math.min(\n this.bitmap.width - 1,\n Math.max(0, ix + x - rs)\n );\n const y1 = Math.min(\n this.bitmap.height - 1,\n Math.max(0, iy + y - rs)\n );\n const weight = weights[iy][ix];\n const idx = (y1 * this.bitmap.width + x1) << 2;\n\n red += this.bitmap.data[idx] * weight;\n green += this.bitmap.data[idx + 1] * weight;\n blue += this.bitmap.data[idx + 2] * weight;\n alpha += this.bitmap.data[idx + 3] * weight;\n wsum += weight;\n }\n\n const idx = (y * this.bitmap.width + x) << 2;\n\n this.bitmap.data[idx] = Math.round(red / wsum);\n this.bitmap.data[idx + 1] = Math.round(green / wsum);\n this.bitmap.data[idx + 2] = Math.round(blue / wsum);\n this.bitmap.data[idx + 3] = Math.round(alpha / wsum);\n }\n }\n }\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;;AAEvD;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe,OAAO;EACpBC,QAAQ,CAACC,CAAC,EAAEC,EAAE,EAAE;IACd;IACA,IAAI,OAAOD,CAAC,KAAK,QAAQ,EAAE;MACzB,OAAOF,UAAU,CAACI,IAAI,CAAC,IAAI,EAAE,oBAAoB,EAAED,EAAE,CAAC;IACxD;IAEA,IAAID,CAAC,GAAG,CAAC,EAAE;MACT,OAAOF,UAAU,CAACI,IAAI,CAAC,IAAI,EAAE,0BAA0B,EAAED,EAAE,CAAC;IAC9D;IAEA,MAAME,EAAE,GAAGC,IAAI,CAACC,IAAI,CAACL,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IACh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AAI,CAAC4B,KAAK,CAACb,KAAK,GAAGG,IAAI,CAAC;UACpD,IAAI,CAACP,MAAM,CAACgB,IAAI,CAACD,GAAG,GAAG,CAAC,CAAC,GAAG1B,IAAI,CAAC4B,KAAK,CAACZ,IAAI,GAAGE,IAAI,CAAC;UACnD,IAAI,CAACP,MAAM,CAACgB,IAAI,CAACD,GAAG,GAAG,CAAC,CAAC,GAAG1B,IAAI,CAAC4B,KAAK,CAACX,KAAK,GAAGC,IAAI,CAAC;QACtD;MACF;IACF;IAEA,IAAIzB,aAAa,CAACI,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-gaussian/index.d.ts b/node_modules/@jimp/plugin-gaussian/index.d.ts new file mode 100644 index 00000000..4f9114c9 --- /dev/null +++ b/node_modules/@jimp/plugin-gaussian/index.d.ts @@ -0,0 +1,7 @@ +import { ImageCallback } from "@jimp/core"; + +interface Gaussian { + gaussian(r: number, cb?: ImageCallback): this; +} + +export default function (): Gaussian; diff --git a/node_modules/@jimp/plugin-gaussian/package.json b/node_modules/@jimp/plugin-gaussian/package.json new file mode 100644 index 00000000..507fb389 --- /dev/null +++ b/node_modules/@jimp/plugin-gaussian/package.json @@ -0,0 +1,30 @@ +{ + "name": "@jimp/plugin-gaussian", + "version": "0.22.12", + "description": "gaussian blur an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-gaussian/src/index.js b/node_modules/@jimp/plugin-gaussian/src/index.js new file mode 100644 index 00000000..21528cb6 --- /dev/null +++ b/node_modules/@jimp/plugin-gaussian/src/index.js @@ -0,0 +1,79 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Applies a true Gaussian blur to the image (warning: this is VERY slow) + * @param {number} r the pixel radius of the blur + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + gaussian(r, cb) { + // http://blog.ivank.net/fastest-gaussian-blur.html + if (typeof r !== "number") { + return throwError.call(this, "r must be a number", cb); + } + + if (r < 1) { + return throwError.call(this, "r must be greater than 0", cb); + } + + const rs = Math.ceil(r * 2.57); // significant radius + const range = rs * 2 + 1; + const rr2 = r * r * 2; + const rr2pi = rr2 * Math.PI; + + const weights = []; + + for (let y = 0; y < range; y++) { + weights[y] = []; + for (let x = 0; x < range; x++) { + const dsq = (x - rs) ** 2 + (y - rs) ** 2; + weights[y][x] = Math.exp(-dsq / rr2) / rr2pi; + } + } + + for (let y = 0; y < this.bitmap.height; y++) { + for (let x = 0; x < this.bitmap.width; x++) { + let red = 0; + let green = 0; + let blue = 0; + let alpha = 0; + let wsum = 0; + + for (let iy = 0; iy < range; iy++) { + for (let ix = 0; ix < range; ix++) { + const x1 = Math.min( + this.bitmap.width - 1, + Math.max(0, ix + x - rs) + ); + const y1 = Math.min( + this.bitmap.height - 1, + Math.max(0, iy + y - rs) + ); + const weight = weights[iy][ix]; + const idx = (y1 * this.bitmap.width + x1) << 2; + + red += this.bitmap.data[idx] * weight; + green += this.bitmap.data[idx + 1] * weight; + blue += this.bitmap.data[idx + 2] * weight; + alpha += this.bitmap.data[idx + 3] * weight; + wsum += weight; + } + + const idx = (y * this.bitmap.width + x) << 2; + + this.bitmap.data[idx] = Math.round(red / wsum); + this.bitmap.data[idx + 1] = Math.round(green / wsum); + this.bitmap.data[idx + 2] = Math.round(blue / wsum); + this.bitmap.data[idx + 3] = Math.round(alpha / wsum); + } + } + } + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-invert/CHANGELOG.md b/node_modules/@jimp/plugin-invert/CHANGELOG.md new file mode 100644 index 00000000..8d029143 --- /dev/null +++ b/node_modules/@jimp/plugin-invert/CHANGELOG.md @@ -0,0 +1,71 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-invert/LICENSE b/node_modules/@jimp/plugin-invert/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-invert/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-invert/README.md b/node_modules/@jimp/plugin-invert/README.md new file mode 100644 index 00000000..e201f584 --- /dev/null +++ b/node_modules/@jimp/plugin-invert/README.md @@ -0,0 +1,24 @@ +
+ +

@jimp/plugin-invert

+

Invert an image's colors.

+
+ +Invert an image's colors. + +## Usage + +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.invert(); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-invert/es/index.js b/node_modules/@jimp/plugin-invert/es/index.js new file mode 100644 index 00000000..61bc06c8 --- /dev/null +++ b/node_modules/@jimp/plugin-invert/es/index.js @@ -0,0 +1,21 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Inverts the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + invert(cb) { + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data[idx] = 255 - this.bitmap.data[idx]; + this.bitmap.data[idx + 1] = 255 - this.bitmap.data[idx + 1]; + this.bitmap.data[idx + 2] = 255 - this.bitmap.data[idx + 2]; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-invert/es/index.js.map b/node_modules/@jimp/plugin-invert/es/index.js.map new file mode 100644 index 00000000..a2fba38f --- /dev/null +++ b/node_modules/@jimp/plugin-invert/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","invert","cb","scanQuiet","bitmap","width","height","x","y","idx","data","call"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Inverts the image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n invert(cb) {\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n this.bitmap.data[idx] = 255 - this.bitmap.data[idx];\n this.bitmap.data[idx + 1] = 255 - this.bitmap.data[idx + 1];\n this.bitmap.data[idx + 2] = 255 - this.bitmap.data[idx + 2];\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,aAAa;;AAE3C;AACA;AACA;AACA;AACA;AACA,gBAAe,OAAO;EACpBC,MAAM,CAACC,EAAE,EAAE;IACT,IAAI,CAACC,SAAS,CACZ,CAAC,EACD,CAAC,EACD,IAAI,CAACC,MAAM,CAACC,KAAK,EACjB,IAAI,CAACD,MAAM,CAACE,MAAM,EAClB,UAAUC,CAAC,EAAEC,CAAC,EAAEC,GAAG,EAAE;MACnB,IAAI,CAACL,MAAM,CAACM,IAAI,CAACD,GAAG,CAAC,GAAG,GAAG,GAAG,IAAI,CAACL,MAAM,CAACM,IAAI,CAACD,GAAG,CAAC;MACnD,IAAI,CAACL,MAAM,CAACM,IAAI,CAACD,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,GAAG,IAAI,CAACL,MAAM,CAACM,IAAI,CAACD,GAAG,GAAG,CAAC,CAAC;MAC3D,IAAI,CAACL,MAAM,CAACM,IAAI,CAACD,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,GAAG,IAAI,CAACL,MAAM,CAACM,IAAI,CAACD,GAAG,GAAG,CAAC,CAAC;IAC7D,CAAC,CACF;IAED,IAAIT,aAAa,CAACE,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACS,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-invert/index.d.ts b/node_modules/@jimp/plugin-invert/index.d.ts new file mode 100644 index 00000000..483b5430 --- /dev/null +++ b/node_modules/@jimp/plugin-invert/index.d.ts @@ -0,0 +1,7 @@ +import { ImageCallback } from "@jimp/core"; + +interface Invert { + invert(cb?: ImageCallback): this; +} + +export default function (): Invert; diff --git a/node_modules/@jimp/plugin-invert/package.json b/node_modules/@jimp/plugin-invert/package.json new file mode 100644 index 00000000..09b9fee7 --- /dev/null +++ b/node_modules/@jimp/plugin-invert/package.json @@ -0,0 +1,30 @@ +{ + "name": "@jimp/plugin-invert", + "version": "0.22.12", + "description": "invert an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-invert/src/index.js b/node_modules/@jimp/plugin-invert/src/index.js new file mode 100644 index 00000000..44ad9302 --- /dev/null +++ b/node_modules/@jimp/plugin-invert/src/index.js @@ -0,0 +1,28 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Inverts the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + invert(cb) { + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + this.bitmap.data[idx] = 255 - this.bitmap.data[idx]; + this.bitmap.data[idx + 1] = 255 - this.bitmap.data[idx + 1]; + this.bitmap.data[idx + 2] = 255 - this.bitmap.data[idx + 2]; + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-mask/CHANGELOG.md b/node_modules/@jimp/plugin-mask/CHANGELOG.md new file mode 100644 index 00000000..3d839517 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/CHANGELOG.md @@ -0,0 +1,85 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-mask/LICENSE b/node_modules/@jimp/plugin-mask/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-mask/README.md b/node_modules/@jimp/plugin-mask/README.md new file mode 100644 index 00000000..840ce372 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/README.md @@ -0,0 +1,26 @@ +
+ +

@jimp/plugin-mask

+

mask an image with another image.

+
+ +Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent. + +## Usage + +- @param {Jimp} src the source Jimp instance +- @param {number} x the horizontal position to blit the image +- @param {number} y the vertical position to blit the image +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + const mask = await jimp.read("test/mask.png"); + + image.mask(mask); +} +``` diff --git a/node_modules/@jimp/plugin-mask/es/index.js b/node_modules/@jimp/plugin-mask/es/index.js new file mode 100644 index 00000000..ba52d216 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/es/index.js @@ -0,0 +1,47 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent. + * @param {Jimp} src the source Jimp instance + * @param {number} x the horizontal position to blit the image + * @param {number} y the vertical position to blit the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + mask(src) { + let x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + let y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + let cb = arguments.length > 3 ? arguments[3] : undefined; + if (!(src instanceof this.constructor)) { + return throwError.call(this, "The source must be a Jimp image", cb); + } + if (typeof x !== "number" || typeof y !== "number") { + return throwError.call(this, "x and y must be numbers", cb); + } + + // round input + x = Math.round(x); + y = Math.round(y); + const w = this.bitmap.width; + const h = this.bitmap.height; + const baseImage = this; + src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) { + const destX = x + sx; + const destY = y + sy; + if (destX >= 0 && destY >= 0 && destX < w && destY < h) { + const dstIdx = baseImage.getPixelIndex(destX, destY); + const { + data + } = this.bitmap; + const avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3; + baseImage.bitmap.data[dstIdx + 3] *= avg / 255; + } + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-mask/es/index.js.map b/node_modules/@jimp/plugin-mask/es/index.js.map new file mode 100644 index 00000000..fed87ab8 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","mask","src","x","y","cb","constructor","call","Math","round","w","bitmap","width","h","height","baseImage","scanQuiet","sx","sy","idx","destX","destY","dstIdx","getPixelIndex","data","avg"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent.\n * @param {Jimp} src the source Jimp instance\n * @param {number} x the horizontal position to blit the image\n * @param {number} y the vertical position to blit the image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n mask(src, x = 0, y = 0, cb) {\n if (!(src instanceof this.constructor)) {\n return throwError.call(this, \"The source must be a Jimp image\", cb);\n }\n\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n\n const w = this.bitmap.width;\n const h = this.bitmap.height;\n const baseImage = this;\n\n src.scanQuiet(\n 0,\n 0,\n src.bitmap.width,\n src.bitmap.height,\n function (sx, sy, idx) {\n const destX = x + sx;\n const destY = y + sy;\n\n if (destX >= 0 && destY >= 0 && destX < w && destY < h) {\n const dstIdx = baseImage.getPixelIndex(destX, destY);\n const { data } = this.bitmap;\n const avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3;\n\n baseImage.bitmap.data[dstIdx + 3] *= avg / 255;\n }\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;;AAEvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe,OAAO;EACpBC,IAAI,CAACC,GA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GAAG,CAAC,CAAC,GAAGK,IAAI,CAACL,GAAG,GAAG,CAAC,CAAC,GAAGK,IAAI,CAACL,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC;QAE/DJ,SAAS,CAACJ,MAAM,CAACa,IAAI,CAACF,MAAM,GAAG,CAAC,CAAC,IAAIG,GAAG,GAAG,GAAG;MAChD;IACF,CAAC,CACF;IAED,IAAI1B,aAAa,CAACM,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-mask/index.d.ts b/node_modules/@jimp/plugin-mask/index.d.ts new file mode 100644 index 00000000..8effa592 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/index.d.ts @@ -0,0 +1,7 @@ +import { ImageCallback, Jimp } from "@jimp/core"; + +interface Mask { + mask(src: Jimp, x: number, y: number, cb?: ImageCallback): this; +} + +export default function (): Mask; diff --git a/node_modules/@jimp/plugin-mask/package.json b/node_modules/@jimp/plugin-mask/package.json new file mode 100644 index 00000000..3faf2647 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/package.json @@ -0,0 +1,37 @@ +{ + "name": "@jimp/plugin-mask", + "version": "0.22.12", + "description": "mask an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-mask/src/index.js b/node_modules/@jimp/plugin-mask/src/index.js new file mode 100644 index 00000000..2a6b32d4 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/src/index.js @@ -0,0 +1,54 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent. + * @param {Jimp} src the source Jimp instance + * @param {number} x the horizontal position to blit the image + * @param {number} y the vertical position to blit the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + mask(src, x = 0, y = 0, cb) { + if (!(src instanceof this.constructor)) { + return throwError.call(this, "The source must be a Jimp image", cb); + } + + if (typeof x !== "number" || typeof y !== "number") { + return throwError.call(this, "x and y must be numbers", cb); + } + + // round input + x = Math.round(x); + y = Math.round(y); + + const w = this.bitmap.width; + const h = this.bitmap.height; + const baseImage = this; + + src.scanQuiet( + 0, + 0, + src.bitmap.width, + src.bitmap.height, + function (sx, sy, idx) { + const destX = x + sx; + const destY = y + sy; + + if (destX >= 0 && destY >= 0 && destX < w && destY < h) { + const dstIdx = baseImage.getPixelIndex(destX, destY); + const { data } = this.bitmap; + const avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3; + + baseImage.bitmap.data[dstIdx + 3] *= avg / 255; + } + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-mask/test/mask.test.js b/node_modules/@jimp/plugin-mask/test/mask.test.js new file mode 100644 index 00000000..e63713f6 --- /dev/null +++ b/node_modules/@jimp/plugin-mask/test/mask.test.js @@ -0,0 +1,134 @@ +import { Jimp, mkJGD } from "@jimp/test-utils"; +import configure from "@jimp/custom"; + +import mask from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [mask] }, Jimp); + +describe("Mask", () => { + let imgSrcOpaq; + let imgSrcAlpa; + let maskGrayBig; + let maskGraySmall; + let maskColor; + + before((done) => { + Promise.all([ + jimp.read(mkJGD("▴□▾□■□", "■▴■▾■□", "■□▴□▾□", "■□■▴■▾")), + jimp.read(mkJGD("▴▵▾▿", "▴▵▾▿", "▴▵▾▿")), + jimp.read(mkJGD("048840", "8CFFC8", "8CFFC8", "048840")), + jimp.read(mkJGD("0369", "369C", "69CF")), + jimp.read(mkJGD("▴▴▾▾", "▪▪▰▰", "□□□□")), + ]) + .then((imgs) => { + imgSrcOpaq = imgs[0]; + imgSrcAlpa = imgs[1]; + maskGrayBig = imgs[2]; + maskGraySmall = imgs[3]; + maskColor = imgs[4]; + done(); + }) + .catch(done); + }); + + it("Affect opaque image with a gray mask with the same size", () => { + expectToBeJGD(imgSrcOpaq.clone().mask(maskGrayBig).getJGDSync(), { + width: 6, + height: 4, + data: [ + 0xff000000, 0xffffff44, 0x0000ff88, 0xffffff88, 0x00000044, 0xffffff00, + 0x00000088, 0xff0000cc, 0x000000ff, 0x0000ffff, 0x000000cc, 0xffffff88, + 0x00000088, 0xffffffcc, 0xff0000ff, 0xffffffff, 0x0000ffcc, 0xffffff88, + 0x00000000, 0xffffff44, 0x00000088, 0xff000088, 0x00000044, 0x0000ff00, + ], + }); + }); + + it("Affect opaque image with a gray mask with the same size, blited", () => { + expectToBeJGD(imgSrcOpaq.clone().mask(maskGrayBig, 1, 1).getJGDSync(), { + width: 6, + height: 4, + data: [ + 0xff0000ff, 0xffffffff, 0x0000ffff, 0xffffffff, 0x000000ff, 0xffffffff, + 0x000000ff, 0xff000000, 0x00000044, 0x0000ff88, 0x00000088, 0xffffff44, + 0x000000ff, 0xffffff88, 0xff0000cc, 0xffffffff, 0x0000ffff, 0xffffffcc, + 0x000000ff, 0xffffff88, 0x000000cc, 0xff0000ff, 0x000000ff, 0x0000ffcc, + ], + }); + }); + + it("Affect opaque image with a gray mask with the same size, blited negative", () => { + expectToBeJGD(imgSrcOpaq.clone().mask(maskGrayBig, -1, -1).getJGDSync(), { + width: 6, + height: 4, + data: [ + 0xff0000cc, 0xffffffff, 0x0000ffff, 0xffffffcc, 0x00000088, 0xffffffff, + 0x000000cc, 0xff0000ff, 0x000000ff, 0x0000ffcc, 0x00000088, 0xffffffff, + 0x00000044, 0xffffff88, 0xff000088, 0xffffff44, 0x0000ff00, 0xffffffff, + 0x000000ff, 0xffffffff, 0x000000ff, 0xff0000ff, 0x000000ff, 0x0000ffff, + ], + }); + }); + + it("Affect opaque image with a smaller gray mask", () => { + expectToBeJGD(imgSrcOpaq.clone().mask(maskGraySmall).getJGDSync(), { + width: 6, + height: 4, + data: [ + 0xff000000, 0xffffff33, 0x0000ff66, 0xffffff99, 0x000000ff, 0xffffffff, + 0x00000033, 0xff000066, 0x00000099, 0x0000ffcc, 0x000000ff, 0xffffffff, + 0x00000066, 0xffffff99, 0xff0000cc, 0xffffffff, 0x0000ffff, 0xffffffff, + 0x000000ff, 0xffffffff, 0x000000ff, 0xff0000ff, 0x000000ff, 0x0000ffff, + ], + }); + }); + + it("Affect opaque image with a smaller gray mask, blited", () => { + expectToBeJGD(imgSrcOpaq.clone().mask(maskGraySmall, 1, 1).getJGDSync(), { + width: 6, + height: 4, + data: [ + 0xff0000ff, 0xffffffff, 0x0000ffff, 0xffffffff, 0x000000ff, 0xffffffff, + 0x000000ff, 0xff000000, 0x00000033, 0x0000ff66, 0x00000099, 0xffffffff, + 0x000000ff, 0xffffff33, 0xff000066, 0xffffff99, 0x0000ffcc, 0xffffffff, + 0x000000ff, 0xffffff66, 0x00000099, 0xff0000cc, 0x000000ff, 0x0000ffff, + ], + }); + }); + + it("Affect alpha image with a bigger gray mask", () => { + expectToBeJGD(imgSrcAlpa.clone().mask(maskGrayBig).getJGDSync(), { + width: 4, + height: 3, + data: [ + 0xff000000, 0xff000021, 0x0000ff88, 0x0000ff43, 0xff000088, 0xff000065, + 0x0000ffff, 0x0000ff7f, 0xff000088, 0xff000065, 0x0000ffff, 0x0000ff7f, + ], + }); + }); + + it("Affect alpha image with a bigger gray mask, blited", () => { + expectToBeJGD(imgSrcAlpa.clone().mask(maskGrayBig, -1, -1).getJGDSync(), { + width: 4, + height: 3, + data: [ + 0xff0000cc, 0xff00007f, 0x0000ffff, 0x0000ff65, 0xff0000cc, 0xff00007f, + 0x0000ffff, 0x0000ff65, 0xff000044, 0xff000043, 0x0000ff88, 0x0000ff21, + ], + }); + }); + + it("Affect opaque image with a colored mask", () => { + expectToBeJGD(imgSrcOpaq.clone().mask(maskColor, 1, 1).getJGDSync(), { + width: 6, + height: 4, + data: [ + 0xff0000ff, 0xffffffff, 0x0000ffff, 0xffffffff, 0x000000ff, 0xffffffff, + 0x000000ff, 0xff000055, 0x00000055, 0x0000ff55, 0x00000055, 0xffffffff, + 0x000000ff, 0xffffffaa, 0xff0000aa, 0xffffffaa, 0x0000ffaa, 0xffffffff, + 0x000000ff, 0xffffffff, 0x000000ff, 0xff0000ff, 0x000000ff, 0x0000ffff, + ], + }); + }); +}); diff --git a/node_modules/@jimp/plugin-normalize/CHANGELOG.md b/node_modules/@jimp/plugin-normalize/CHANGELOG.md new file mode 100644 index 00000000..3d839517 --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/CHANGELOG.md @@ -0,0 +1,85 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-normalize/LICENSE b/node_modules/@jimp/plugin-normalize/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-normalize/README.md b/node_modules/@jimp/plugin-normalize/README.md new file mode 100644 index 00000000..19ba914d --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/README.md @@ -0,0 +1,24 @@ +
+ +

@jimp/plugin-normalize

+

Normalize an image's colors.

+
+ +Normalizes an images color by computing a histogram. + +## Usage + +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.normalize(); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-normalize/es/index.js b/node_modules/@jimp/plugin-normalize/es/index.js new file mode 100644 index 00000000..49a86e31 --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/es/index.js @@ -0,0 +1,66 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Get an image's histogram + * @return {object} An object with an array of color occurrence counts for each channel (r,g,b) + */ +function histogram() { + const histogram = { + r: new Array(256).fill(0), + g: new Array(256).fill(0), + b: new Array(256).fill(0) + }; + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, index) { + histogram.r[this.bitmap.data[index + 0]]++; + histogram.g[this.bitmap.data[index + 1]]++; + histogram.b[this.bitmap.data[index + 2]]++; + }); + return histogram; +} + +/** + * Normalize values + * @param {integer} value Pixel channel value. + * @param {integer} min Minimum value for channel + * @param {integer} max Maximum value for channel + * @return {integer} normalized values + */ +const normalize = function (value, min, max) { + return (value - min) * 255 / (max - min); +}; +const getBounds = function (histogramChannel) { + return [histogramChannel.findIndex(value => value > 0), 255 - histogramChannel.slice().reverse().findIndex(value => value > 0)]; +}; + +/** + * Normalizes the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + normalize(cb) { + const h = histogram.call(this); + + // store bounds (minimum and maximum values) + const bounds = { + r: getBounds(h.r), + g: getBounds(h.g), + b: getBounds(h.b) + }; + + // apply value transformations + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + const r = this.bitmap.data[idx + 0]; + const g = this.bitmap.data[idx + 1]; + const b = this.bitmap.data[idx + 2]; + this.bitmap.data[idx + 0] = normalize(r, bounds.r[0], bounds.r[1]); + this.bitmap.data[idx + 1] = normalize(g, bounds.g[0], bounds.g[1]); + this.bitmap.data[idx + 2] = normalize(b, bounds.b[0], bounds.b[1]); + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-normalize/es/index.js.map b/node_modules/@jimp/plugin-normalize/es/index.js.map new file mode 100644 index 00000000..b937f6f4 --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","histogram","r","Array","fill","g","b","scanQuiet","bitmap","width","height","x","y","index","data","normalize","value","min","max","getBounds","histogramChannel","findIndex","slice","reverse","cb","h","call","bounds","idx"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Get an image's histogram\n * @return {object} An object with an array of color occurrence counts for each channel (r,g,b)\n */\nfunction histogram() {\n const histogram = {\n r: new Array(256).fill(0),\n g: new Array(256).fill(0),\n b: new Array(256).fill(0),\n };\n\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, index) {\n histogram.r[this.bitmap.data[index + 0]]++;\n histogram.g[this.bitmap.data[index + 1]]++;\n histogram.b[this.bitmap.data[index + 2]]++;\n }\n );\n\n return histogram;\n}\n\n/**\n * Normalize values\n * @param {integer} value Pixel channel value.\n * @param {integer} min Minimum value for channel\n * @param {integer} max Maximum value for channel\n * @return {integer} normalized values\n */\nconst normalize = function (value, min, max) {\n return ((value - min) * 255) / (max - min);\n};\n\nconst getBounds = function (histogramChannel) {\n return [\n histogramChannel.findIndex((value) => value > 0),\n 255 -\n histogramChannel\n .slice()\n .reverse()\n .findIndex((value) => value > 0),\n ];\n};\n\n/**\n * Normalizes the image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n normalize(cb) {\n const h = histogram.call(this);\n\n // store bounds (minimum and maximum values)\n const bounds = {\n r: getBounds(h.r),\n g: getBounds(h.g),\n b: getBounds(h.b),\n };\n\n // apply value transformations\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n const r = this.bitmap.data[idx + 0];\n const g = this.bitmap.data[idx + 1];\n const b = this.bitmap.data[idx + 2];\n\n this.bitmap.data[idx + 0] = normalize(r, bounds.r[0], bounds.r[1]);\n this.bitmap.data[idx + 1] = normalize(g, bounds.g[0], bounds.g[1]);\n this.bitmap.data[idx + 2] = normalize(b, bounds.b[0], bounds.b[1]);\n }\n );\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,aAAa;;AAE3C;AACA;AACA;AACA;AACA,SAASC,SAAS,GAAG;EACnB,MAAMA,SAAS,GAAG;IAChBC,CAAC,EAAE,IAAIC,KAAK,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC,CAAC,CAAC;IACzBC,CAAC,EAAE,IAAIF,KAAK,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC,CAAC,CAAC;IACzBE,CAAC,EAAE,IAAIH,KAAK,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC,CAAC;EAC1B,CAAC;EAED,IAAI,CAACG,SAAS,CACZ,CAAC,EACD,CAAC,EACD,IAAI,CAACC,MAAM,CAACC,KAAK,EACjB,IAAI,CAACD,MAAM,CAACE,MAAM,EAClB,UAAUC,CAAC,EAAEC,CAAC,EAAEC,KAAK,EAAE;IACrBZ,SAAS,CAACC,CAAC,CAAC,IA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EACjB,IAAI,CAACD,MAAM,CAACE,MAAM,EAClB,UAAUC,CAAC,EAAEC,CAAC,EAAEgB,GAAG,EAAE;MACnB,MAAM1B,CAAC,GAAG,IAAI,CAACM,MAAM,CAACM,IAAI,CAACc,GAAG,GAAG,CAAC,CAAC;MACnC,MAAMvB,CAAC,GAAG,IAAI,CAACG,MAAM,CAACM,IAAI,CAACc,GAAG,GAAG,CAAC,CAAC;MACnC,MAAMtB,CAAC,GAAG,IAAI,CAACE,MAAM,CAACM,IAAI,CAACc,GAAG,GAAG,CAAC,CAAC;MAEnC,IAAI,CAACpB,MAAM,CAACM,IAAI,CAACc,GAAG,GAAG,CAAC,CAAC,GAAGb,SAAS,CAACb,CAAC,EAAEyB,MAAM,CAACzB,CAAC,CAAC,CAAC,CAAC,EAAEyB,MAAM,CAACzB,CAAC,CAAC,CAAC,CAAC,CAAC;MAClE,IAAI,CAACM,MAAM,CAACM,IAAI,CAACc,GAAG,GAAG,CAAC,CAAC,GAAGb,SAAS,CAACV,CAAC,EAAEsB,MAAM,CAACtB,CAAC,CAAC,CAAC,CAAC,EAAEsB,MAAM,CAACtB,CAAC,CAAC,CAAC,CAAC,CAAC;MAClE,IAAI,CAACG,MAAM,CAACM,IAAI,CAACc,GAAG,GAAG,CAAC,CAAC,GAAGb,SAAS,CAACT,CAAC,EAAEqB,MAAM,CAACrB,CAAC,CAAC,CAAC,CAAC,EAAEqB,MAAM,CAACrB,CAAC,CAAC,CAAC,CAAC,CAAC;IACpE,CAAC,CACF;IAED,IAAIN,aAAa,CAACwB,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-normalize/index.d.ts b/node_modules/@jimp/plugin-normalize/index.d.ts new file mode 100644 index 00000000..1ae996dc --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/index.d.ts @@ -0,0 +1,7 @@ +import { ImageCallback } from "@jimp/core"; + +interface Normalize { + normalize(cb?: ImageCallback): this; +} + +export default function (): Normalize; diff --git a/node_modules/@jimp/plugin-normalize/package.json b/node_modules/@jimp/plugin-normalize/package.json new file mode 100644 index 00000000..3ada8c8d --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/package.json @@ -0,0 +1,37 @@ +{ + "name": "@jimp/plugin-normalize", + "version": "0.22.12", + "description": "normalize an image.", + "main": "dist/index.js", + "module": "es/index.js", + "types": "index.d.ts", + "repository": "jimp-dev/jimp", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-normalize/src/index.js b/node_modules/@jimp/plugin-normalize/src/index.js new file mode 100644 index 00000000..57a696ca --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/src/index.js @@ -0,0 +1,90 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Get an image's histogram + * @return {object} An object with an array of color occurrence counts for each channel (r,g,b) + */ +function histogram() { + const histogram = { + r: new Array(256).fill(0), + g: new Array(256).fill(0), + b: new Array(256).fill(0), + }; + + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, index) { + histogram.r[this.bitmap.data[index + 0]]++; + histogram.g[this.bitmap.data[index + 1]]++; + histogram.b[this.bitmap.data[index + 2]]++; + } + ); + + return histogram; +} + +/** + * Normalize values + * @param {integer} value Pixel channel value. + * @param {integer} min Minimum value for channel + * @param {integer} max Maximum value for channel + * @return {integer} normalized values + */ +const normalize = function (value, min, max) { + return ((value - min) * 255) / (max - min); +}; + +const getBounds = function (histogramChannel) { + return [ + histogramChannel.findIndex((value) => value > 0), + 255 - + histogramChannel + .slice() + .reverse() + .findIndex((value) => value > 0), + ]; +}; + +/** + * Normalizes the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + normalize(cb) { + const h = histogram.call(this); + + // store bounds (minimum and maximum values) + const bounds = { + r: getBounds(h.r), + g: getBounds(h.g), + b: getBounds(h.b), + }; + + // apply value transformations + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + const r = this.bitmap.data[idx + 0]; + const g = this.bitmap.data[idx + 1]; + const b = this.bitmap.data[idx + 2]; + + this.bitmap.data[idx + 0] = normalize(r, bounds.r[0], bounds.r[1]); + this.bitmap.data[idx + 1] = normalize(g, bounds.g[0], bounds.g[1]); + this.bitmap.data[idx + 2] = normalize(b, bounds.b[0], bounds.b[1]); + } + ); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-normalize/test/normalize.test.js b/node_modules/@jimp/plugin-normalize/test/normalize.test.js new file mode 100644 index 00000000..2d8a885a --- /dev/null +++ b/node_modules/@jimp/plugin-normalize/test/normalize.test.js @@ -0,0 +1,33 @@ +import { Jimp, mkJGD } from "@jimp/test-utils"; +import configure from "@jimp/custom"; + +import normalize from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [normalize] }, Jimp); + +describe("Normalize", () => { + it("change grayscale image", async () => { + const image = await jimp.read(mkJGD("36▦", "6▦9", "▦9C")); + + expectToBeJGD(image.normalize().getJGDSync(), mkJGD("■5▦", "5▦A", "▦A□")); + }); + + it("change red/blue image", async () => { + const image = await jimp.read({ + width: 3, + height: 2, + data: [ + 0x000000ff, 0x400022ff, 0x40002200, 0x400000ff, 0x000022ff, 0x800055ff, + ], + }); + + expectToBeJGD(image.normalize().getJGDSync(), { + width: 3, + height: 2, + data: [ + 0x000000ff, 0x7f0066ff, 0x7f006600, 0x7f0000ff, 0x000066ff, 0xff00ffff, + ], + }); + }); +}); diff --git a/node_modules/@jimp/plugin-print/CHANGELOG.md b/node_modules/@jimp/plugin-print/CHANGELOG.md new file mode 100644 index 00000000..cb1f398a --- /dev/null +++ b/node_modules/@jimp/plugin-print/CHANGELOG.md @@ -0,0 +1,193 @@ +# v0.22.11 (Fri Feb 23 2024) + +:tada: This release contains work from a new contributor! :tada: + +Thank you, Rob Juurlink ([@kozmoz](https://github.com/kozmoz)), for all your work! + +#### 🚀 Enhancement + +- Add \n support for image.print #865 [#1265](https://github.com/jimp-dev/jimp/pull/1265) (juurr00@juurlink.org [@kozmoz](https://github.com/kozmoz) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 3 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- juurr00 (juurr00@juurlink.org) +- Rob Juurlink ([@kozmoz](https://github.com/kozmoz)) + +--- + +# v0.22.9 (Wed Jul 26 2023) + +:tada: This release contains work from a new contributor! :tada: + +Thank you, Tim O. (macer) ([@gitmacer](https://github.com/gitmacer)), for all your work! + +#### 🚀 Enhancement + +- Add € to extended Fonts [#1249](https://github.com/jimp-dev/jimp/pull/1249) ([@gitmacer](https://github.com/gitmacer)) + +#### Authors: 1 + +- Tim O. (macer) ([@gitmacer](https://github.com/gitmacer)) + +--- + +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.17.6 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- Update ordering of overrides so ReturnType pulls correct typing. [#1077](https://github.com/jimp-dev/jimp/pull/1077) ([@dcbartlett](https://github.com/dcbartlett) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Dennis Bartlett ([@dcbartlett](https://github.com/dcbartlett)) + +--- + +# v0.17.2 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- remove extra bm-font dep [#1134](https://github.com/jimp-dev/jimp/pull/1134) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.17.1 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- use a consistent text layouting algorithm [#1133](https://github.com/jimp-dev/jimp/pull/1133) ([@iliazeus](https://github.com/iliazeus) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Ilia Pozdnyakov ([@iliazeus](https://github.com/iliazeus)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- Update README.md [#1120](https://github.com/jimp-dev/jimp/pull/1120) ([@mfuatnuroglu](https://github.com/mfuatnuroglu)) + +#### ⚠️ Pushed to `main` + +- try this ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- [@mfuatnuroglu](https://github.com/mfuatnuroglu) +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.10.1 (Sun Apr 05 2020) + +#### 📝 Documentation + +- Fix a `loadFont` and case inconsistency of `jimp` [#868](https://github.com/oliver-moran/jimp/pull/868) ([@xinbenlv](https://github.com/xinbenlv)) + +#### Authors: 1 + +- xinbenlv ([@xinbenlv](https://github.com/xinbenlv)) + +--- + +# v0.9.5 (Tue Mar 03 2020) + +#### 🐛 Bug Fix + +- `@jimp/plugin-print` + - Export font type [#838](https://github.com/oliver-moran/jimp/pull/838) ([@DomiR](https://github.com/DomiR)) + +#### 📝 Documentation + +- `@jimp/plugin-print` + - Added ttf2fnt.com to the list [#845](https://github.com/oliver-moran/jimp/pull/845) ([@mbejda](https://github.com/mbejda)) + +#### Authors: 1 + +- Dominique Rau ([@DomiR](https://github.com/DomiR)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-print/LICENSE b/node_modules/@jimp/plugin-print/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-print/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-print/README.md b/node_modules/@jimp/plugin-print/README.md new file mode 100644 index 00000000..4d395c87 --- /dev/null +++ b/node_modules/@jimp/plugin-print/README.md @@ -0,0 +1,173 @@ +
+ +

@jimp/plugin-print

+

Print text on an image.

+
+ +Jimp supports basic typography using BMFont format (.fnt) even ones in different languages! Just find a bitmap font that is suitable [bitmap fonts](https://en.wikipedia.org/wiki/Bitmap_fonts). + +Online tools are also available to convert TTF fonts to BMFont format. They can be used to create color font or sprite packs. + +:star: [ttf2fnt](https://ttf2fnt.com/) + +:star: [Littera](http://kvazars.com/littera/) + +:star: [Hiero](https://github.com/libgdx/libgdx/wiki/Hiero) + +## Included Fonts + +- `Jimp.FONT_SANS_8_BLACK` +- `Jimp.FONT_SANS_10_BLACK` +- `Jimp.FONT_SANS_12_BLACK` +- `Jimp.FONT_SANS_14_BLACK` +- `Jimp.FONT_SANS_16_BLACK` +- `Jimp.FONT_SANS_32_BLACK` +- `Jimp.FONT_SANS_64_BLACK` +- `Jimp.FONT_SANS_128_BLACK` +- `Jimp.FONT_SANS_8_WHITE` +- `Jimp.FONT_SANS_16_WHITE` +- `Jimp.FONT_SANS_32_WHITE` +- `Jimp.FONT_SANS_64_WHITE` +- `Jimp.FONT_SANS_128_WHITE` + +## loadFont + +Loads a bitmap font from a file + +- @param {string} file the file path of a .fnt file +- @param {function(Error, Jimp)} cb (optional) a function to call when the font is loaded +- @returns {Promise} a promise + +```js +import Jimp from "jimp"; + +async function main() { + const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK); +} + +main(); +``` + +## print + +Draws a text on a image on a given boundary + +- @param {Jimp} font a bitmap font loaded from `Jimp.loadFont` command +- @param {number} x the x position to start drawing the text +- @param {number} y the y position to start drawing the text +- @param {string} text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`) +- @param {number} maxWidth (optional) the boundary width to draw in +- @param {number} maxHeight (optional) the boundary height to draw in +- @param {function(Error, Jimp)} cb (optional) a function to call when the text is written + +```js +import Jimp from "jimp"; + +async function main() { + const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK); + const image = await Jimp.read(1000, 1000, 0x0000ffff); + + image.print(font, 10, 10, "Hello World!"); +} + +main(); +``` + +### Alignment + +Alignment modes are supported by replacing the `str` argument with an object containing `text`, `alignmentX` and `alignmentY`. `alignmentX` defaults to `Jimp.HORIZONTAL_ALIGN_LEFT` and `alignmentY` defaults to `Jimp.VERTICAL_ALIGN_TOP`. + +You can align text using the following constants. + +```js +Jimp.HORIZONTAL_ALIGN_LEFT; +Jimp.HORIZONTAL_ALIGN_CENTER; +Jimp.HORIZONTAL_ALIGN_RIGHT; + +Jimp.VERTICAL_ALIGN_TOP; +Jimp.VERTICAL_ALIGN_MIDDLE; +Jimp.VERTICAL_ALIGN_BOTTOM; +``` + +Default align modes for `image.print` are: + +```js +{ + alignmentX: Jimp.HORIZONTAL_ALIGN_LEFT, + alignmentY: Jimp.VERTICAL_ALIGN_TOP +} +``` + +```js +const font = await Jimp.loadFont(pathOrURL); + +// prints 'Hello world!' on an image, middle and center-aligned +image.print( + font, + x, + y, + { + text: "Hello world!", + alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, + alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, + }, + maxWidth, + maxHeight +); +``` + +**Note**: although `maxWidth` and `maxHeight` parameters are optional to `print()`, they are needed to correctly align the text using the requested alignment mode. + +#### Staggering Text + +If you need to stagger text position along the x or y-axis the print method also returns the final coordinates as an argument to the callback. + +```js +const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK); + +image.print( + font, + 10, + 10, + "Hello world that wraps!", + 50, + (err, image, { x, y }) => { + image.print(font, x, y + 20, "More text on another line", 50); + } +); +``` + +## measureText + +Measure how wide a piece of text will be. + +```js +import Jimp from "jimp"; + +async function main() { + const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK); + const image = await Jimp.read(1000, 1000, 0x0000ffff); + + Jimp.measureText(font, "Hello World!"); +} + +main(); +``` + +## measureTextHeight + +Measure how tall a piece of text will be. + +```js +import Jimp from "jimp"; + +async function main() { + const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK); + const image = await Jimp.read(1000, 1000, 0x0000ffff); + + Jimp.measureTextHeight(font, "Hello World!", 100); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-print/es/index.js b/node_modules/@jimp/plugin-print/es/index.js new file mode 100644 index 00000000..fe798370 --- /dev/null +++ b/node_modules/@jimp/plugin-print/es/index.js @@ -0,0 +1,179 @@ +import Path from "path"; +import bMFont from "load-bmfont"; +import { isNodePattern, throwError } from "@jimp/utils"; +import { measureText, measureTextHeight, splitLines } from "./measure-text"; +function xOffsetBasedOnAlignment(constants, font, line, maxWidth, alignment) { + if (alignment === constants.HORIZONTAL_ALIGN_LEFT) { + return 0; + } + if (alignment === constants.HORIZONTAL_ALIGN_CENTER) { + return (maxWidth - measureText(font, line)) / 2; + } + return maxWidth - measureText(font, line); +} +function drawCharacter(image, font, x, y, char) { + if (char.width > 0 && char.height > 0) { + const characterPage = font.pages[char.page]; + image.blit(characterPage, x + char.xoffset, y + char.yoffset, char.x, char.y, char.width, char.height); + } + return image; +} +function printText(font, x, y, text, defaultCharWidth) { + for (let i = 0; i < text.length; i++) { + let char; + if (font.chars[text[i]]) { + char = text[i]; + } else if (/\s/.test(text[i])) { + char = ""; + } else { + char = "?"; + } + const fontChar = font.chars[char] || {}; + const fontKerning = font.kernings[char]; + drawCharacter(this, font, x, y, fontChar || {}); + const kerning = fontKerning && fontKerning[text[i + 1]] ? fontKerning[text[i + 1]] : 0; + x += kerning + (fontChar.xadvance || defaultCharWidth); + } +} +function loadPages(Jimp, dir, pages) { + const newPages = pages.map(page => { + return Jimp.read(dir + "/" + page); + }); + return Promise.all(newPages); +} +const dir = process.env.DIRNAME || `${__dirname}/../`; +export default (() => ({ + constants: { + measureText, + measureTextHeight, + FONT_SANS_8_BLACK: Path.join(dir, "fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt"), + FONT_SANS_10_BLACK: Path.join(dir, "fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt"), + FONT_SANS_12_BLACK: Path.join(dir, "fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt"), + FONT_SANS_14_BLACK: Path.join(dir, "fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt"), + FONT_SANS_16_BLACK: Path.join(dir, "fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt"), + FONT_SANS_32_BLACK: Path.join(dir, "fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt"), + FONT_SANS_64_BLACK: Path.join(dir, "fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt"), + FONT_SANS_128_BLACK: Path.join(dir, "fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt"), + FONT_SANS_8_WHITE: Path.join(dir, "fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt"), + FONT_SANS_16_WHITE: Path.join(dir, "fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt"), + FONT_SANS_32_WHITE: Path.join(dir, "fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt"), + FONT_SANS_64_WHITE: Path.join(dir, "fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt"), + FONT_SANS_128_WHITE: Path.join(dir, "fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt"), + /** + * Loads a bitmap font from a file + * @param {string} file the file path of a .fnt file + * @param {function(Error, Jimp)} cb (optional) a function to call when the font is loaded + * @returns {Promise} a promise + */ + loadFont(file, cb) { + if (typeof file !== "string") return throwError.call(this, "file must be a string", cb); + return new Promise((resolve, reject) => { + cb = cb || function (err, font) { + if (err) reject(err);else resolve(font); + }; + bMFont(file, (err, font) => { + const chars = {}; + const kernings = {}; + if (err) { + return throwError.call(this, err, cb); + } + for (let i = 0; i < font.chars.length; i++) { + chars[String.fromCharCode(font.chars[i].id)] = font.chars[i]; + } + for (let i = 0; i < font.kernings.length; i++) { + const firstString = String.fromCharCode(font.kernings[i].first); + kernings[firstString] = kernings[firstString] || {}; + kernings[firstString][String.fromCharCode(font.kernings[i].second)] = font.kernings[i].amount; + } + loadPages(this, Path.dirname(file), font.pages).then(pages => { + cb(null, { + chars, + kernings, + pages, + common: font.common, + info: font.info + }); + }); + }); + }); + } + }, + class: { + /** + * Draws a text on a image on a given boundary + * @param {Jimp} font a bitmap font loaded from `Jimp.loadFont` command + * @param {number} x the x position to start drawing the text + * @param {number} y the y position to start drawing the text + * @param {any} text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`) + * @param {number} maxWidth (optional) the boundary width to draw in + * @param {number} maxHeight (optional) the boundary height to draw in + * @param {function(Error, Jimp)} cb (optional) a function to call when the text is written + * @returns {Jimp} this for chaining of methods + */ + print(font, x, y, text, maxWidth, maxHeight, cb) { + if (typeof maxWidth === "function" && typeof cb === "undefined") { + cb = maxWidth; + maxWidth = Infinity; + } + if (typeof maxWidth === "undefined") { + maxWidth = Infinity; + } + if (typeof maxHeight === "function" && typeof cb === "undefined") { + cb = maxHeight; + maxHeight = Infinity; + } + if (typeof maxHeight === "undefined") { + maxHeight = Infinity; + } + if (typeof font !== "object") { + return throwError.call(this, "font must be a Jimp loadFont", cb); + } + if (typeof x !== "number" || typeof y !== "number" || typeof maxWidth !== "number") { + return throwError.call(this, "x, y and maxWidth must be numbers", cb); + } + if (typeof maxWidth !== "number") { + return throwError.call(this, "maxWidth must be a number", cb); + } + if (typeof maxHeight !== "number") { + return throwError.call(this, "maxHeight must be a number", cb); + } + let alignmentX; + let alignmentY; + if (typeof text === "object" && text.text !== null && text.text !== undefined) { + alignmentX = text.alignmentX || this.constructor.HORIZONTAL_ALIGN_LEFT; + alignmentY = text.alignmentY || this.constructor.VERTICAL_ALIGN_TOP; + ({ + text + } = text); + } else { + alignmentX = this.constructor.HORIZONTAL_ALIGN_LEFT; + alignmentY = this.constructor.VERTICAL_ALIGN_TOP; + text = text.toString(); + } + if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_BOTTOM) { + y += maxHeight - measureTextHeight(font, text, maxWidth); + } else if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_MIDDLE) { + y += maxHeight / 2 - measureTextHeight(font, text, maxWidth) / 2; + } + const defaultCharWidth = Object.entries(font.chars)[0][1].xadvance; + const { + lines, + longestLine + } = splitLines(font, text, maxWidth); + lines.forEach(line => { + const lineString = line.join(" "); + const alignmentWidth = xOffsetBasedOnAlignment(this.constructor, font, lineString, maxWidth, alignmentX); + printText.call(this, font, x + alignmentWidth, y, lineString, defaultCharWidth); + y += font.common.lineHeight; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this, { + x: x + longestLine, + y + }); + } + return this; + } + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/es/index.js.map b/node_modules/@jimp/plugin-print/es/index.js.map new file mode 100644 index 00000000..c76733f4 --- /dev/null +++ b/node_modules/@jimp/plugin-print/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["Path","bMFont","isNodePattern","throwError","measureText","measureTextHeight","splitLines","xOffsetBasedOnAlignment","constants","font","line","maxWidth","alignment","HORIZONTAL_ALIGN_LEFT","HORIZONTAL_ALIGN_CENTER","drawCharacter","image","x","y","char","width","height","characterPage","pages","page","blit","xoffset","yoffset","printText","text","defaultCharWidth","i","length","chars","test","fontChar","fontKerning","kernings","kerning","xadvance","loadPages","Jimp","dir","newPages","map","read","Promise","all","process","env","DIRNAME","__dirname","FONT_SANS_8_BLACK","join","FONT_SANS_10_BLACK","FONT_SANS_12_BLACK","FONT_SANS_14_BLACK","FONT_SANS_16_BLACK","FONT_SANS_32_BLACK","FONT_SANS_64_BLACK","FONT_SANS_128_BLACK","FONT_SANS_8_WHITE","FONT_SANS_16_WHITE","FONT_SANS_32_WHITE","FONT_SANS_64_WHITE","FONT_SANS_128_WHITE","loadFont","file","cb","call","resolve","reject","err","String","fromCharCode","id","firstString","first","second","amount","dirname","then","common","info","class","print","maxHeight","Infinity","alignmentX","alignmentY","undefined","constructor","VERTICAL_ALIGN_TOP","toString","VERTICAL_ALIGN_BOTTOM","VERTICAL_ALIGN_MIDDLE","Object","entries","lines","longestLine","forEach","lineString","alignmentWidth","lineHeight"],"sources":["../src/index.js"],"sourcesContent":["import Path from \"path\";\nimport bMFont from \"load-bmfont\";\nimport { isNodePattern, throwError } from \"@jimp/utils\";\nimport { measureText, measureTextHeight, splitLines } from \"./measure-text\";\n\nfunction xOffsetBasedOnAlignment(constants, font, line, maxWidth, alignment) {\n if (alignment === constants.HORIZONTAL_ALIGN_LEFT) {\n return 0;\n }\n\n if (alignment === constants.HORIZONTAL_ALIGN_CENTER) {\n return (maxWidth - measureText(font, line)) / 2;\n }\n\n return maxWidth - measureText(font, line);\n}\n\nfunction drawCharacter(image, font, x, y, char) {\n if (char.width > 0 && char.height > 0) {\n const characterPage = font.pages[char.page];\n\n image.blit(\n characterPage,\n x + char.xoffset,\n y + char.yoffset,\n char.x,\n char.y,\n char.width,\n char.height\n );\n }\n\n return image;\n}\n\nfunction printText(font, x, y, text, defaultCharWidth) {\n for (let i = 0; i < text.length; i++) {\n let char;\n\n if (font.chars[text[i]]) {\n char = text[i];\n } else if (/\\s/.test(text[i])) {\n char = \"\";\n } else {\n char = \"?\";\n }\n\n const fontChar = font.chars[char] || {};\n const fontKerning = font.kernings[char];\n\n drawCharacter(this, font, x, y, fontChar || {});\n\n const kerning =\n fontKerning && fontKerning[text[i + 1]] ? fontKerning[text[i + 1]] : 0;\n\n x += kerning + (fontChar.xadvance || defaultCharWidth);\n }\n}\n\nfunction loadPages(Jimp, dir, pages) {\n const newPages = pages.map((page) => {\n return Jimp.read(dir + \"/\" + page);\n });\n\n return Promise.all(newPages);\n}\n\nconst dir = process.env.DIRNAME || `${__dirname}/../`;\n\nexport default () => ({\n constants: {\n measureText,\n measureTextHeight,\n FONT_SANS_8_BLACK: Path.join(\n dir,\n \"fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt\"\n ),\n FONT_SANS_10_BLACK: Path.join(\n dir,\n \"fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt\"\n ),\n FONT_SANS_12_BLACK: Path.join(\n dir,\n \"fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt\"\n ),\n FONT_SANS_14_BLACK: Path.join(\n dir,\n \"fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt\"\n ),\n FONT_SANS_16_BLACK: Path.join(\n dir,\n \"fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt\"\n ),\n FONT_SANS_32_BLACK: Path.join(\n dir,\n \"fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt\"\n ),\n FONT_SANS_64_BLACK: Path.join(\n dir,\n \"fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt\"\n ),\n FONT_SANS_128_BLACK: Path.join(\n dir,\n \"fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt\"\n ),\n\n FONT_SANS_8_WHITE: Path.join(\n dir,\n \"fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt\"\n ),\n FONT_SANS_16_WHITE: Path.join(\n dir,\n \"fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt\"\n ),\n FONT_SANS_32_WHITE: Path.join(\n dir,\n \"fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt\"\n ),\n FONT_SANS_64_WHITE: Path.join(\n dir,\n \"fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt\"\n ),\n FONT_SANS_128_WHITE: Path.join(\n dir,\n \"fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt\"\n ),\n\n /**\n * Loads a bitmap font from a file\n * @param {string} file the file path of a .fnt file\n * @param {function(Error, Jimp)} cb (optional) a function to call when the font is loaded\n * @returns {Promise} a promise\n */\n loadFont(file, cb) {\n if (typeof file !== \"string\")\n return throwError.call(this, \"file must be a string\", cb);\n\n return new Promise((resolve, reject) => {\n cb =\n cb ||\n function (err, font) {\n if (err) reject(err);\n else resolve(font);\n };\n\n bMFont(file, (err, font) => {\n const chars = {};\n const kernings = {};\n\n if (err) {\n return throwError.call(this, err, cb);\n }\n\n for (let i = 0; i < font.chars.length; i++) {\n chars[String.fromCharCode(font.chars[i].id)] = font.chars[i];\n }\n\n for (let i = 0; i < font.kernings.length; i++) {\n const firstString = String.fromCharCode(font.kernings[i].first);\n kernings[firstString] = kernings[firstString] || {};\n kernings[firstString][\n String.fromCharCode(font.kernings[i].second)\n ] = font.kernings[i].amount;\n }\n\n loadPages(this, Path.dirname(file), font.pages).then((pages) => {\n cb(null, {\n chars,\n kernings,\n pages,\n common: font.common,\n info: font.info,\n });\n });\n });\n });\n },\n },\n\n class: {\n /**\n * Draws a text on a image on a given boundary\n * @param {Jimp} font a bitmap font loaded from `Jimp.loadFont` command\n * @param {number} x the x position to start drawing the text\n * @param {number} y the y position to start drawing the text\n * @param {any} text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`)\n * @param {number} maxWidth (optional) the boundary width to draw in\n * @param {number} maxHeight (optional) the boundary height to draw in\n * @param {function(Error, Jimp)} cb (optional) a function to call when the text is written\n * @returns {Jimp} this for chaining of methods\n */\n print(font, x, y, text, maxWidth, maxHeight, cb) {\n if (typeof maxWidth === \"function\" && typeof cb === \"undefined\") {\n cb = maxWidth;\n maxWidth = Infinity;\n }\n\n if (typeof maxWidth === \"undefined\") {\n maxWidth = Infinity;\n }\n\n if (typeof maxHeight === \"function\" && typeof cb === \"undefined\") {\n cb = maxHeight;\n maxHeight = Infinity;\n }\n\n if (typeof maxHeight === \"undefined\") {\n maxHeight = Infinity;\n }\n\n if (typeof font !== \"object\") {\n return throwError.call(this, \"font must be a Jimp loadFont\", cb);\n }\n\n if (\n typeof x !== \"number\" ||\n typeof y !== \"number\" ||\n typeof maxWidth !== \"number\"\n ) {\n return throwError.call(this, \"x, y and maxWidth must be numbers\", cb);\n }\n\n if (typeof maxWidth !== \"number\") {\n return throwError.call(this, \"maxWidth must be a number\", cb);\n }\n\n if (typeof maxHeight !== \"number\") {\n return throwError.call(this, \"maxHeight must be a number\", cb);\n }\n\n let alignmentX;\n let alignmentY;\n\n if (\n typeof text === \"object\" &&\n text.text !== null &&\n text.text !== undefined\n ) {\n alignmentX = text.alignmentX || this.constructor.HORIZONTAL_ALIGN_LEFT;\n alignmentY = text.alignmentY || this.constructor.VERTICAL_ALIGN_TOP;\n ({ text } = text);\n } else {\n alignmentX = this.constructor.HORIZONTAL_ALIGN_LEFT;\n alignmentY = this.constructor.VERTICAL_ALIGN_TOP;\n text = text.toString();\n }\n\n if (\n maxHeight !== Infinity &&\n alignmentY === this.constructor.VERTICAL_ALIGN_BOTTOM\n ) {\n y += maxHeight - measureTextHeight(font, text, maxWidth);\n } else if (\n maxHeight !== Infinity &&\n alignmentY === this.constructor.VERTICAL_ALIGN_MIDDLE\n ) {\n y += maxHeight / 2 - measureTextHeight(font, text, maxWidth) / 2;\n }\n\n const defaultCharWidth = Object.entries(font.chars)[0][1].xadvance;\n const { lines, longestLine } = splitLines(font, text, maxWidth);\n\n lines.forEach((line) => {\n const lineString = line.join(\" \");\n const alignmentWidth = xOffsetBasedOnAlignment(\n this.constructor,\n font,\n lineString,\n maxWidth,\n alignmentX\n );\n\n printText.call(\n this,\n font,\n x + alignmentWidth,\n y,\n lineString,\n defaultCharWidth\n );\n\n y += font.common.lineHeight;\n });\n\n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CAAC;MAC1D,CAAC,MAAM,IACL2E,SAAS,KAAKC,QAAQ,IACtBE,UAAU,KAAK,IAAI,CAACE,WAAW,CAACI,qBAAqB,EACrD;QACA7E,CAAC,IAAIoE,SAAS,GAAG,CAAC,GAAGjF,iBAAiB,CAACI,IAAI,EAAEoB,IAAI,EAAElB,QAAQ,CAAC,GAAG,CAAC;MAClE;MAEA,MAAMmB,gBAAgB,GAAGkE,MAAM,CAACC,OAAO,CAACxF,IAAI,CAACwB,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAACM,QAAQ;MAClE,MAAM;QAAE2D,KAAK;QAAEC;MAAY,CAAC,GAAG7F,UAAU,CAACG,IAAI,EAAEoB,IAAI,EAAElB,QAAQ,CAAC;MAE/DuF,KAAK,CAACE,OAAO,CAAE1F,IAAI,IAAK;QACtB,MAAM2F,UAAU,GAAG3F,IAAI,CAAC2C,IAAI,CAAC,GAAG,CAAC;QACjC,MAAMiD,cAAc,GAAG/F,uBAAuB,CAC5C,IAAI,CAACoF,WAAW,EAChBlF,IAAI,EACJ4F,UAAU,EACV1F,QAAQ,EACR6E,UAAU,CACX;QAED5D,SAAS,CAACyC,IAAI,CACZ,IAAI,EACJ5D,IAAI,EACJQ,CAAC,GAAGqF,cAAc,EAClBpF,CAAC,EACDmF,UAAU,EACVvE,gBAAgB,CACjB;QAEDZ,CAAC,IAAIT,IAAI,CAACyE,MAAM,CAACqB,UAAU;MAC7B,CAAC,CAAC;MAEF,IAAIrG,aAAa,CAACkE,EAAE,CAAC,EAAE;QACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE;UAAEpD,CAAC,EAAEA,CAAC,GAAGkF,WAAW;UAAEjF;QAAE,CAAC,CAAC;MACtD;MAEA,OAAO,IAAI;IACb;EACF;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/es/measure-text.js b/node_modules/@jimp/plugin-print/es/measure-text.js new file mode 100644 index 00000000..7d493bd4 --- /dev/null +++ b/node_modules/@jimp/plugin-print/es/measure-text.js @@ -0,0 +1,41 @@ +export function measureText(font, text) { + let x = 0; + for (let i = 0; i < text.length; i++) { + if (font.chars[text[i]]) { + const kerning = font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]] ? font.kernings[text[i]][text[i + 1]] : 0; + x += (font.chars[text[i]].xadvance || 0) + kerning; + } + } + return x; +} +export function splitLines(font, text, maxWidth) { + const words = text.replace(/[\r\n]+/g, " \n").split(" "); + const lines = []; + let currentLine = []; + let longestLine = 0; + words.forEach(word => { + const line = [...currentLine, word].join(" "); + const length = measureText(font, line); + if (length <= maxWidth && !word.includes("\n")) { + if (length > longestLine) { + longestLine = length; + } + currentLine.push(word); + } else { + lines.push(currentLine); + currentLine = [word.replace("\n", "")]; + } + }); + lines.push(currentLine); + return { + lines, + longestLine + }; +} +export function measureTextHeight(font, text, maxWidth) { + const { + lines + } = splitLines(font, text, maxWidth); + return lines.length * font.common.lineHeight; +} +//# sourceMappingURL=measure-text.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/es/measure-text.js.map b/node_modules/@jimp/plugin-print/es/measure-text.js.map new file mode 100644 index 00000000..24304226 --- /dev/null +++ b/node_modules/@jimp/plugin-print/es/measure-text.js.map @@ -0,0 +1 @@ +{"version":3,"file":"measure-text.js","names":["measureText","font","text","x","i","length","chars","kerning","kernings","xadvance","splitLines","maxWidth","words","replace","split","lines","currentLine","longestLine","forEach","word","line","join","includes","push","measureTextHeight","common","lineHeight"],"sources":["../src/measure-text.js"],"sourcesContent":["export function measureText(font, text) {\n let x = 0;\n\n for (let i = 0; i < text.length; i++) {\n if (font.chars[text[i]]) {\n const kerning =\n font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]]\n ? font.kernings[text[i]][text[i + 1]]\n : 0;\n\n x += (font.chars[text[i]].xadvance || 0) + kerning;\n }\n }\n\n return x;\n}\n\nexport function splitLines(font, text, maxWidth) {\n const words = text.replace(/[\\r\\n]+/g, \" \\n\").split(\" \");\n\n const lines = [];\n let currentLine = [];\n let longestLine = 0;\n\n words.forEach((word) => {\n const line = [...currentLine, word].join(\" \");\n const length = measureText(font, line);\n\n if (length <= maxWidth && !word.includes(\"\\n\")) {\n if (length > longestLine) {\n longestLine = length;\n }\n\n currentLine.push(word);\n } else {\n lines.push(currentLine);\n currentLine = [word.replace(\"\\n\", \"\")];\n }\n });\n lines.push(currentLine);\n return {\n lines,\n longestLine,\n };\n}\n\nexport function measureTextHeight(font, text, maxWidth) {\n const { lines } = splitLines(font, text, maxWidth);\n\n return lines.length * font.common.lineHeight;\n}\n"],"mappings":"AAAA,OAAO,SAASA,WAAW,CAACC,IAAI,EAAEC,IAAI,EAAE;EACtC,IAAIC,CAAC,GAAG,CAAC;EAET,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGF,IAAI,CAACG,MAAM,EAAED,CAAC,EAAE,EAAE;IACpC,IAAIH,IAAI,CAACK,KAAK,CAACJ,IAAI,CAACE,CAAC,CAAC,CAAC,EAAE;MACvB,MAAMG,OAAO,GACXN,IAAI,CAACO,QAAQ,CAACN,IAAI,CAACE,CAAC,CAAC,CAAC,IAAIH,IAAI,CAACO,QAAQ,CAACN,IAAI,CAACE,CAAC,CAAC,CAAC,CAACF,IAAI,CAACE,CAAC,GAAG,CAAC,CAAC,CAAC,GACzDH,IAAI,CAACO,QAAQ,CAACN,IAAI,CAACE,CAAC,CAAC,CAAC,CAACF,IAAI,CAACE,CAAC,GAAG,CAAC,CAAC,CAAC,GACnC,CAAC;MAEPD,CAAC,IAAI,CAACF,IAAI,CAACK,KAAK,CAACJ,IAAI,CAACE,CAAC,CAAC,CAAC,CAACK,QAAQ,IAAI,CAAC,IAAIF,OAAO;IACpD;EACF;EAEA,OAAOJ,CAAC;AACV;AAEA,OAAO,SAASO,UAAU,CAACT,IAAI,EAAEC,IAAI,EAAES,QAAQ,EAAE;EAC/C,MAAMC,KAAK,GAAGV,IAAI,CAACW,OAAO,CAAC,UAAU,EAAE,KAAK,CAAC,CAACC,KAAK,CAAC,GAAG,CAAC;EAExD,MAAMC,KAAK,GAAG,EAAE;EAChB,IAAIC,WAAW,GAAG,EAAE;EACpB,IAAIC,WAAW,GAAG,CAAC;EAEnBL,KAAK,CAACM,OAAO,CAAEC,IAAI,IAAK;IACtB,MAAMC,IAAI,GAAG,CAAC,GAAGJ,WAAW,EAAEG,IAAI,CAAC,CAACE,IAAI,CAAC,GAAG,CAAC;IAC7C,MAAMhB,MAAM,GAAGL,WAAW,CAACC,IAAI,EAAEmB,IAAI,CAAC;IAEtC,IAAIf,MAAM,IAAIM,QAAQ,IAAI,CAACQ,IAAI,CAACG,QAAQ,CAAC,IAAI,CAAC,EAAE;MAC9C,IAAIjB,MAAM,GAAGY,WAAW,EAAE;QACxBA,WAAW,GAAGZ,MAAM;MACtB;MAEAW,WAAW,CAACO,IAAI,CAACJ,IAAI,CAAC;IACxB,CAAC,MAAM;MACLJ,KAAK,CAACQ,IAAI,CAACP,WAAW,CAAC;MACvBA,WAAW,GAAG,CAACG,IAAI,CAACN,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACxC;EACF,CAAC,CAAC;EACFE,KAAK,CAACQ,IAAI,CAACP,WAAW,CAAC;EACvB,OAAO;IACLD,KAAK;IACLE;EACF,CAAC;AACH;AAEA,OAAO,SAASO,iBAAiB,CAACvB,IAAI,EAAEC,IAAI,EAAES,QAAQ,EAAE;EACtD,MAAM;IAAEI;EAAM,CAAC,GAAGL,UAAU,CAACT,IAAI,EAAEC,IAAI,EAAES,QAAQ,CAAC;EAElD,OAAOI,KAAK,CAACV,MAAM,GAAGJ,IAAI,CAACwB,MAAM,CAACC,UAAU;AAC9C"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/Apache License.txt b/node_modules/@jimp/plugin-print/fonts/open-sans/Apache License.txt new file mode 100644 index 00000000..989e2c59 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/Apache License.txt @@ -0,0 +1,201 @@ +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 [yyyy] [name of copyright owner] + + 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. \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt new file mode 100644 index 00000000..1e4c5db0 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-10-black/open-sans-10-black.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-10-black/open-sans-10-black.png new file mode 100644 index 00000000..a4592981 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-10-black/open-sans-10-black.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt new file mode 100644 index 00000000..5372da2a --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt @@ -0,0 +1,183 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-12-black/open-sans-12-black.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-12-black/open-sans-12-black.png new file mode 100644 index 00000000..b84a9d79 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-12-black/open-sans-12-black.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt new file mode 100644 index 00000000..2bb22b19 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-black/open-sans-128-black.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-black/open-sans-128-black.png new file mode 100644 index 00000000..7e9986e2 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-black/open-sans-128-black.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt new file mode 100644 index 00000000..5e8811e6 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-white/open-sans-128-white.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-white/open-sans-128-white.png new file mode 100644 index 00000000..64b949b1 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-white/open-sans-128-white.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt new file mode 100644 index 00000000..8df67a9b --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-14-black/open-sans-14-black.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-14-black/open-sans-14-black.png new file mode 100644 index 00000000..e66461fe Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-14-black/open-sans-14-black.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt new file mode 100644 index 00000000..afb29970 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-black/open-sans-16-black.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-black/open-sans-16-black.png new file mode 100644 index 00000000..99171bea Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-black/open-sans-16-black.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt new file mode 100644 index 00000000..2b6cbe79 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-white/open-sans-16-white.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-white/open-sans-16-white.png new file mode 100644 index 00000000..ccb1e3c9 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-16-white/open-sans-16-white.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt new file mode 100644 index 00000000..f2d9bf4a --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-black/open-sans-32-black.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-black/open-sans-32-black.png new file mode 100644 index 00000000..50ff1b41 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-black/open-sans-32-black.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt new file mode 100644 index 00000000..35c3584d --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-white/open-sans-32-white.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-white/open-sans-32-white.png new file mode 100644 index 00000000..5900c354 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-32-white/open-sans-32-white.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt new file mode 100644 index 00000000..f4580f3c --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-black/open-sans-64-black.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-black/open-sans-64-black.png new file mode 100644 index 00000000..47af5238 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-black/open-sans-64-black.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt new file mode 100644 index 00000000..dca72ad3 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-white/open-sans-64-white.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-white/open-sans-64-white.png new file mode 100644 index 00000000..de9a88aa Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-64-white/open-sans-64-white.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt new file mode 100644 index 00000000..34f0e621 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-black/open-sans-8-black.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-black/open-sans-8-black.png new file mode 100644 index 00000000..b0579858 Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-black/open-sans-8-black.png differ diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt new file mode 100644 index 00000000..6d437678 --- /dev/null +++ b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-white/open-sans-8-white.png b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-white/open-sans-8-white.png new file mode 100644 index 00000000..435f6d5e Binary files /dev/null and b/node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-8-white/open-sans-8-white.png differ diff --git a/node_modules/@jimp/plugin-print/index.d.ts b/node_modules/@jimp/plugin-print/index.d.ts new file mode 100644 index 00000000..d906616d --- /dev/null +++ b/node_modules/@jimp/plugin-print/index.d.ts @@ -0,0 +1,125 @@ +import { GenericCallback, ImageCallback } from "@jimp/core"; + +export interface FontChar { + id: number; + x: number; + y: number; + width: number; + height: number; + xoffset: number; + yoffset: number; + xadvance: number; + page: number; + chnl: number; +} + +export interface FontInfo { + face: string; + size: number; + bold: number; + italic: number; + charset: string; + unicode: number; + stretchH: number; + smooth: number; + aa: number; + padding: [number, number, number, number]; + spacing: [number, number]; +} + +export interface FontCommon { + lineHeight: number; + base: number; + scaleW: number; + scaleH: number; + pages: number; + packed: number; + alphaChnl: number; + redChnl: number; + greenChnl: number; + blueChnl: number; +} + +export interface Font { + chars: { + [char: string]: FontChar; + }; + kernings: { + [firstString: string]: { + [secondString: string]: number; + }; + }; + pages: string[]; + common: FontCommon; + info: FontInfo; +} + +type PrintableText = + | any + | { + text: string; + alignmentX: number; + alignmentY: number; + }; + +interface PrintClass { + // Text methods + print( + font: Font, + x: number, + y: number, + text: PrintableText, + cb?: ImageCallback + ): this; + print( + font: Font, + x: number, + y: number, + text: PrintableText, + maxWidth?: number, + cb?: ImageCallback + ): this; + print( + font: Font, + x: number, + y: number, + text: PrintableText, + maxWidth?: number, + maxHeight?: number, + cb?: ImageCallback + ): this; +} + +interface Print { + constants: { + measureText(font: Font, text: PrintableText): number; + measureTextHeight( + font: Font, + text: PrintableText, + maxWidth: number + ): number; + + // Font locations + FONT_SANS_8_BLACK: string; + FONT_SANS_10_BLACK: string; + FONT_SANS_12_BLACK: string; + FONT_SANS_14_BLACK: string; + FONT_SANS_16_BLACK: string; + FONT_SANS_32_BLACK: string; + FONT_SANS_64_BLACK: string; + FONT_SANS_128_BLACK: string; + + FONT_SANS_8_WHITE: string; + FONT_SANS_16_WHITE: string; + FONT_SANS_32_WHITE: string; + FONT_SANS_64_WHITE: string; + FONT_SANS_128_WHITE: string; + + loadFont(file: string, cb: GenericCallback): Promise; + loadFont(file: string): Promise; + } + + class: PrintClass; +} + +export default function (): Print; diff --git a/node_modules/@jimp/plugin-print/package.json b/node_modules/@jimp/plugin-print/package.json new file mode 100644 index 00000000..240ff6cb --- /dev/null +++ b/node_modules/@jimp/plugin-print/package.json @@ -0,0 +1,40 @@ +{ + "name": "@jimp/plugin-print", + "version": "0.22.12", + "description": "print an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "load-bmfont": "^1.4.1" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-blit": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/plugin-blit": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-print/src/index.js b/node_modules/@jimp/plugin-print/src/index.js new file mode 100644 index 00000000..baf8a5c4 --- /dev/null +++ b/node_modules/@jimp/plugin-print/src/index.js @@ -0,0 +1,292 @@ +import Path from "path"; +import bMFont from "load-bmfont"; +import { isNodePattern, throwError } from "@jimp/utils"; +import { measureText, measureTextHeight, splitLines } from "./measure-text"; + +function xOffsetBasedOnAlignment(constants, font, line, maxWidth, alignment) { + if (alignment === constants.HORIZONTAL_ALIGN_LEFT) { + return 0; + } + + if (alignment === constants.HORIZONTAL_ALIGN_CENTER) { + return (maxWidth - measureText(font, line)) / 2; + } + + return maxWidth - measureText(font, line); +} + +function drawCharacter(image, font, x, y, char) { + if (char.width > 0 && char.height > 0) { + const characterPage = font.pages[char.page]; + + image.blit( + characterPage, + x + char.xoffset, + y + char.yoffset, + char.x, + char.y, + char.width, + char.height + ); + } + + return image; +} + +function printText(font, x, y, text, defaultCharWidth) { + for (let i = 0; i < text.length; i++) { + let char; + + if (font.chars[text[i]]) { + char = text[i]; + } else if (/\s/.test(text[i])) { + char = ""; + } else { + char = "?"; + } + + const fontChar = font.chars[char] || {}; + const fontKerning = font.kernings[char]; + + drawCharacter(this, font, x, y, fontChar || {}); + + const kerning = + fontKerning && fontKerning[text[i + 1]] ? fontKerning[text[i + 1]] : 0; + + x += kerning + (fontChar.xadvance || defaultCharWidth); + } +} + +function loadPages(Jimp, dir, pages) { + const newPages = pages.map((page) => { + return Jimp.read(dir + "/" + page); + }); + + return Promise.all(newPages); +} + +const dir = process.env.DIRNAME || `${__dirname}/../`; + +export default () => ({ + constants: { + measureText, + measureTextHeight, + FONT_SANS_8_BLACK: Path.join( + dir, + "fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt" + ), + FONT_SANS_10_BLACK: Path.join( + dir, + "fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt" + ), + FONT_SANS_12_BLACK: Path.join( + dir, + "fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt" + ), + FONT_SANS_14_BLACK: Path.join( + dir, + "fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt" + ), + FONT_SANS_16_BLACK: Path.join( + dir, + "fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt" + ), + FONT_SANS_32_BLACK: Path.join( + dir, + "fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt" + ), + FONT_SANS_64_BLACK: Path.join( + dir, + "fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt" + ), + FONT_SANS_128_BLACK: Path.join( + dir, + "fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt" + ), + + FONT_SANS_8_WHITE: Path.join( + dir, + "fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt" + ), + FONT_SANS_16_WHITE: Path.join( + dir, + "fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt" + ), + FONT_SANS_32_WHITE: Path.join( + dir, + "fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt" + ), + FONT_SANS_64_WHITE: Path.join( + dir, + "fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt" + ), + FONT_SANS_128_WHITE: Path.join( + dir, + "fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt" + ), + + /** + * Loads a bitmap font from a file + * @param {string} file the file path of a .fnt file + * @param {function(Error, Jimp)} cb (optional) a function to call when the font is loaded + * @returns {Promise} a promise + */ + loadFont(file, cb) { + if (typeof file !== "string") + return throwError.call(this, "file must be a string", cb); + + return new Promise((resolve, reject) => { + cb = + cb || + function (err, font) { + if (err) reject(err); + else resolve(font); + }; + + bMFont(file, (err, font) => { + const chars = {}; + const kernings = {}; + + if (err) { + return throwError.call(this, err, cb); + } + + for (let i = 0; i < font.chars.length; i++) { + chars[String.fromCharCode(font.chars[i].id)] = font.chars[i]; + } + + for (let i = 0; i < font.kernings.length; i++) { + const firstString = String.fromCharCode(font.kernings[i].first); + kernings[firstString] = kernings[firstString] || {}; + kernings[firstString][ + String.fromCharCode(font.kernings[i].second) + ] = font.kernings[i].amount; + } + + loadPages(this, Path.dirname(file), font.pages).then((pages) => { + cb(null, { + chars, + kernings, + pages, + common: font.common, + info: font.info, + }); + }); + }); + }); + }, + }, + + class: { + /** + * Draws a text on a image on a given boundary + * @param {Jimp} font a bitmap font loaded from `Jimp.loadFont` command + * @param {number} x the x position to start drawing the text + * @param {number} y the y position to start drawing the text + * @param {any} text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`) + * @param {number} maxWidth (optional) the boundary width to draw in + * @param {number} maxHeight (optional) the boundary height to draw in + * @param {function(Error, Jimp)} cb (optional) a function to call when the text is written + * @returns {Jimp} this for chaining of methods + */ + print(font, x, y, text, maxWidth, maxHeight, cb) { + if (typeof maxWidth === "function" && typeof cb === "undefined") { + cb = maxWidth; + maxWidth = Infinity; + } + + if (typeof maxWidth === "undefined") { + maxWidth = Infinity; + } + + if (typeof maxHeight === "function" && typeof cb === "undefined") { + cb = maxHeight; + maxHeight = Infinity; + } + + if (typeof maxHeight === "undefined") { + maxHeight = Infinity; + } + + if (typeof font !== "object") { + return throwError.call(this, "font must be a Jimp loadFont", cb); + } + + if ( + typeof x !== "number" || + typeof y !== "number" || + typeof maxWidth !== "number" + ) { + return throwError.call(this, "x, y and maxWidth must be numbers", cb); + } + + if (typeof maxWidth !== "number") { + return throwError.call(this, "maxWidth must be a number", cb); + } + + if (typeof maxHeight !== "number") { + return throwError.call(this, "maxHeight must be a number", cb); + } + + let alignmentX; + let alignmentY; + + if ( + typeof text === "object" && + text.text !== null && + text.text !== undefined + ) { + alignmentX = text.alignmentX || this.constructor.HORIZONTAL_ALIGN_LEFT; + alignmentY = text.alignmentY || this.constructor.VERTICAL_ALIGN_TOP; + ({ text } = text); + } else { + alignmentX = this.constructor.HORIZONTAL_ALIGN_LEFT; + alignmentY = this.constructor.VERTICAL_ALIGN_TOP; + text = text.toString(); + } + + if ( + maxHeight !== Infinity && + alignmentY === this.constructor.VERTICAL_ALIGN_BOTTOM + ) { + y += maxHeight - measureTextHeight(font, text, maxWidth); + } else if ( + maxHeight !== Infinity && + alignmentY === this.constructor.VERTICAL_ALIGN_MIDDLE + ) { + y += maxHeight / 2 - measureTextHeight(font, text, maxWidth) / 2; + } + + const defaultCharWidth = Object.entries(font.chars)[0][1].xadvance; + const { lines, longestLine } = splitLines(font, text, maxWidth); + + lines.forEach((line) => { + const lineString = line.join(" "); + const alignmentWidth = xOffsetBasedOnAlignment( + this.constructor, + font, + lineString, + maxWidth, + alignmentX + ); + + printText.call( + this, + font, + x + alignmentWidth, + y, + lineString, + defaultCharWidth + ); + + y += font.common.lineHeight; + }); + + if (isNodePattern(cb)) { + cb.call(this, null, this, { x: x + longestLine, y }); + } + + return this; + }, + }, +}); diff --git a/node_modules/@jimp/plugin-print/src/measure-text.js b/node_modules/@jimp/plugin-print/src/measure-text.js new file mode 100644 index 00000000..c1790881 --- /dev/null +++ b/node_modules/@jimp/plugin-print/src/measure-text.js @@ -0,0 +1,51 @@ +export function measureText(font, text) { + let x = 0; + + for (let i = 0; i < text.length; i++) { + if (font.chars[text[i]]) { + const kerning = + font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]] + ? font.kernings[text[i]][text[i + 1]] + : 0; + + x += (font.chars[text[i]].xadvance || 0) + kerning; + } + } + + return x; +} + +export function splitLines(font, text, maxWidth) { + const words = text.replace(/[\r\n]+/g, " \n").split(" "); + + const lines = []; + let currentLine = []; + let longestLine = 0; + + words.forEach((word) => { + const line = [...currentLine, word].join(" "); + const length = measureText(font, line); + + if (length <= maxWidth && !word.includes("\n")) { + if (length > longestLine) { + longestLine = length; + } + + currentLine.push(word); + } else { + lines.push(currentLine); + currentLine = [word.replace("\n", "")]; + } + }); + lines.push(currentLine); + return { + lines, + longestLine, + }; +} + +export function measureTextHeight(font, text, maxWidth) { + const { lines } = splitLines(font, text, maxWidth); + + return lines.length * font.common.lineHeight; +} diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_16_BLACK-positioned.png b/node_modules/@jimp/plugin-print/test/images/SANS_16_BLACK-positioned.png new file mode 100644 index 00000000..be11559a Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_16_BLACK-positioned.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_16_BLACK.png b/node_modules/@jimp/plugin-print/test/images/SANS_16_BLACK.png new file mode 100644 index 00000000..2369ba83 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_16_BLACK.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_16_WHITE.png b/node_modules/@jimp/plugin-print/test/images/SANS_16_WHITE.png new file mode 100644 index 00000000..8b1bd8d3 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_16_WHITE.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_32_BLACK.png b/node_modules/@jimp/plugin-print/test/images/SANS_32_BLACK.png new file mode 100644 index 00000000..2084bb67 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_32_BLACK.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_32_WHITE.png b/node_modules/@jimp/plugin-print/test/images/SANS_32_WHITE.png new file mode 100644 index 00000000..58d3ea29 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_32_WHITE.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_64_BLACK.png b/node_modules/@jimp/plugin-print/test/images/SANS_64_BLACK.png new file mode 100644 index 00000000..a263ab23 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_64_BLACK.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_64_WHITE.png b/node_modules/@jimp/plugin-print/test/images/SANS_64_WHITE.png new file mode 100644 index 00000000..1573052d Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_64_WHITE.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_8_BLACK.png b/node_modules/@jimp/plugin-print/test/images/SANS_8_BLACK.png new file mode 100644 index 00000000..9295ee97 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_8_BLACK.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/SANS_8_WHITE.png b/node_modules/@jimp/plugin-print/test/images/SANS_8_WHITE.png new file mode 100644 index 00000000..df20ee1b Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/SANS_8_WHITE.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/bottom-aligned-y.png b/node_modules/@jimp/plugin-print/test/images/bottom-aligned-y.png new file mode 100644 index 00000000..6298192d Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/bottom-aligned-y.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/bottom-aligned.png b/node_modules/@jimp/plugin-print/test/images/bottom-aligned.png new file mode 100644 index 00000000..ff7a00a1 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/bottom-aligned.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/center-aligned.png b/node_modules/@jimp/plugin-print/test/images/center-aligned.png new file mode 100644 index 00000000..602f576b Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/center-aligned.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/left-aligned.png b/node_modules/@jimp/plugin-print/test/images/left-aligned.png new file mode 100644 index 00000000..5d919cd3 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/left-aligned.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/middle-aligned-y.png b/node_modules/@jimp/plugin-print/test/images/middle-aligned-y.png new file mode 100644 index 00000000..d6eec20b Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/middle-aligned-y.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/middle-aligned.png b/node_modules/@jimp/plugin-print/test/images/middle-aligned.png new file mode 100644 index 00000000..214e23b2 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/middle-aligned.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/print-number.png b/node_modules/@jimp/plugin-print/test/images/print-number.png new file mode 100644 index 00000000..46f01d7c Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/print-number.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/right-aligned.png b/node_modules/@jimp/plugin-print/test/images/right-aligned.png new file mode 100644 index 00000000..77651496 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/right-aligned.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/spacing.png b/node_modules/@jimp/plugin-print/test/images/spacing.png new file mode 100644 index 00000000..f6422e48 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/spacing.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/unknown-char-test.png b/node_modules/@jimp/plugin-print/test/images/unknown-char-test.png new file mode 100644 index 00000000..2ae9ff59 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/unknown-char-test.png differ diff --git a/node_modules/@jimp/plugin-print/test/images/with-newlines.png b/node_modules/@jimp/plugin-print/test/images/with-newlines.png new file mode 100644 index 00000000..8da2d115 Binary files /dev/null and b/node_modules/@jimp/plugin-print/test/images/with-newlines.png differ diff --git a/node_modules/@jimp/plugin-print/test/print.test.js b/node_modules/@jimp/plugin-print/test/print.test.js new file mode 100644 index 00000000..dee02fea --- /dev/null +++ b/node_modules/@jimp/plugin-print/test/print.test.js @@ -0,0 +1,311 @@ +/* eslint key-spacing: ["error", { "align": "value" }] */ + +import { Jimp, getTestDir, hasOwnProp } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import blit from "@jimp/plugin-blit"; +import expect from "@storybook/expect"; + +import print from "../src"; + +const jimp = configure({ plugins: [print, blit] }, Jimp); + +async function createTextImage( + width, + height, + font, + { x = 0, y = 0, text, maxWidth, maxHeight } +) { + const loadedFont = await jimp.loadFont(font); + const image = await Jimp.create(width, height, 0xffffffff); + + return image.print(loadedFont, x, y, text, maxWidth, maxHeight); +} + +describe("Write text over image", function () { + this.timeout(30000); + + const fontDefs = { + SANS_8_BLACK: { w: 28, h: 28, bg: 0xffffffff }, + + SANS_16_BLACK: { w: 54, h: 54, bg: 0xffffffff }, + SANS_32_BLACK: { w: 114, h: 114, bg: 0xffffffff }, + SANS_64_BLACK: { w: 220, h: 220, bg: 0xffffffff }, + + SANS_8_WHITE: { w: 28, h: 28, bg: 0x000000ff }, + + SANS_16_WHITE: { w: 54, h: 54, bg: 0x000000ff }, + SANS_32_WHITE: { w: 114, h: 114, bg: 0x000000ff }, + SANS_64_WHITE: { w: 220, h: 220, bg: 0x000000ff }, + }; + + for (const fontName in fontDefs) + if (hasOwnProp(fontDefs, fontName)) + ((fontName, conf) => { + it("Jimp preset " + fontName + " bitmap font", async () => { + const font = await jimp.loadFont(Jimp["FONT_" + fontName]); + const expected = + getTestDir(__dirname) + "/images/" + fontName + ".png"; + + const expectedImg = await Jimp.read(expected); + const image = await Jimp.create(conf.w, conf.h, conf.bg); + + expect( + image.print(font, 0, 0, "This is only a test.", image.bitmap.width) + .bitmap.data + ).toEqual(expectedImg.bitmap.data); + }); + })(fontName, fontDefs[fontName]); + + it("Jimp preset SANS_16_BLACK bitmap font positioned", async () => { + const font = await jimp.loadFont(Jimp.FONT_SANS_16_BLACK); + const expected = + getTestDir(__dirname) + "/images/SANS_16_BLACK-positioned.png"; + const expectedImg = await Jimp.read(expected); + const image = await Jimp.create("300", "100", 0xff8800ff); + + expect( + image.print(font, 150, 50, "This is only a test.", 100).bitmap.data + ).toEqual(expectedImg.bitmap.data); + }); + + it("Jimp loads font from URL", async () => { + const font = await Jimp.loadFont( + "https://raw.githubusercontent.com/jimp-dev/jimp/main/packages/plugin-print/fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt" + ); + const expected = + getTestDir(__dirname) + "/images/SANS_16_BLACK-positioned.png"; + const expectedImg = await Jimp.read(expected); + const image = await Jimp.create("300", "100", 0xff8800ff); + + expect( + image.print(font, 150, 50, "This is only a test.", 100).bitmap.data + ).toEqual(expectedImg.bitmap.data); + }); + + it("Jimp renders ? for unknown characters", async () => { + const font = await jimp.loadFont(Jimp.FONT_SANS_16_BLACK); + + const expected = getTestDir(__dirname) + "/images/unknown-char-test.png"; + const expectedImg = await Jimp.read(expected); + const image = await Jimp.read("300", "100", 0xff8800ff); + + expect(image.print(font, 0, 0, "ツ ツ ツ", 100).bitmap.data).toEqual( + expectedImg.bitmap.data + ); + }); + + it("Jimp can print numbers too", async () => { + const font = await Jimp.loadFont(Jimp.FONT_SANS_16_BLACK); + + const expected = getTestDir(__dirname) + "/images/print-number.png"; + const expectedImg = await Jimp.read(expected); + const image = await Jimp.read("300", "100", 0xff8800ff); + + expect(image.print(font, 0, 0, 12345678, 100).bitmap.data).toEqual( + expectedImg.bitmap.data + ); + }); + + it("left-align text by default", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/left-aligned.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + text: "This is only a test.", + + maxWidth: 100, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("left-align text by default when passing object", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/left-aligned.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + text: { text: "This is only a test." }, + + maxWidth: 100, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("left-align text when passing object with alignmentX", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/left-aligned.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + text: { + text: "This is only a test.", + + alignmentX: Jimp.HORIZONTAL_ALIGN_LEFT, + }, + maxWidth: 100, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("center-align text when passing object with alignmentX", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/center-aligned.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + text: { + text: "This is only a test.", + + alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, + }, + maxWidth: 100, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("right-align text when passing object with alignmentX", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/right-aligned.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + text: { + text: "This is only a test.", + + alignmentX: Jimp.HORIZONTAL_ALIGN_RIGHT, + }, + maxWidth: 100, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("middle-align text when passing object with alignmentY", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/middle-aligned.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + text: { + text: "This is only a test.", + + alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, + }, + maxWidth: 100, + + maxHeight: 240, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("middle-align text when passing object with alignmentY can offset y", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/middle-aligned-y.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + y: 50, + + text: { + text: "This is only a test.", + + alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, + }, + maxWidth: 100, + + maxHeight: 240, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("bottom-align text when passing object with alignmentY", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/bottom-aligned.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + text: { + text: "This is only a test.", + + alignmentY: Jimp.VERTICAL_ALIGN_BOTTOM, + }, + maxWidth: 100, + + maxHeight: 240, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("bottom-align text when passing object with alignmentY offset y", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/bottom-aligned-y.png" + ); + const textImage = await createTextImage(320, 240, Jimp.FONT_SANS_16_BLACK, { + y: 100, + + text: { + text: "This is only a test.", + + alignmentY: Jimp.VERTICAL_ALIGN_BOTTOM, + }, + maxWidth: 100, + + maxHeight: 100, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("exposes print y position in cb", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/spacing.png" + ); + + const loadedFont = await jimp.loadFont(Jimp.FONT_SANS_16_BLACK); + const image = await Jimp.create(500, 500, 0xffffffff); + + image.print( + loadedFont, + 0, + 0, + "One two three four fix six seven eight nine ten eleven twelve", + 250, + (err, image, { x, y }) => { + image.print( + loadedFont, + x, + y + 50, + "thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty", + 250 + ); + } + ); + + expect(image.bitmap.data).toEqual(expectedImage.bitmap.data); + }); + + it("measureText is consistent with measureTextWidth", async () => { + const font = await jimp.loadFont(Jimp.FONT_SANS_16_BLACK); + + const text = "n n n"; + const width = jimp.measureText(font, text); + const height = jimp.measureTextHeight(font, text, width); + const lineHeight = jimp.measureTextHeight(font, text, Infinity); + + expect(height).toEqual(lineHeight); + }); + + it("text with newlines, default alignment", async () => { + const expectedImage = await Jimp.read( + getTestDir(__dirname) + "/images/with-newlines.png" + ); + + const textImage = await createTextImage(100, 240, Jimp.FONT_SANS_16_BLACK, { + text: "This \nis only \na \ntest.", + + maxWidth: 300, + }); + + expect(textImage.bitmap.data).toEqual(expectedImage.bitmap.data); + }); +}); diff --git a/node_modules/@jimp/plugin-resize/CHANGELOG.md b/node_modules/@jimp/plugin-resize/CHANGELOG.md new file mode 100644 index 00000000..d50c15d9 --- /dev/null +++ b/node_modules/@jimp/plugin-resize/CHANGELOG.md @@ -0,0 +1,114 @@ +# v0.22.5 (Tue Feb 21 2023) + +:tada: This release contains work from a new contributor! :tada: + +Thank you, Charly Poirier ([@charlypoirier](https://github.com/charlypoirier)), for all your work! + +#### 🐛 Bug Fix + +- Fix resizing issue with Jimp.AUTO [#1202](https://github.com/jimp-dev/jimp/pull/1202) ([@charlypoirier](https://github.com/charlypoirier)) + +#### Authors: 1 + +- Charly Poirier ([@charlypoirier](https://github.com/charlypoirier)) + +--- + +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- delete CLI package [#1162](https://github.com/jimp-dev/jimp/pull/1162) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.2 (Sun Feb 05 2023) + +#### 🐛 Bug Fix + +- Change some exports to move towards more ESM compatibility [#1154](https://github.com/jimp-dev/jimp/pull/1154) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 1 + +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-resize/LICENSE b/node_modules/@jimp/plugin-resize/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-resize/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-resize/README.md b/node_modules/@jimp/plugin-resize/README.md new file mode 100644 index 00000000..a74dbdff --- /dev/null +++ b/node_modules/@jimp/plugin-resize/README.md @@ -0,0 +1,61 @@ +
+ +

@jimp/plugin-resize

+

Resize an image.

+
+ +Resizes the image to a set width and height using a 2-pass bilinear algorithm/ + +## Usage + +- @param {number} w the width to resize the image to (or Jimp.AUTO) +- @param {number} h the height to resize the image to (or Jimp.AUTO) +- @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + // Read the image. + const image = await jimp.read("test/image.png"); + + // Resize the image to width 150 and auto height. + await image.resize(150, jimp.AUTO); + + // Save and overwrite the image + await image.writeAsync("test/image.png"); +} + +main(); +``` + +## Auto + +`Jimp.AUTO` can be passes to either the height or width and jimp will scale the image accordingly. `Jimp.AUTO` cannot be both height and width. + +```js +// resize the height to 250 and scale the width accordingly +image.resize(Jimp.AUTO, 250); +// resize the width to 250 and scale the height accordingly +image.resize(250, Jimp.AUTO); +``` + +### Resize modes + +The default resizing algorithm uses a bilinear method. + +Optionally, the following constants can be passed to choose a particular resizing algorithm: + +```js +Jimp.RESIZE_NEAREST_NEIGHBOR; +Jimp.RESIZE_BILINEAR; +Jimp.RESIZE_BICUBIC; +Jimp.RESIZE_HERMITE; +Jimp.RESIZE_BEZIER; +``` + +```js +image.resize(250, 250, Jimp.RESIZE_BEZIER); +``` diff --git a/node_modules/@jimp/plugin-resize/es/index.js b/node_modules/@jimp/plugin-resize/es/index.js new file mode 100644 index 00000000..dd4ecb4c --- /dev/null +++ b/node_modules/@jimp/plugin-resize/es/index.js @@ -0,0 +1,69 @@ +import { throwError, isNodePattern } from "@jimp/utils"; +import Resize from "./modules/resize"; +import Resize2 from "./modules/resize2"; +export default (() => ({ + constants: { + RESIZE_NEAREST_NEIGHBOR: "nearestNeighbor", + RESIZE_BILINEAR: "bilinearInterpolation", + RESIZE_BICUBIC: "bicubicInterpolation", + RESIZE_HERMITE: "hermiteInterpolation", + RESIZE_BEZIER: "bezierInterpolation" + }, + class: { + /** + * Resizes the image to a set width and height using a 2-pass bilinear algorithm + * @param {number} w the width to resize the image to (or Jimp.AUTO) + * @param {number} h the height to resize the image to (or Jimp.AUTO) + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + resize(w, h, mode, cb) { + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + if (w === this.constructor.AUTO && h === this.constructor.AUTO) { + return throwError.call(this, "w and h cannot both be set to auto", cb); + } + if (w === this.constructor.AUTO) { + w = this.bitmap.width * (h / this.bitmap.height); + } + if (h === this.constructor.AUTO) { + h = this.bitmap.height * (w / this.bitmap.width); + } + if (w < 0 || h < 0) { + return throwError.call(this, "w and h must be positive numbers", cb); + } + + // round inputs + w = Math.round(w) || 1; + h = Math.round(h) || 1; + if (typeof Resize2[mode] === "function") { + const dst = { + data: Buffer.alloc(w * h * 4), + width: w, + height: h + }; + Resize2[mode](this.bitmap, dst); + this.bitmap = dst; + } else { + const image = this; + const resize = new Resize(this.bitmap.width, this.bitmap.height, w, h, true, true, buffer => { + image.bitmap.data = Buffer.from(buffer); + image.bitmap.width = w; + image.bitmap.height = h; + }); + resize.resize(this.bitmap.data); + } + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-resize/es/index.js.map b/node_modules/@jimp/plugin-resize/es/index.js.map new file mode 100644 index 00000000..af90280c --- /dev/null +++ b/node_modules/@jimp/plugin-resize/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["throwError","isNodePattern","Resize","Resize2","constants","RESIZE_NEAREST_NEIGHBOR","RESIZE_BILINEAR","RESIZE_BICUBIC","RESIZE_HERMITE","RESIZE_BEZIER","class","resize","w","h","mode","cb","call","constructor","AUTO","bitmap","width","height","Math","round","dst","data","Buffer","alloc","image","buffer","from"],"sources":["../src/index.js"],"sourcesContent":["import { throwError, isNodePattern } from \"@jimp/utils\";\n\nimport Resize from \"./modules/resize\";\nimport Resize2 from \"./modules/resize2\";\n\nexport default () => ({\n constants: {\n RESIZE_NEAREST_NEIGHBOR: \"nearestNeighbor\",\n RESIZE_BILINEAR: \"bilinearInterpolation\",\n RESIZE_BICUBIC: \"bicubicInterpolation\",\n RESIZE_HERMITE: \"hermiteInterpolation\",\n RESIZE_BEZIER: \"bezierInterpolation\",\n },\n\n class: {\n /**\n * Resizes the image to a set width and height using a 2-pass bilinear algorithm\n * @param {number} w the width to resize the image to (or Jimp.AUTO)\n * @param {number} h the height to resize the image to (or Jimp.AUTO)\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n resize(w, h, mode, cb) {\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n\n if (w === this.constructor.AUTO && h === this.constructor.AUTO) {\n return throwError.call(this, \"w and h cannot both be set to auto\", cb);\n }\n\n if (w === this.constructor.AUTO) {\n w = this.bitmap.width * (h / this.bitmap.height);\n }\n\n if (h === this.constructor.AUTO) {\n h = this.bitmap.height * (w / this.bitmap.width);\n }\n\n if (w < 0 || h < 0) {\n return throwError.call(this, \"w and h must be positive numbers\", cb);\n }\n\n // round inputs\n w = Math.round(w) || 1;\n h = Math.round(h) || 1;\n\n if (typeof Resize2[mode] === \"function\") {\n const dst = {\n data: Buffer.alloc(w * h * 4),\n width: w,\n height: h,\n };\n Resize2[mode](this.bitmap, dst);\n this.bitmap = dst;\n } else {\n const image = this;\n const resize = new Resize(\n this.bitmap.width,\n this.bitmap.height,\n w,\n h,\n true,\n true,\n (buffer) => {\n image.bitmap.data = Buffer.from(buffer);\n image.bitmap.width = w;\n image.bitmap.height = h;\n }\n );\n resize.resize(this.bitmap.data);\n }\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n },\n});\n"],"mappings":"AAAA,SAASA,UAAU,EAAEC,aAAa,QAAQ,aAAa;AAEvD,OAAOC,MAAM,MAAM,kBAAkB;AACrC,OAAOC,OAAO,MAAM,mBAAmB;AAEvC,gBAAe,OAAO;EACpBC,SAAS,EAAE;IACTC,uBAAuB,EAAE,iBAAiB;IAC1CC,eAAe,EAAE,uBAAuB;IACxCC,cAAc,EAAE,sBAAsB;IACtCC,cAAc,EAAE,sBAAsB;IACtCC,aAAa,EAAE;EACjB,CAAC;EAEDC,KAAK,EAAE;IACL;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;IACIC,MAAM,CAACC,CAAC,EAAEC,CAAC,EAAEC,IAAI,EAAEC,EAAE,EAAE;MACrB,IAAI,OAAOH,CAAC,KAAK,QAAQ,IAAI,OAAOC,CAAC,KAAK,QAAQ,EAAE;QAClD,OAAOb,UAAU,CAACgB,IAAI,CAAC,IAAI,EAAE,yBAAyB,EAAED,EAAE,CAAC;MAC7D;MAEA,IAAI,OAAOD,IAAI,KAAK,UAAU,IAAI,OAAOC,EAAE,KAAK,WAAW,EAAE;QAC3DA,EAAE,GAAGD,IAAI;QACTA,IAAI,GAAG,IAAI;MACb;MAEA,IAAIF,CAAC,KAAK,IAAI,CAACK,WAAW,CAACC,IAAI,IAAIL,CAAC,KAAK,IAAI,CAACI,WAAW,CAACC,IAAI,EAAE;QAC9D,OAAOlB,UAAU,CAACgB,IAAI,CAAC,IAAI,EAAE,oCAAoC,EAAED,EAAE,CAAC;MACxE;MAEA,IAAIH,CAAC,KAAK,IAAI,CAACK,WAAW,CAACC,IAAI,EAAE;QAC/BN,CAAC,GAAG,IAAI,CAACO,MAAM,CAACC,KAAK,IAAIP,CAAC,GAAG,IAAI,CAACM,MAAM,CAACE,MAAM,C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ACF;QACDF,MAAM,CAACA,MAAM,CAAC,IAAI,CAACQ,MAAM,CAACM,IAAI,CAAC;MACjC;MAEA,IAAIxB,aAAa,CAACc,EAAE,CAAC,EAAE;QACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;MAC3B;MAEA,OAAO,IAAI;IACb;EACF;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-resize/es/modules/resize.js b/node_modules/@jimp/plugin-resize/es/modules/resize.js new file mode 100644 index 00000000..619c6b8c --- /dev/null +++ b/node_modules/@jimp/plugin-resize/es/modules/resize.js @@ -0,0 +1,355 @@ +// JavaScript Image Resizer (c) 2012 - Grant Galitz +// Released to public domain 29 July 2013: https://github.com/grantgalitz/JS-Image-Resizer/issues/4 + +function Resize(widthOriginal, heightOriginal, targetWidth, targetHeight, blendAlpha, interpolationPass, resizeCallback) { + this.widthOriginal = Math.abs(Math.floor(widthOriginal) || 0); + this.heightOriginal = Math.abs(Math.floor(heightOriginal) || 0); + this.targetWidth = Math.abs(Math.floor(targetWidth) || 0); + this.targetHeight = Math.abs(Math.floor(targetHeight) || 0); + this.colorChannels = blendAlpha ? 4 : 3; + this.interpolationPass = Boolean(interpolationPass); + this.resizeCallback = typeof resizeCallback === "function" ? resizeCallback : function () {}; + this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels; + this.originalWidthMultipliedByChannels = this.widthOriginal * this.colorChannels; + this.originalHeightMultipliedByChannels = this.heightOriginal * this.colorChannels; + this.widthPassResultSize = this.targetWidthMultipliedByChannels * this.heightOriginal; + this.finalResultSize = this.targetWidthMultipliedByChannels * this.targetHeight; + this.initialize(); +} +Resize.prototype.initialize = function () { + // Perform some checks: + if (this.widthOriginal > 0 && this.heightOriginal > 0 && this.targetWidth > 0 && this.targetHeight > 0) { + this.configurePasses(); + } else { + throw new Error("Invalid settings specified for the resizer."); + } +}; +Resize.prototype.configurePasses = function () { + if (this.widthOriginal === this.targetWidth) { + // Bypass the width resizer pass: + this.resizeWidth = this.bypassResizer; + } else { + // Setup the width resizer pass: + this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth; + if (this.ratioWeightWidthPass < 1 && this.interpolationPass) { + this.initializeFirstPassBuffers(true); + this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthInterpolatedRGBA : this.resizeWidthInterpolatedRGB; + } else { + this.initializeFirstPassBuffers(false); + this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthRGBA : this.resizeWidthRGB; + } + } + if (this.heightOriginal === this.targetHeight) { + // Bypass the height resizer pass: + this.resizeHeight = this.bypassResizer; + } else { + // Setup the height resizer pass: + this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight; + if (this.ratioWeightHeightPass < 1 && this.interpolationPass) { + this.initializeSecondPassBuffers(true); + this.resizeHeight = this.resizeHeightInterpolated; + } else { + this.initializeSecondPassBuffers(false); + this.resizeHeight = this.colorChannels === 4 ? this.resizeHeightRGBA : this.resizeHeightRGB; + } + } +}; +Resize.prototype._resizeWidthInterpolatedRGBChannels = function (buffer, fourthChannel) { + const channelsNum = fourthChannel ? 4 : 3; + const ratioWeight = this.ratioWeightWidthPass; + const outputBuffer = this.widthBuffer; + let weight = 0; + let finalOffset = 0; + let pixelOffset = 0; + let firstWeight = 0; + let secondWeight = 0; + let targetPosition; + + // Handle for only one interpolation input being valid for start calculation: + for (targetPosition = 0; weight < 1 / 3; targetPosition += channelsNum, weight += ratioWeight) { + for (finalOffset = targetPosition, pixelOffset = 0; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { + outputBuffer[finalOffset] = buffer[pixelOffset]; + outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; + outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; + if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3]; + } + } + + // Adjust for overshoot of the last pass's counter: + weight -= 1 / 3; + let interpolationWidthSourceReadStop; + for (interpolationWidthSourceReadStop = this.widthOriginal - 1; weight < interpolationWidthSourceReadStop; targetPosition += channelsNum, weight += ratioWeight) { + // Calculate weightings: + secondWeight = weight % 1; + firstWeight = 1 - secondWeight; + // Interpolate: + for (finalOffset = targetPosition, pixelOffset = Math.floor(weight) * channelsNum; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { + outputBuffer[finalOffset + 0] = buffer[pixelOffset + 0] * firstWeight + buffer[pixelOffset + channelsNum + 0] * secondWeight; + outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1] * firstWeight + buffer[pixelOffset + channelsNum + 1] * secondWeight; + outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2] * firstWeight + buffer[pixelOffset + channelsNum + 2] * secondWeight; + if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3] * firstWeight + buffer[pixelOffset + channelsNum + 3] * secondWeight; + } + } + + // Handle for only one interpolation input being valid for end calculation: + for (interpolationWidthSourceReadStop = this.originalWidthMultipliedByChannels - channelsNum; targetPosition < this.targetWidthMultipliedByChannels; targetPosition += channelsNum) { + for (finalOffset = targetPosition, pixelOffset = interpolationWidthSourceReadStop; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { + outputBuffer[finalOffset] = buffer[pixelOffset]; + outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; + outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; + if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3]; + } + } + return outputBuffer; +}; +Resize.prototype._resizeWidthRGBChannels = function (buffer, fourthChannel) { + const channelsNum = fourthChannel ? 4 : 3; + const ratioWeight = this.ratioWeightWidthPass; + const ratioWeightDivisor = 1 / ratioWeight; + const nextLineOffsetOriginalWidth = this.originalWidthMultipliedByChannels - channelsNum + 1; + const nextLineOffsetTargetWidth = this.targetWidthMultipliedByChannels - channelsNum + 1; + const output = this.outputWidthWorkBench; + const outputBuffer = this.widthBuffer; + const trustworthyColorsCount = this.outputWidthWorkBenchOpaquePixelsCount; + let weight = 0; + let amountToNext = 0; + let actualPosition = 0; + let currentPosition = 0; + let line = 0; + let pixelOffset = 0; + let outputOffset = 0; + let multiplier = 1; + let r = 0; + let g = 0; + let b = 0; + let a = 0; + do { + for (line = 0; line < this.originalHeightMultipliedByChannels;) { + output[line++] = 0; + output[line++] = 0; + output[line++] = 0; + if (fourthChannel) { + output[line++] = 0; + trustworthyColorsCount[line / channelsNum - 1] = 0; + } + } + weight = ratioWeight; + do { + amountToNext = 1 + actualPosition - currentPosition; + multiplier = Math.min(weight, amountToNext); + for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) { + r = buffer[pixelOffset]; + g = buffer[++pixelOffset]; + b = buffer[++pixelOffset]; + a = fourthChannel ? buffer[++pixelOffset] : 255; + // Ignore RGB values if pixel is completely transparent + output[line++] += (a ? r : 0) * multiplier; + output[line++] += (a ? g : 0) * multiplier; + output[line++] += (a ? b : 0) * multiplier; + if (fourthChannel) { + output[line++] += a * multiplier; + trustworthyColorsCount[line / channelsNum - 1] += a ? multiplier : 0; + } + } + if (weight >= amountToNext) { + actualPosition += channelsNum; + currentPosition = actualPosition; + weight -= amountToNext; + } else { + currentPosition += weight; + break; + } + } while (weight > 0 && actualPosition < this.originalWidthMultipliedByChannels); + for (line = 0, pixelOffset = outputOffset; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetTargetWidth) { + weight = fourthChannel ? trustworthyColorsCount[line / channelsNum] : 1; + multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor; + outputBuffer[pixelOffset] = output[line++] * multiplier; + outputBuffer[++pixelOffset] = output[line++] * multiplier; + outputBuffer[++pixelOffset] = output[line++] * multiplier; + if (fourthChannel) outputBuffer[++pixelOffset] = output[line++] * ratioWeightDivisor; + } + outputOffset += channelsNum; + } while (outputOffset < this.targetWidthMultipliedByChannels); + return outputBuffer; +}; +Resize.prototype._resizeHeightRGBChannels = function (buffer, fourthChannel) { + const ratioWeight = this.ratioWeightHeightPass; + const ratioWeightDivisor = 1 / ratioWeight; + const output = this.outputHeightWorkBench; + const outputBuffer = this.heightBuffer; + const trustworthyColorsCount = this.outputHeightWorkBenchOpaquePixelsCount; + let weight = 0; + let amountToNext = 0; + let actualPosition = 0; + let currentPosition = 0; + let pixelOffset = 0; + let outputOffset = 0; + let caret = 0; + let multiplier = 1; + let r = 0; + let g = 0; + let b = 0; + let a = 0; + do { + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { + output[pixelOffset++] = 0; + output[pixelOffset++] = 0; + output[pixelOffset++] = 0; + if (fourthChannel) { + output[pixelOffset++] = 0; + trustworthyColorsCount[pixelOffset / 4 - 1] = 0; + } + } + weight = ratioWeight; + do { + amountToNext = 1 + actualPosition - currentPosition; + multiplier = Math.min(weight, amountToNext); + caret = actualPosition; + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { + r = buffer[caret++]; + g = buffer[caret++]; + b = buffer[caret++]; + a = fourthChannel ? buffer[caret++] : 255; + // Ignore RGB values if pixel is completely transparent + output[pixelOffset++] += (a ? r : 0) * multiplier; + output[pixelOffset++] += (a ? g : 0) * multiplier; + output[pixelOffset++] += (a ? b : 0) * multiplier; + if (fourthChannel) { + output[pixelOffset++] += a * multiplier; + trustworthyColorsCount[pixelOffset / 4 - 1] += a ? multiplier : 0; + } + } + if (weight >= amountToNext) { + actualPosition = caret; + currentPosition = actualPosition; + weight -= amountToNext; + } else { + currentPosition += weight; + break; + } + } while (weight > 0 && actualPosition < this.widthPassResultSize); + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { + weight = fourthChannel ? trustworthyColorsCount[pixelOffset / 4] : 1; + multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor; + outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier); + outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier); + outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier); + if (fourthChannel) { + outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); + } + } + } while (outputOffset < this.finalResultSize); + return outputBuffer; +}; +Resize.prototype.resizeWidthInterpolatedRGB = function (buffer) { + return this._resizeWidthInterpolatedRGBChannels(buffer, false); +}; +Resize.prototype.resizeWidthInterpolatedRGBA = function (buffer) { + return this._resizeWidthInterpolatedRGBChannels(buffer, true); +}; +Resize.prototype.resizeWidthRGB = function (buffer) { + return this._resizeWidthRGBChannels(buffer, false); +}; +Resize.prototype.resizeWidthRGBA = function (buffer) { + return this._resizeWidthRGBChannels(buffer, true); +}; +Resize.prototype.resizeHeightInterpolated = function (buffer) { + const ratioWeight = this.ratioWeightHeightPass; + const outputBuffer = this.heightBuffer; + let weight = 0; + let finalOffset = 0; + let pixelOffset = 0; + let pixelOffsetAccumulated = 0; + let pixelOffsetAccumulated2 = 0; + let firstWeight = 0; + let secondWeight = 0; + let interpolationHeightSourceReadStop; + + // Handle for only one interpolation input being valid for start calculation: + for (; weight < 1 / 3; weight += ratioWeight) { + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { + outputBuffer[finalOffset++] = Math.round(buffer[pixelOffset++]); + } + } + + // Adjust for overshoot of the last pass's counter: + weight -= 1 / 3; + for (interpolationHeightSourceReadStop = this.heightOriginal - 1; weight < interpolationHeightSourceReadStop; weight += ratioWeight) { + // Calculate weightings: + secondWeight = weight % 1; + firstWeight = 1 - secondWeight; + // Interpolate: + pixelOffsetAccumulated = Math.floor(weight) * this.targetWidthMultipliedByChannels; + pixelOffsetAccumulated2 = pixelOffsetAccumulated + this.targetWidthMultipliedByChannels; + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) { + outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++] * firstWeight + buffer[pixelOffsetAccumulated2++] * secondWeight); + } + } + + // Handle for only one interpolation input being valid for end calculation: + while (finalOffset < this.finalResultSize) { + for (pixelOffset = 0, pixelOffsetAccumulated = interpolationHeightSourceReadStop * this.targetWidthMultipliedByChannels; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) { + outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++]); + } + } + return outputBuffer; +}; +Resize.prototype.resizeHeightRGB = function (buffer) { + return this._resizeHeightRGBChannels(buffer, false); +}; +Resize.prototype.resizeHeightRGBA = function (buffer) { + return this._resizeHeightRGBChannels(buffer, true); +}; +Resize.prototype.resize = function (buffer) { + this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer))); +}; +Resize.prototype.bypassResizer = function (buffer) { + // Just return the buffer passed: + return buffer; +}; +Resize.prototype.initializeFirstPassBuffers = function (BILINEARAlgo) { + // Initialize the internal width pass buffers: + this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize); + if (!BILINEARAlgo) { + this.outputWidthWorkBench = this.generateFloatBuffer(this.originalHeightMultipliedByChannels); + if (this.colorChannels > 3) { + this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.heightOriginal); + } + } +}; +Resize.prototype.initializeSecondPassBuffers = function (BILINEARAlgo) { + // Initialize the internal height pass buffers: + this.heightBuffer = this.generateUint8Buffer(this.finalResultSize); + if (!BILINEARAlgo) { + this.outputHeightWorkBench = this.generateFloatBuffer(this.targetWidthMultipliedByChannels); + if (this.colorChannels > 3) { + this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.targetWidth); + } + } +}; +Resize.prototype.generateFloatBuffer = function (bufferLength) { + // Generate a float32 typed array buffer: + try { + return new Float32Array(bufferLength); + } catch (error) { + return []; + } +}; +Resize.prototype.generateFloat64Buffer = function (bufferLength) { + // Generate a float64 typed array buffer: + try { + return new Float64Array(bufferLength); + } catch (error) { + return []; + } +}; +Resize.prototype.generateUint8Buffer = function (bufferLength) { + // Generate a uint8 typed array buffer: + try { + return new Uint8Array(bufferLength); + } catch (error) { + return []; + } +}; +export default Resize; +//# sourceMappingURL=resize.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-resize/es/modules/resize.js.map b/node_modules/@jimp/plugin-resize/es/modules/resize.js.map new file mode 100644 index 00000000..5dd2ddec --- /dev/null +++ b/node_modules/@jimp/plugin-resize/es/modules/resize.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resize.js","names":["Resize","widthOriginal","heightOriginal","targetWidth","targetHeight","blendAlpha","interpolationPass","resizeCallback","Math","abs","floor","colorChannels","Boolean","targetWidthMultipliedByChannels","originalWidthMultipliedByChannels","originalHeightMultipliedByChannels","widthPassResultSize","finalResultSize","initialize","prototype","configurePasses","Error","resizeWidth","bypassResizer","ratioWeightWidthPass","initializeFirstPassBuffers","resizeWidthInterpolatedRGBA","resizeWidthInterpolatedRGB","resizeWidthRGBA","resizeWidthRGB","resizeHeight","ratioWeightHeightPass","initializeSecondPassBuffers","resizeHeightInterpolated","resizeHeightRGBA","resizeHeightRGB","_resizeWidthInterpolatedRGBChannels","buffer","fourthChannel","channelsNum","ratioWeight","outputBuffer","widthBuffer","weight","finalOffset","pixelOffset","firstWeight","secondWeight","targetPosition","interpolationWidthSourceReadStop","_resizeWidthRGBChannels","ratioWeightDivisor","nextLineOffsetOriginalWidth","nextLineOffsetTargetWidth","output","outputWidthWorkBench","trustworthyColorsCount","outputWidthWorkBenchOpaquePixelsCount","amountToNext","actualPosition","currentPosition","line","outputOffset","multiplier","r","g","b","a","min","_resizeHeightRGBChannels","outputHeightWorkBench","heightBuffer","outputHeightWorkBenchOpaquePixelsCount","caret","round","pixelOffsetAccumulated","pixelOffsetAccumulated2","interpolationHeightSourceReadStop","resize","BILINEARAlgo","generateFloatBuffer","generateFloat64Buffer","generateUint8Buffer","bufferLength","Float32Array","error","Float64Array","Uint8Array"],"sources":["../../src/modules/resize.js"],"sourcesContent":["// JavaScript Image Resizer (c) 2012 - Grant Galitz\n// Released to public domain 29 July 2013: https://github.com/grantgalitz/JS-Image-Resizer/issues/4\n\nfunction Resize(\n widthOriginal,\n heightOriginal,\n targetWidth,\n targetHeight,\n blendAlpha,\n interpolationPass,\n resizeCallback\n) {\n this.widthOriginal = Math.abs(Math.floor(widthOriginal) || 0);\n this.heightOriginal = Math.abs(Math.floor(heightOriginal) || 0);\n this.targetWidth = Math.abs(Math.floor(targetWidth) || 0);\n this.targetHeight = Math.abs(Math.floor(targetHeight) || 0);\n this.colorChannels = blendAlpha ? 4 : 3;\n this.interpolationPass = Boolean(interpolationPass);\n this.resizeCallback =\n typeof resizeCallback === \"function\" ? resizeCallback : function () {};\n\n this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels;\n this.originalWidthMultipliedByChannels =\n this.widthOriginal * this.colorChannels;\n this.originalHeightMultipliedByChannels =\n this.heightOriginal * this.colorChannels;\n this.widthPassResultSize =\n this.targetWidthMultipliedByChannels * this.heightOriginal;\n this.finalResultSize =\n this.targetWidthMultipliedByChannels * this.targetHeight;\n this.initialize();\n}\n\nResize.prototype.initialize = function () {\n // Perform some checks:\n if (\n this.widthOriginal > 0 &&\n this.heightOriginal > 0 &&\n this.targetWidth > 0 &&\n this.targetHeight > 0\n ) {\n this.configurePasses();\n } else {\n throw new Error(\"Invalid settings specified for the resizer.\");\n }\n};\n\nResize.prototype.configurePasses = function () {\n if (this.widthOriginal === this.targetWidth) {\n // Bypass the width resizer pass:\n this.resizeWidth = this.bypassResizer;\n } else {\n // Setup the width resizer pass:\n this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth;\n if (this.ratioWeightWidthPass < 1 && this.interpolationPass) {\n this.initializeFirstPassBuffers(true);\n this.resizeWidth =\n this.colorChannels === 4\n ? this.resizeWidthInterpolatedRGBA\n : this.resizeWidthInterpolatedRGB;\n } else {\n this.initializeFirstPassBuffers(false);\n this.resizeWidth =\n this.colorChannels === 4 ? this.resizeWidthRGBA : this.resizeWidthRGB;\n }\n }\n\n if (this.heightOriginal === this.targetHeight) {\n // Bypass the height resizer pass:\n this.resizeHeight = this.bypassResizer;\n } else {\n // Setup the height resizer pass:\n this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight;\n if (this.ratioWeightHeightPass < 1 && this.interpolationPass) {\n this.initializeSecondPassBuffers(true);\n this.resizeHeight = this.resizeHeightInterpolated;\n } else {\n this.initializeSecondPassBuffers(false);\n this.resizeHeight =\n this.colorChannels === 4 ? this.resizeHeightRGBA : this.resizeHeightRGB;\n }\n }\n};\n\nResize.prototype._resizeWidthInterpolatedRGBChannels = function (\n buffer,\n fourthChannel\n) {\n const channelsNum = fourthChannel ? 4 : 3;\n const ratioWeight = this.ratioWeightWidthPass;\n const outputBuffer = this.widthBuffer;\n\n let weight = 0;\n let finalOffset = 0;\n let pixelOffset = 0;\n let firstWeight = 0;\n let secondWeight = 0;\n let targetPosition;\n\n // Handle for only one interpolation input being valid for start calculation:\n for (\n targetPosition = 0;\n weight < 1 / 3;\n targetPosition += channelsNum, weight += ratioWeight\n ) {\n for (\n finalOffset = targetPosition, pixelOffset = 0;\n finalOffset < this.widthPassResultSize;\n pixelOffset += this.originalWidthMultipliedByChannels,\n finalOffset += this.targetWidthMultipliedByChannels\n ) {\n outputBuffer[finalOffset] = buffer[pixelOffset];\n outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];\n outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];\n if (fourthChannel)\n outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];\n }\n }\n\n // Adjust for overshoot of the last pass's counter:\n weight -= 1 / 3;\n let interpolationWidthSourceReadStop;\n\n for (\n interpolationWidthSourceReadStop = this.widthOriginal - 1;\n weight < interpolationWidthSourceReadStop;\n targetPosition += channelsNum, weight += ratioWeight\n ) {\n // Calculate weightings:\n secondWeight = weight % 1;\n firstWeight = 1 - secondWeight;\n // Interpolate:\n for (\n finalOffset = targetPosition,\n pixelOffset = Math.floor(weight) * channelsNum;\n finalOffset < this.widthPassResultSize;\n pixelOffset += this.originalWidthMultipliedByChannels,\n finalOffset += this.targetWidthMultipliedByChannels\n ) {\n outputBuffer[finalOffset + 0] =\n buffer[pixelOffset + 0] * firstWeight +\n buffer[pixelOffset + channelsNum + 0] * secondWeight;\n outputBuffer[finalOffset + 1] =\n buffer[pixelOffset + 1] * firstWeight +\n buffer[pixelOffset + channelsNum + 1] * secondWeight;\n outputBuffer[finalOffset + 2] =\n buffer[pixelOffset + 2] * firstWeight +\n buffer[pixelOffset + channelsNum + 2] * secondWeight;\n if (fourthChannel)\n outputBuffer[finalOffset + 3] =\n buffer[pixelOffset + 3] * firstWeight +\n buffer[pixelOffset + channelsNum + 3] * secondWeight;\n }\n }\n\n // Handle for only one interpolation input being valid for end calculation:\n for (\n interpolationWidthSourceReadStop =\n this.originalWidthMultipliedByChannels - channelsNum;\n targetPosition < this.targetWidthMultipliedByChannels;\n targetPosition += channelsNum\n ) {\n for (\n finalOffset = targetPosition,\n pixelOffset = interpolationWidthSourceReadStop;\n finalOffset < this.widthPassResultSize;\n pixelOffset += this.originalWidthMultipliedByChannels,\n finalOffset += this.targetWidthMultipliedByChannels\n ) {\n outputBuffer[finalOffset] = buffer[pixelOffset];\n outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];\n outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];\n if (fourthChannel)\n outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];\n }\n }\n\n return outputBuffer;\n};\n\nResize.prototype._resizeWidthRGBChannels = function (buffer, fourthChannel) {\n const channelsNum = fourthChannel ? 4 : 3;\n const ratioWeight = this.ratioWeightWidthPass;\n const ratioWeightDivisor = 1 / ratioWeight;\n const nextLineOffsetOriginalWidth =\n this.originalWidthMultipliedByChannels - channelsNum + 1;\n const nextLineOffsetTargetWidth =\n this.targetWidthMultipliedByChannels - channelsNum + 1;\n const output = this.outputWidthWorkBench;\n const outputBuffer = this.widthBuffer;\n const trustworthyColorsCount = this.outputWidthWorkBenchOpaquePixelsCount;\n\n let weight = 0;\n let amountToNext = 0;\n let actualPosition = 0;\n let currentPosition = 0;\n let line = 0;\n let pixelOffset = 0;\n let outputOffset = 0;\n let multiplier = 1;\n let r = 0;\n let g = 0;\n let b = 0;\n let a = 0;\n\n do {\n for (line = 0; line < this.originalHeightMultipliedByChannels; ) {\n output[line++] = 0;\n output[line++] = 0;\n output[line++] = 0;\n if (fourthChannel) {\n output[line++] = 0;\n trustworthyColorsCount[line / channelsNum - 1] = 0;\n }\n }\n\n weight = ratioWeight;\n\n do {\n amountToNext = 1 + actualPosition - currentPosition;\n multiplier = Math.min(weight, amountToNext);\n for (\n line = 0, pixelOffset = actualPosition;\n line < this.originalHeightMultipliedByChannels;\n pixelOffset += nextLineOffsetOriginalWidth\n ) {\n r = buffer[pixelOffset];\n g = buffer[++pixelOffset];\n b = buffer[++pixelOffset];\n a = fourthChannel ? buffer[++pixelOffset] : 255;\n // Ignore RGB values if pixel is completely transparent\n output[line++] += (a ? r : 0) * multiplier;\n output[line++] += (a ? g : 0) * multiplier;\n output[line++] += (a ? b : 0) * multiplier;\n if (fourthChannel) {\n output[line++] += a * multiplier;\n trustworthyColorsCount[line / channelsNum - 1] += a ? multiplier : 0;\n }\n }\n\n if (weight >= amountToNext) {\n actualPosition += channelsNum;\n currentPosition = actualPosition;\n weight -= amountToNext;\n } else {\n currentPosition += weight;\n break;\n }\n } while (\n weight > 0 &&\n actualPosition < this.originalWidthMultipliedByChannels\n );\n\n for (\n line = 0, pixelOffset = outputOffset;\n line < this.originalHeightMultipliedByChannels;\n pixelOffset += nextLineOffsetTargetWidth\n ) {\n weight = fourthChannel ? trustworthyColorsCount[line / channelsNum] : 1;\n multiplier = fourthChannel\n ? weight\n ? 1 / weight\n : 0\n : ratioWeightDivisor;\n outputBuffer[pixelOffset] = output[line++] * multiplier;\n outputBuffer[++pixelOffset] = output[line++] * multiplier;\n outputBuffer[++pixelOffset] = output[line++] * multiplier;\n if (fourthChannel)\n outputBuffer[++pixelOffset] = output[line++] * ratioWeightDivisor;\n }\n\n outputOffset += channelsNum;\n } while (outputOffset < this.targetWidthMultipliedByChannels);\n\n return outputBuffer;\n};\n\nResize.prototype._resizeHeightRGBChannels = function (buffer, fourthChannel) {\n const ratioWeight = this.ratioWeightHeightPass;\n const ratioWeightDivisor = 1 / ratioWeight;\n const output = this.outputHeightWorkBench;\n const outputBuffer = this.heightBuffer;\n const trustworthyColorsCount = this.outputHeightWorkBenchOpaquePixelsCount;\n\n let weight = 0;\n let amountToNext = 0;\n let actualPosition = 0;\n let currentPosition = 0;\n let pixelOffset = 0;\n let outputOffset = 0;\n let caret = 0;\n let multiplier = 1;\n let r = 0;\n let g = 0;\n let b = 0;\n let a = 0;\n\n do {\n for (\n pixelOffset = 0;\n pixelOffset < this.targetWidthMultipliedByChannels;\n\n ) {\n output[pixelOffset++] = 0;\n output[pixelOffset++] = 0;\n output[pixelOffset++] = 0;\n\n if (fourthChannel) {\n output[pixelOffset++] = 0;\n trustworthyColorsCount[pixelOffset / 4 - 1] = 0;\n }\n }\n\n weight = ratioWeight;\n\n do {\n amountToNext = 1 + actualPosition - currentPosition;\n multiplier = Math.min(weight, amountToNext);\n caret = actualPosition;\n\n for (\n pixelOffset = 0;\n pixelOffset < this.targetWidthMultipliedByChannels;\n\n ) {\n r = buffer[caret++];\n g = buffer[caret++];\n b = buffer[caret++];\n a = fourthChannel ? buffer[caret++] : 255;\n // Ignore RGB values if pixel is completely transparent\n output[pixelOffset++] += (a ? r : 0) * multiplier;\n output[pixelOffset++] += (a ? g : 0) * multiplier;\n output[pixelOffset++] += (a ? b : 0) * multiplier;\n\n if (fourthChannel) {\n output[pixelOffset++] += a * multiplier;\n trustworthyColorsCount[pixelOffset / 4 - 1] += a ? multiplier : 0;\n }\n }\n\n if (weight >= amountToNext) {\n actualPosition = caret;\n currentPosition = actualPosition;\n weight -= amountToNext;\n } else {\n currentPosition += weight;\n break;\n }\n } while (weight > 0 && actualPosition < this.widthPassResultSize);\n\n for (\n pixelOffset = 0;\n pixelOffset < this.targetWidthMultipliedByChannels;\n\n ) {\n weight = fourthChannel ? trustworthyColorsCount[pixelOffset / 4] : 1;\n multiplier = fourthChannel\n ? weight\n ? 1 / weight\n : 0\n : ratioWeightDivisor;\n outputBuffer[outputOffset++] = Math.round(\n output[pixelOffset++] * multiplier\n );\n outputBuffer[outputOffset++] = Math.round(\n output[pixelOffset++] * multiplier\n );\n outputBuffer[outputOffset++] = Math.round(\n output[pixelOffset++] * multiplier\n );\n\n if (fourthChannel) {\n outputBuffer[outputOffset++] = Math.round(\n output[pixelOffset++] * ratioWeightDivisor\n );\n }\n }\n } while (outputOffset < this.finalResultSize);\n\n return outputBuffer;\n};\n\nResize.prototype.resizeWidthInterpolatedRGB = function (buffer) {\n return this._resizeWidthInterpolatedRGBChannels(buffer, false);\n};\n\nResize.prototype.resizeWidthInterpolatedRGBA = function (buffer) {\n return this._resizeWidthInterpolatedRGBChannels(buffer, true);\n};\n\nResize.prototype.resizeWidthRGB = function (buffer) {\n return this._resizeWidthRGBChannels(buffer, false);\n};\n\nResize.prototype.resizeWidthRGBA = function (buffer) {\n return this._resizeWidthRGBChannels(buffer, true);\n};\n\nResize.prototype.resizeHeightInterpolated = function (buffer) {\n const ratioWeight = this.ratioWeightHeightPass;\n const outputBuffer = this.heightBuffer;\n\n let weight = 0;\n let finalOffset = 0;\n let pixelOffset = 0;\n let pixelOffsetAccumulated = 0;\n let pixelOffsetAccumulated2 = 0;\n let firstWeight = 0;\n let secondWeight = 0;\n let interpolationHeightSourceReadStop;\n\n // Handle for only one interpolation input being valid for start calculation:\n for (; weight < 1 / 3; weight += ratioWeight) {\n for (\n pixelOffset = 0;\n pixelOffset < this.targetWidthMultipliedByChannels;\n\n ) {\n outputBuffer[finalOffset++] = Math.round(buffer[pixelOffset++]);\n }\n }\n\n // Adjust for overshoot of the last pass's counter:\n weight -= 1 / 3;\n\n for (\n interpolationHeightSourceReadStop = this.heightOriginal - 1;\n weight < interpolationHeightSourceReadStop;\n weight += ratioWeight\n ) {\n // Calculate weightings:\n secondWeight = weight % 1;\n firstWeight = 1 - secondWeight;\n // Interpolate:\n pixelOffsetAccumulated =\n Math.floor(weight) * this.targetWidthMultipliedByChannels;\n pixelOffsetAccumulated2 =\n pixelOffsetAccumulated + this.targetWidthMultipliedByChannels;\n for (\n pixelOffset = 0;\n pixelOffset < this.targetWidthMultipliedByChannels;\n ++pixelOffset\n ) {\n outputBuffer[finalOffset++] = Math.round(\n buffer[pixelOffsetAccumulated++] * firstWeight +\n buffer[pixelOffsetAccumulated2++] * secondWeight\n );\n }\n }\n\n // Handle for only one interpolation input being valid for end calculation:\n while (finalOffset < this.finalResultSize) {\n for (\n pixelOffset = 0,\n pixelOffsetAccumulated =\n interpolationHeightSourceReadStop *\n this.targetWidthMultipliedByChannels;\n pixelOffset < this.targetWidthMultipliedByChannels;\n ++pixelOffset\n ) {\n outputBuffer[finalOffset++] = Math.round(\n buffer[pixelOffsetAccumulated++]\n );\n }\n }\n\n return outputBuffer;\n};\n\nResize.prototype.resizeHeightRGB = function (buffer) {\n return this._resizeHeightRGBChannels(buffer, false);\n};\n\nResize.prototype.resizeHeightRGBA = function (buffer) {\n return this._resizeHeightRGBChannels(buffer, true);\n};\n\nResize.prototype.resize = function (buffer) {\n this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer)));\n};\n\nResize.prototype.bypassResizer = function (buffer) {\n // Just return the buffer passed:\n return buffer;\n};\n\nResize.prototype.initializeFirstPassBuffers = function (BILINEARAlgo) {\n // Initialize the internal width pass buffers:\n this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize);\n\n if (!BILINEARAlgo) {\n this.outputWidthWorkBench = this.generateFloatBuffer(\n this.originalHeightMultipliedByChannels\n );\n\n if (this.colorChannels > 3) {\n this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(\n this.heightOriginal\n );\n }\n }\n};\n\nResize.prototype.initializeSecondPassBuffers = function (BILINEARAlgo) {\n // Initialize the internal height pass buffers:\n this.heightBuffer = this.generateUint8Buffer(this.finalResultSize);\n\n if (!BILINEARAlgo) {\n this.outputHeightWorkBench = this.generateFloatBuffer(\n this.targetWidthMultipliedByChannels\n );\n\n if (this.colorChannels > 3) {\n this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(\n this.targetWidth\n );\n }\n }\n};\n\nResize.prototype.generateFloatBuffer = function (bufferLength) {\n // Generate a float32 typed array buffer:\n try {\n return new Float32Array(bufferLength);\n } catch (error) {\n return [];\n }\n};\n\nResize.prototype.generateFloat64Buffer = function (bufferLength) {\n // Generate a float64 typed array buffer:\n try {\n return new Float64Array(bufferLength);\n } catch (error) {\n return [];\n }\n};\n\nResize.prototype.generateUint8Buffer = function (bufferLength) {\n // Generate a uint8 typed array buffer:\n try {\n return new Uint8Array(bufferLength);\n } catch (error) {\n return [];\n }\n};\n\nexport default Resize;\n"],"mappings":"AAAA;AACA;;AAEA,SAASA,MAAM,CACbC,aAAa,EACbC,cAAc,EACdC,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,iBAAiB,EACjBC,cAAc,EACd;EACA,IAAI,CAACN,aAAa,GAAGO,IAAI,CAACC,GAAG,CAACD,IAAI,CAACE,KAAK,CAACT,aAAa,CAAC,IAAI,CAAC,CAAC;EAC7D,IAAI,CAACC,cAAc,GAAGM,IAAI,CAACC,GAAG,CAACD,IAAI,CAACE,KAAK,CAACR,cAAc,CAAC,IAAI,CAAC,CAAC;EAC/D,IAAI,CAACC,WAAW,GAAGK,IAAI,CAACC,GAAG,CAACD,IAAI,CAACE,KAAK,CAACP,WAAW,CAAC,IAAI,CAAC,CAAC;EACzD,IAAI,CAACC,YAAY,GAAGI,IAAI,CAACC,GAAG,CAACD,IAAI,CAACE,KAAK,CAACN,YAAY,CAAC,IAAI,CAAC,CAAC;EAC3D,IAAI,CAACO,aAAa,GAAGN,UAAU,GAAG,CAAC,GAAG,CAAC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,CAAC,CAAC,OAAOE,KAAK,EAAE;IACd,OAAO,EAAE;EACX;AACF,CAAC;AAEDrF,MAAM,CAACmB,SAAS,CAAC+D,mBAAmB,GAAG,UAAUC,YAAY,EAAE;EAC7D;EACA,IAAI;IACF,OAAO,IAAII,UAAU,CAACJ,YAAY,CAAC;EACrC,CAAC,CAAC,OAAOE,KAAK,EAAE;IACd,OAAO,EAAE;EACX;AACF,CAAC;AAED,eAAerF,MAAM"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-resize/es/modules/resize2.js b/node_modules/@jimp/plugin-resize/es/modules/resize2.js new file mode 100644 index 00000000..d1fad17c --- /dev/null +++ b/node_modules/@jimp/plugin-resize/es/modules/resize2.js @@ -0,0 +1,248 @@ +/** + * Copyright (c) 2015 Guyon Roche + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions:

+ * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +const operations = { + nearestNeighbor(src, dst) { + const wSrc = src.width; + const hSrc = src.height; + const wDst = dst.width; + const hDst = dst.height; + const bufSrc = src.data; + const bufDst = dst.data; + for (let i = 0; i < hDst; i++) { + for (let j = 0; j < wDst; j++) { + let posDst = (i * wDst + j) * 4; + const iSrc = Math.floor(i * hSrc / hDst); + const jSrc = Math.floor(j * wSrc / wDst); + let posSrc = (iSrc * wSrc + jSrc) * 4; + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + } + } + }, + bilinearInterpolation(src, dst) { + const wSrc = src.width; + const hSrc = src.height; + const wDst = dst.width; + const hDst = dst.height; + const bufSrc = src.data; + const bufDst = dst.data; + const interpolate = function (k, kMin, vMin, kMax, vMax) { + // special case - k is integer + if (kMin === kMax) { + return vMin; + } + return Math.round((k - kMin) * vMax + (kMax - k) * vMin); + }; + const assign = function (pos, offset, x, xMin, xMax, y, yMin, yMax) { + let posMin = (yMin * wSrc + xMin) * 4 + offset; + let posMax = (yMin * wSrc + xMax) * 4 + offset; + const vMin = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]); + + // special case, y is integer + if (yMax === yMin) { + bufDst[pos + offset] = vMin; + } else { + posMin = (yMax * wSrc + xMin) * 4 + offset; + posMax = (yMax * wSrc + xMax) * 4 + offset; + const vMax = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]); + bufDst[pos + offset] = interpolate(y, yMin, vMin, yMax, vMax); + } + }; + for (let i = 0; i < hDst; i++) { + for (let j = 0; j < wDst; j++) { + const posDst = (i * wDst + j) * 4; + // x & y in src coordinates + const x = j * wSrc / wDst; + const xMin = Math.floor(x); + const xMax = Math.min(Math.ceil(x), wSrc - 1); + const y = i * hSrc / hDst; + const yMin = Math.floor(y); + const yMax = Math.min(Math.ceil(y), hSrc - 1); + assign(posDst, 0, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 1, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 2, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 3, x, xMin, xMax, y, yMin, yMax); + } + } + }, + _interpolate2D(src, dst, options, interpolate) { + const bufSrc = src.data; + const bufDst = dst.data; + const wSrc = src.width; + const hSrc = src.height; + const wDst = dst.width; + const hDst = dst.height; + + // when dst smaller than src/2, interpolate first to a multiple between 0.5 and 1.0 src, then sum squares + const wM = Math.max(1, Math.floor(wSrc / wDst)); + const wDst2 = wDst * wM; + const hM = Math.max(1, Math.floor(hSrc / hDst)); + const hDst2 = hDst * hM; + + // =========================================================== + // Pass 1 - interpolate rows + // buf1 has width of dst2 and height of src + const buf1 = Buffer.alloc(wDst2 * hSrc * 4); + for (let i = 0; i < hSrc; i++) { + for (let j = 0; j < wDst2; j++) { + // i in src coords, j in dst coords + + // calculate x in src coords + // this interpolation requires 4 sample points and the two inner ones must be real + // the outer points can be fudged for the edges. + // therefore (wSrc-1)/wDst2 + const x = j * (wSrc - 1) / wDst2; + const xPos = Math.floor(x); + const t = x - xPos; + const srcPos = (i * wSrc + xPos) * 4; + const buf1Pos = (i * wDst2 + j) * 4; + for (let k = 0; k < 4; k++) { + const kPos = srcPos + k; + const x0 = xPos > 0 ? bufSrc[kPos - 4] : 2 * bufSrc[kPos] - bufSrc[kPos + 4]; + const x1 = bufSrc[kPos]; + const x2 = bufSrc[kPos + 4]; + const x3 = xPos < wSrc - 2 ? bufSrc[kPos + 8] : 2 * bufSrc[kPos + 4] - bufSrc[kPos]; + buf1[buf1Pos + k] = interpolate(x0, x1, x2, x3, t); + } + } + } + // this._writeFile(wDst2, hSrc, buf1, "out/buf1.jpg"); + + // =========================================================== + // Pass 2 - interpolate columns + // buf2 has width and height of dst2 + const buf2 = Buffer.alloc(wDst2 * hDst2 * 4); + for (let i = 0; i < hDst2; i++) { + for (let j = 0; j < wDst2; j++) { + // i&j in dst2 coords + + // calculate y in buf1 coords + // this interpolation requires 4 sample points and the two inner ones must be real + // the outer points can be fudged for the edges. + // therefore (hSrc-1)/hDst2 + const y = i * (hSrc - 1) / hDst2; + const yPos = Math.floor(y); + const t = y - yPos; + const buf1Pos = (yPos * wDst2 + j) * 4; + const buf2Pos = (i * wDst2 + j) * 4; + for (let k = 0; k < 4; k++) { + const kPos = buf1Pos + k; + const y0 = yPos > 0 ? buf1[kPos - wDst2 * 4] : 2 * buf1[kPos] - buf1[kPos + wDst2 * 4]; + const y1 = buf1[kPos]; + const y2 = buf1[kPos + wDst2 * 4]; + const y3 = yPos < hSrc - 2 ? buf1[kPos + wDst2 * 8] : 2 * buf1[kPos + wDst2 * 4] - buf1[kPos]; + buf2[buf2Pos + k] = interpolate(y0, y1, y2, y3, t); + } + } + } + // this._writeFile(wDst2, hDst2, buf2, "out/buf2.jpg"); + + // =========================================================== + // Pass 3 - scale to dst + const m = wM * hM; + if (m > 1) { + for (let i = 0; i < hDst; i++) { + for (let j = 0; j < wDst; j++) { + // i&j in dst bounded coords + let r = 0; + let g = 0; + let b = 0; + let a = 0; + let realColors = 0; + for (let y = 0; y < hM; y++) { + const yPos = i * hM + y; + for (let x = 0; x < wM; x++) { + const xPos = j * wM + x; + const xyPos = (yPos * wDst2 + xPos) * 4; + const pixelAlpha = buf2[xyPos + 3]; + if (pixelAlpha) { + r += buf2[xyPos]; + g += buf2[xyPos + 1]; + b += buf2[xyPos + 2]; + realColors++; + } + a += pixelAlpha; + } + } + const pos = (i * wDst + j) * 4; + bufDst[pos] = realColors ? Math.round(r / realColors) : 0; + bufDst[pos + 1] = realColors ? Math.round(g / realColors) : 0; + bufDst[pos + 2] = realColors ? Math.round(b / realColors) : 0; + bufDst[pos + 3] = Math.round(a / m); + } + } + } else { + // replace dst buffer with buf2 + dst.data = buf2; + } + }, + bicubicInterpolation(src, dst, options) { + const interpolateCubic = function (x0, x1, x2, x3, t) { + const a0 = x3 - x2 - x0 + x1; + const a1 = x0 - x1 - a0; + const a2 = x2 - x0; + const a3 = x1; + return Math.max(0, Math.min(255, a0 * (t * t * t) + a1 * (t * t) + a2 * t + a3)); + }; + return this._interpolate2D(src, dst, options, interpolateCubic); + }, + hermiteInterpolation(src, dst, options) { + const interpolateHermite = function (x0, x1, x2, x3, t) { + const c0 = x1; + const c1 = 0.5 * (x2 - x0); + const c2 = x0 - 2.5 * x1 + 2 * x2 - 0.5 * x3; + const c3 = 0.5 * (x3 - x0) + 1.5 * (x1 - x2); + return Math.max(0, Math.min(255, Math.round(((c3 * t + c2) * t + c1) * t + c0))); + }; + return this._interpolate2D(src, dst, options, interpolateHermite); + }, + bezierInterpolation(src, dst, options) { + // between 2 points y(n), y(n+1), use next points out, y(n-1), y(n+2) + // to predict control points (a & b) to be placed at n+0.5 + // ya(n) = y(n) + (y(n+1)-y(n-1))/4 + // yb(n) = y(n+1) - (y(n+2)-y(n))/4 + // then use std bezier to interpolate [n,n+1) + // y(n+t) = y(n)*(1-t)^3 + 3 * ya(n)*(1-t)^2*t + 3 * yb(n)*(1-t)*t^2 + y(n+1)*t^3 + // note the 3* factor for the two control points + // for edge cases, can choose: + // y(-1) = y(0) - 2*(y(1)-y(0)) + // y(w) = y(w-1) + 2*(y(w-1)-y(w-2)) + // but can go with y(-1) = y(0) and y(w) = y(w-1) + const interpolateBezier = function (x0, x1, x2, x3, t) { + // x1, x2 are the knots, use x0 and x3 to calculate control points + const cp1 = x1 + (x2 - x0) / 4; + const cp2 = x2 - (x3 - x1) / 4; + const nt = 1 - t; + const c0 = x1 * nt * nt * nt; + const c1 = 3 * cp1 * nt * nt * t; + const c2 = 3 * cp2 * nt * t * t; + const c3 = x2 * t * t * t; + return Math.max(0, Math.min(255, Math.round(c0 + c1 + c2 + c3))); + }; + return this._interpolate2D(src, dst, options, interpolateBezier); + } +}; +export default operations; +//# sourceMappingURL=resize2.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-resize/es/modules/resize2.js.map b/node_modules/@jimp/plugin-resize/es/modules/resize2.js.map new file mode 100644 index 00000000..21edaf92 --- /dev/null +++ b/node_modules/@jimp/plugin-resize/es/modules/resize2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resize2.js","names":["operations","nearestNeighbor","src","dst","wSrc","width","hSrc","height","wDst","hDst","bufSrc","data","bufDst","i","j","posDst","iSrc","Math","floor","jSrc","posSrc","bilinearInterpolation","interpolate","k","kMin","vMin","kMax","vMax","round","assign","pos","offset","x","xMin","xMax","y","yMin","yMax","posMin","posMax","min","ceil","_interpolate2D","options","wM","max","wDst2","hM","hDst2","buf1","Buffer","alloc","xPos","t","srcPos","buf1Pos","kPos","x0","x1","x2","x3","buf2","yPos","buf2Pos","y0","y1","y2","y3","m","r","g","b","a","realColors","xyPos","pixelAlpha","bicubicInterpolation","interpolateCubic","a0","a1","a2","a3","hermiteInterpolation","interpolateHermite","c0","c1","c2","c3","bezierInterpolation","interpolateBezier","cp1","cp2","nt"],"sources":["../../src/modules/resize2.js"],"sourcesContent":["/**\n * Copyright (c) 2015 Guyon Roche\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:

\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\nconst operations = {\n nearestNeighbor(src, dst) {\n const wSrc = src.width;\n const hSrc = src.height;\n\n const wDst = dst.width;\n const hDst = dst.height;\n\n const bufSrc = src.data;\n const bufDst = dst.data;\n\n for (let i = 0; i < hDst; i++) {\n for (let j = 0; j < wDst; j++) {\n let posDst = (i * wDst + j) * 4;\n\n const iSrc = Math.floor((i * hSrc) / hDst);\n const jSrc = Math.floor((j * wSrc) / wDst);\n let posSrc = (iSrc * wSrc + jSrc) * 4;\n\n bufDst[posDst++] = bufSrc[posSrc++];\n bufDst[posDst++] = bufSrc[posSrc++];\n bufDst[posDst++] = bufSrc[posSrc++];\n bufDst[posDst++] = bufSrc[posSrc++];\n }\n }\n },\n\n bilinearInterpolation(src, dst) {\n const wSrc = src.width;\n const hSrc = src.height;\n\n const wDst = dst.width;\n const hDst = dst.height;\n\n const bufSrc = src.data;\n const bufDst = dst.data;\n\n const interpolate = function (k, kMin, vMin, kMax, vMax) {\n // special case - k is integer\n if (kMin === kMax) {\n return vMin;\n }\n\n return Math.round((k - kMin) * vMax + (kMax - k) * vMin);\n };\n\n const assign = function (pos, offset, x, xMin, xMax, y, yMin, yMax) {\n let posMin = (yMin * wSrc + xMin) * 4 + offset;\n let posMax = (yMin * wSrc + xMax) * 4 + offset;\n const vMin = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]);\n\n // special case, y is integer\n if (yMax === yMin) {\n bufDst[pos + offset] = vMin;\n } else {\n posMin = (yMax * wSrc + xMin) * 4 + offset;\n posMax = (yMax * wSrc + xMax) * 4 + offset;\n const vMax = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]);\n\n bufDst[pos + offset] = interpolate(y, yMin, vMin, yMax, vMax);\n }\n };\n\n for (let i = 0; i < hDst; i++) {\n for (let j = 0; j < wDst; j++) {\n const posDst = (i * wDst + j) * 4;\n // x & y in src coordinates\n const x = (j * wSrc) / wDst;\n const xMin = Math.floor(x);\n const xMax = Math.min(Math.ceil(x), wSrc - 1);\n\n const y = (i * hSrc) / hDst;\n const yMin = Math.floor(y);\n const yMax = Math.min(Math.ceil(y), hSrc - 1);\n\n assign(posDst, 0, x, xMin, xMax, y, yMin, yMax);\n assign(posDst, 1, x, xMin, xMax, y, yMin, yMax);\n assign(posDst, 2, x, xMin, xMax, y, yMin, yMax);\n assign(posDst, 3, x, xMin, xMax, y, yMin, yMax);\n }\n }\n },\n\n _interpolate2D(src, dst, options, interpolate) {\n const bufSrc = src.data;\n const bufDst = dst.data;\n\n const wSrc = src.width;\n const hSrc = src.height;\n\n const wDst = dst.width;\n const hDst = dst.height;\n\n // when dst smaller than src/2, interpolate first to a multiple between 0.5 and 1.0 src, then sum squares\n const wM = Math.max(1, Math.floor(wSrc / wDst));\n const wDst2 = wDst * wM;\n const hM = Math.max(1, Math.floor(hSrc / hDst));\n const hDst2 = hDst * hM;\n\n // ===========================================================\n // Pass 1 - interpolate rows\n // buf1 has width of dst2 and height of src\n const buf1 = Buffer.alloc(wDst2 * hSrc * 4);\n for (let i = 0; i < hSrc; i++) {\n for (let j = 0; j < wDst2; j++) {\n // i in src coords, j in dst coords\n\n // calculate x in src coords\n // this interpolation requires 4 sample points and the two inner ones must be real\n // the outer points can be fudged for the edges.\n // therefore (wSrc-1)/wDst2\n const x = (j * (wSrc - 1)) / wDst2;\n const xPos = Math.floor(x);\n const t = x - xPos;\n const srcPos = (i * wSrc + xPos) * 4;\n const buf1Pos = (i * wDst2 + j) * 4;\n\n for (let k = 0; k < 4; k++) {\n const kPos = srcPos + k;\n const x0 =\n xPos > 0 ? bufSrc[kPos - 4] : 2 * bufSrc[kPos] - bufSrc[kPos + 4];\n const x1 = bufSrc[kPos];\n const x2 = bufSrc[kPos + 4];\n const x3 =\n xPos < wSrc - 2\n ? bufSrc[kPos + 8]\n : 2 * bufSrc[kPos + 4] - bufSrc[kPos];\n buf1[buf1Pos + k] = interpolate(x0, x1, x2, x3, t);\n }\n }\n }\n // this._writeFile(wDst2, hSrc, buf1, \"out/buf1.jpg\");\n\n // ===========================================================\n // Pass 2 - interpolate columns\n // buf2 has width and height of dst2\n const buf2 = Buffer.alloc(wDst2 * hDst2 * 4);\n for (let i = 0; i < hDst2; i++) {\n for (let j = 0; j < wDst2; j++) {\n // i&j in dst2 coords\n\n // calculate y in buf1 coords\n // this interpolation requires 4 sample points and the two inner ones must be real\n // the outer points can be fudged for the edges.\n // therefore (hSrc-1)/hDst2\n const y = (i * (hSrc - 1)) / hDst2;\n const yPos = Math.floor(y);\n const t = y - yPos;\n const buf1Pos = (yPos * wDst2 + j) * 4;\n const buf2Pos = (i * wDst2 + j) * 4;\n for (let k = 0; k < 4; k++) {\n const kPos = buf1Pos + k;\n const y0 =\n yPos > 0\n ? buf1[kPos - wDst2 * 4]\n : 2 * buf1[kPos] - buf1[kPos + wDst2 * 4];\n const y1 = buf1[kPos];\n const y2 = buf1[kPos + wDst2 * 4];\n const y3 =\n yPos < hSrc - 2\n ? buf1[kPos + wDst2 * 8]\n : 2 * buf1[kPos + wDst2 * 4] - buf1[kPos];\n\n buf2[buf2Pos + k] = interpolate(y0, y1, y2, y3, t);\n }\n }\n }\n // this._writeFile(wDst2, hDst2, buf2, \"out/buf2.jpg\");\n\n // ===========================================================\n // Pass 3 - scale to dst\n const m = wM * hM;\n if (m > 1) {\n for (let i = 0; i < hDst; i++) {\n for (let j = 0; j < wDst; j++) {\n // i&j in dst bounded coords\n let r = 0;\n let g = 0;\n let b = 0;\n let a = 0;\n let realColors = 0;\n\n for (let y = 0; y < hM; y++) {\n const yPos = i * hM + y;\n\n for (let x = 0; x < wM; x++) {\n const xPos = j * wM + x;\n const xyPos = (yPos * wDst2 + xPos) * 4;\n const pixelAlpha = buf2[xyPos + 3];\n\n if (pixelAlpha) {\n r += buf2[xyPos];\n g += buf2[xyPos + 1];\n b += buf2[xyPos + 2];\n realColors++;\n }\n\n a += pixelAlpha;\n }\n }\n\n const pos = (i * wDst + j) * 4;\n bufDst[pos] = realColors ? Math.round(r / realColors) : 0;\n bufDst[pos + 1] = realColors ? Math.round(g / realColors) : 0;\n bufDst[pos + 2] = realColors ? Math.round(b / realColors) : 0;\n bufDst[pos + 3] = Math.round(a / m);\n }\n }\n } else {\n // replace dst buffer with buf2\n dst.data = buf2;\n }\n },\n\n bicubicInterpolation(src, dst, options) {\n const interpolateCubic = function (x0, x1, x2, x3, t) {\n const a0 = x3 - x2 - x0 + x1;\n const a1 = x0 - x1 - a0;\n const a2 = x2 - x0;\n const a3 = x1;\n return Math.max(\n 0,\n Math.min(255, a0 * (t * t * t) + a1 * (t * t) + a2 * t + a3)\n );\n };\n\n return this._interpolate2D(src, dst, options, interpolateCubic);\n },\n\n hermiteInterpolation(src, dst, options) {\n const interpolateHermite = function (x0, x1, x2, x3, t) {\n const c0 = x1;\n const c1 = 0.5 * (x2 - x0);\n const c2 = x0 - 2.5 * x1 + 2 * x2 - 0.5 * x3;\n const c3 = 0.5 * (x3 - x0) + 1.5 * (x1 - x2);\n return Math.max(\n 0,\n Math.min(255, Math.round(((c3 * t + c2) * t + c1) * t + c0))\n );\n };\n\n return this._interpolate2D(src, dst, options, interpolateHermite);\n },\n\n bezierInterpolation(src, dst, options) {\n // between 2 points y(n), y(n+1), use next points out, y(n-1), y(n+2)\n // to predict control points (a & b) to be placed at n+0.5\n // ya(n) = y(n) + (y(n+1)-y(n-1))/4\n // yb(n) = y(n+1) - (y(n+2)-y(n))/4\n // then use std bezier to interpolate [n,n+1)\n // y(n+t) = y(n)*(1-t)^3 + 3 * ya(n)*(1-t)^2*t + 3 * yb(n)*(1-t)*t^2 + y(n+1)*t^3\n // note the 3* factor for the two control points\n // for edge cases, can choose:\n // y(-1) = y(0) - 2*(y(1)-y(0))\n // y(w) = y(w-1) + 2*(y(w-1)-y(w-2))\n // but can go with y(-1) = y(0) and y(w) = y(w-1)\n const interpolateBezier = function (x0, x1, x2, x3, t) {\n // x1, x2 are the knots, use x0 and x3 to calculate control points\n const cp1 = x1 + (x2 - x0) / 4;\n const cp2 = x2 - (x3 - x1) / 4;\n const nt = 1 - t;\n const c0 = x1 * nt * nt * nt;\n const c1 = 3 * cp1 * nt * nt * t;\n const c2 = 3 * cp2 * nt * t * t;\n const c3 = x2 * t * t * t;\n return Math.max(0, Math.min(255, Math.round(c0 + c1 + c2 + c3)));\n };\n\n return this._interpolate2D(src, dst, options, interpolateBezier);\n },\n};\n\nexport default operations;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,MAAMA,UAAU,GAAG;EACjBC,eAAe,CAACC,GAAG,EAAEC,GAAG,EAAE;IACxB,MAAMC,IAAI,GAAGF,GAAG,CAACG,KAAK;IACtB,MAAMC,IAAI,GAAGJ,GAAG,CAACK,MAAM;IAEvB,MAAMC,IAAI,GAAGL,GAAG,CAACE,KAAK;IACtB,MAAMI,IAAI,GAAGN,GAAG,CAACI,MAAM;IAEvB,MAAMG,MAAM,GAAGR,GAAG,CAACS,IAAI;IACvB,MAAMC,MAAM,GAAGT,GAAG,CAACQ,IAAI;IAEvB,KAAK,IAAIE,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGJ,IAAI,EAAEI,CAAC,EAAE,EAAE;MAC7B,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGN,IAAI,EAAEM,CAAC,EAAE,EAAE;QAC7B,IAAIC,MAAM,GAAG,CAACF,CAAC,GAAGL,IAAI,GAAGM,CAAC,IAAI,CAAC;QAE/B,MAAME,IAAI,GAAGC,IAAI,CAACC,KAAK,CAAEL,CAAC,GAAGP,IAAI,GAAIG,IAAI,CAAC;QAC1C,MAAMU,IAAI,GAAGF,IAAI,CAACC,KAAK,CAAEJ,CAAC,GAAGV,IAAI,GAAII,IAAI,CAAC;QAC1C,IAAIY,MAAM,GAAG,CAACJ,IAAI,GAAGZ,IAAI,GAAGe,IAAI,IAAI,CAAC;QAErCP,MAAM,CAACG,MAAM,EAAE,CAAC,GAAGL,MAAM,CAACU,MAAM,EAAE,CAAC;QACnCR,MAAM,CAACG,MAAM,EAAE,CAAC,GAAGL,MAAM,CAACU,MAAM,EAAE,CA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,KAAK,CAACwD,EAAE,GAAGC,EAAE,GAAGC,EAAE,GAAGC,EAAE,CAAC,CAAC,CAAC;IAClE,CAAC;IAED,OAAO,IAAI,CAAC7C,cAAc,CAACxC,GAAG,EAAEC,GAAG,EAAEwC,OAAO,EAAE8C,iBAAiB,CAAC;EAClE;AACF,CAAC;AAED,eAAezF,UAAU"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-resize/index.d.ts b/node_modules/@jimp/plugin-resize/index.d.ts new file mode 100644 index 00000000..58b3cdcb --- /dev/null +++ b/node_modules/@jimp/plugin-resize/index.d.ts @@ -0,0 +1,21 @@ +import { ImageCallback } from "@jimp/core"; + +interface ResizeClass { + resize(w: number, h: number, cb?: ImageCallback): this; + resize(w: number, h: number, mode?: string, cb?: ImageCallback): this; +} + +interface Resize { + constants: { + // resize methods + RESIZE_NEAREST_NEIGHBOR: "nearestNeighbor"; + RESIZE_BILINEAR: "bilinearInterpolation"; + RESIZE_BICUBIC: "bicubicInterpolation"; + RESIZE_HERMITE: "hermiteInterpolation"; + RESIZE_BEZIER: "bezierInterpolation"; + }; + + class: ResizeClass; +} + +export default function (): Resize; diff --git a/node_modules/@jimp/plugin-resize/package.json b/node_modules/@jimp/plugin-resize/package.json new file mode 100644 index 00000000..1e955a96 --- /dev/null +++ b/node_modules/@jimp/plugin-resize/package.json @@ -0,0 +1,37 @@ +{ + "name": "@jimp/plugin-resize", + "version": "0.22.12", + "description": "Resize an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-resize/src/index.js b/node_modules/@jimp/plugin-resize/src/index.js new file mode 100644 index 00000000..5b269d54 --- /dev/null +++ b/node_modules/@jimp/plugin-resize/src/index.js @@ -0,0 +1,87 @@ +import { throwError, isNodePattern } from "@jimp/utils"; + +import Resize from "./modules/resize"; +import Resize2 from "./modules/resize2"; + +export default () => ({ + constants: { + RESIZE_NEAREST_NEIGHBOR: "nearestNeighbor", + RESIZE_BILINEAR: "bilinearInterpolation", + RESIZE_BICUBIC: "bicubicInterpolation", + RESIZE_HERMITE: "hermiteInterpolation", + RESIZE_BEZIER: "bezierInterpolation", + }, + + class: { + /** + * Resizes the image to a set width and height using a 2-pass bilinear algorithm + * @param {number} w the width to resize the image to (or Jimp.AUTO) + * @param {number} h the height to resize the image to (or Jimp.AUTO) + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + resize(w, h, mode, cb) { + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + + if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + + if (w === this.constructor.AUTO && h === this.constructor.AUTO) { + return throwError.call(this, "w and h cannot both be set to auto", cb); + } + + if (w === this.constructor.AUTO) { + w = this.bitmap.width * (h / this.bitmap.height); + } + + if (h === this.constructor.AUTO) { + h = this.bitmap.height * (w / this.bitmap.width); + } + + if (w < 0 || h < 0) { + return throwError.call(this, "w and h must be positive numbers", cb); + } + + // round inputs + w = Math.round(w) || 1; + h = Math.round(h) || 1; + + if (typeof Resize2[mode] === "function") { + const dst = { + data: Buffer.alloc(w * h * 4), + width: w, + height: h, + }; + Resize2[mode](this.bitmap, dst); + this.bitmap = dst; + } else { + const image = this; + const resize = new Resize( + this.bitmap.width, + this.bitmap.height, + w, + h, + true, + true, + (buffer) => { + image.bitmap.data = Buffer.from(buffer); + image.bitmap.width = w; + image.bitmap.height = h; + } + ); + resize.resize(this.bitmap.data); + } + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + }, +}); diff --git a/node_modules/@jimp/plugin-resize/src/modules/resize.js b/node_modules/@jimp/plugin-resize/src/modules/resize.js new file mode 100644 index 00000000..9fea5ed2 --- /dev/null +++ b/node_modules/@jimp/plugin-resize/src/modules/resize.js @@ -0,0 +1,548 @@ +// JavaScript Image Resizer (c) 2012 - Grant Galitz +// Released to public domain 29 July 2013: https://github.com/grantgalitz/JS-Image-Resizer/issues/4 + +function Resize( + widthOriginal, + heightOriginal, + targetWidth, + targetHeight, + blendAlpha, + interpolationPass, + resizeCallback +) { + this.widthOriginal = Math.abs(Math.floor(widthOriginal) || 0); + this.heightOriginal = Math.abs(Math.floor(heightOriginal) || 0); + this.targetWidth = Math.abs(Math.floor(targetWidth) || 0); + this.targetHeight = Math.abs(Math.floor(targetHeight) || 0); + this.colorChannels = blendAlpha ? 4 : 3; + this.interpolationPass = Boolean(interpolationPass); + this.resizeCallback = + typeof resizeCallback === "function" ? resizeCallback : function () {}; + + this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels; + this.originalWidthMultipliedByChannels = + this.widthOriginal * this.colorChannels; + this.originalHeightMultipliedByChannels = + this.heightOriginal * this.colorChannels; + this.widthPassResultSize = + this.targetWidthMultipliedByChannels * this.heightOriginal; + this.finalResultSize = + this.targetWidthMultipliedByChannels * this.targetHeight; + this.initialize(); +} + +Resize.prototype.initialize = function () { + // Perform some checks: + if ( + this.widthOriginal > 0 && + this.heightOriginal > 0 && + this.targetWidth > 0 && + this.targetHeight > 0 + ) { + this.configurePasses(); + } else { + throw new Error("Invalid settings specified for the resizer."); + } +}; + +Resize.prototype.configurePasses = function () { + if (this.widthOriginal === this.targetWidth) { + // Bypass the width resizer pass: + this.resizeWidth = this.bypassResizer; + } else { + // Setup the width resizer pass: + this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth; + if (this.ratioWeightWidthPass < 1 && this.interpolationPass) { + this.initializeFirstPassBuffers(true); + this.resizeWidth = + this.colorChannels === 4 + ? this.resizeWidthInterpolatedRGBA + : this.resizeWidthInterpolatedRGB; + } else { + this.initializeFirstPassBuffers(false); + this.resizeWidth = + this.colorChannels === 4 ? this.resizeWidthRGBA : this.resizeWidthRGB; + } + } + + if (this.heightOriginal === this.targetHeight) { + // Bypass the height resizer pass: + this.resizeHeight = this.bypassResizer; + } else { + // Setup the height resizer pass: + this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight; + if (this.ratioWeightHeightPass < 1 && this.interpolationPass) { + this.initializeSecondPassBuffers(true); + this.resizeHeight = this.resizeHeightInterpolated; + } else { + this.initializeSecondPassBuffers(false); + this.resizeHeight = + this.colorChannels === 4 ? this.resizeHeightRGBA : this.resizeHeightRGB; + } + } +}; + +Resize.prototype._resizeWidthInterpolatedRGBChannels = function ( + buffer, + fourthChannel +) { + const channelsNum = fourthChannel ? 4 : 3; + const ratioWeight = this.ratioWeightWidthPass; + const outputBuffer = this.widthBuffer; + + let weight = 0; + let finalOffset = 0; + let pixelOffset = 0; + let firstWeight = 0; + let secondWeight = 0; + let targetPosition; + + // Handle for only one interpolation input being valid for start calculation: + for ( + targetPosition = 0; + weight < 1 / 3; + targetPosition += channelsNum, weight += ratioWeight + ) { + for ( + finalOffset = targetPosition, pixelOffset = 0; + finalOffset < this.widthPassResultSize; + pixelOffset += this.originalWidthMultipliedByChannels, + finalOffset += this.targetWidthMultipliedByChannels + ) { + outputBuffer[finalOffset] = buffer[pixelOffset]; + outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; + outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; + if (fourthChannel) + outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3]; + } + } + + // Adjust for overshoot of the last pass's counter: + weight -= 1 / 3; + let interpolationWidthSourceReadStop; + + for ( + interpolationWidthSourceReadStop = this.widthOriginal - 1; + weight < interpolationWidthSourceReadStop; + targetPosition += channelsNum, weight += ratioWeight + ) { + // Calculate weightings: + secondWeight = weight % 1; + firstWeight = 1 - secondWeight; + // Interpolate: + for ( + finalOffset = targetPosition, + pixelOffset = Math.floor(weight) * channelsNum; + finalOffset < this.widthPassResultSize; + pixelOffset += this.originalWidthMultipliedByChannels, + finalOffset += this.targetWidthMultipliedByChannels + ) { + outputBuffer[finalOffset + 0] = + buffer[pixelOffset + 0] * firstWeight + + buffer[pixelOffset + channelsNum + 0] * secondWeight; + outputBuffer[finalOffset + 1] = + buffer[pixelOffset + 1] * firstWeight + + buffer[pixelOffset + channelsNum + 1] * secondWeight; + outputBuffer[finalOffset + 2] = + buffer[pixelOffset + 2] * firstWeight + + buffer[pixelOffset + channelsNum + 2] * secondWeight; + if (fourthChannel) + outputBuffer[finalOffset + 3] = + buffer[pixelOffset + 3] * firstWeight + + buffer[pixelOffset + channelsNum + 3] * secondWeight; + } + } + + // Handle for only one interpolation input being valid for end calculation: + for ( + interpolationWidthSourceReadStop = + this.originalWidthMultipliedByChannels - channelsNum; + targetPosition < this.targetWidthMultipliedByChannels; + targetPosition += channelsNum + ) { + for ( + finalOffset = targetPosition, + pixelOffset = interpolationWidthSourceReadStop; + finalOffset < this.widthPassResultSize; + pixelOffset += this.originalWidthMultipliedByChannels, + finalOffset += this.targetWidthMultipliedByChannels + ) { + outputBuffer[finalOffset] = buffer[pixelOffset]; + outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; + outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; + if (fourthChannel) + outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3]; + } + } + + return outputBuffer; +}; + +Resize.prototype._resizeWidthRGBChannels = function (buffer, fourthChannel) { + const channelsNum = fourthChannel ? 4 : 3; + const ratioWeight = this.ratioWeightWidthPass; + const ratioWeightDivisor = 1 / ratioWeight; + const nextLineOffsetOriginalWidth = + this.originalWidthMultipliedByChannels - channelsNum + 1; + const nextLineOffsetTargetWidth = + this.targetWidthMultipliedByChannels - channelsNum + 1; + const output = this.outputWidthWorkBench; + const outputBuffer = this.widthBuffer; + const trustworthyColorsCount = this.outputWidthWorkBenchOpaquePixelsCount; + + let weight = 0; + let amountToNext = 0; + let actualPosition = 0; + let currentPosition = 0; + let line = 0; + let pixelOffset = 0; + let outputOffset = 0; + let multiplier = 1; + let r = 0; + let g = 0; + let b = 0; + let a = 0; + + do { + for (line = 0; line < this.originalHeightMultipliedByChannels; ) { + output[line++] = 0; + output[line++] = 0; + output[line++] = 0; + if (fourthChannel) { + output[line++] = 0; + trustworthyColorsCount[line / channelsNum - 1] = 0; + } + } + + weight = ratioWeight; + + do { + amountToNext = 1 + actualPosition - currentPosition; + multiplier = Math.min(weight, amountToNext); + for ( + line = 0, pixelOffset = actualPosition; + line < this.originalHeightMultipliedByChannels; + pixelOffset += nextLineOffsetOriginalWidth + ) { + r = buffer[pixelOffset]; + g = buffer[++pixelOffset]; + b = buffer[++pixelOffset]; + a = fourthChannel ? buffer[++pixelOffset] : 255; + // Ignore RGB values if pixel is completely transparent + output[line++] += (a ? r : 0) * multiplier; + output[line++] += (a ? g : 0) * multiplier; + output[line++] += (a ? b : 0) * multiplier; + if (fourthChannel) { + output[line++] += a * multiplier; + trustworthyColorsCount[line / channelsNum - 1] += a ? multiplier : 0; + } + } + + if (weight >= amountToNext) { + actualPosition += channelsNum; + currentPosition = actualPosition; + weight -= amountToNext; + } else { + currentPosition += weight; + break; + } + } while ( + weight > 0 && + actualPosition < this.originalWidthMultipliedByChannels + ); + + for ( + line = 0, pixelOffset = outputOffset; + line < this.originalHeightMultipliedByChannels; + pixelOffset += nextLineOffsetTargetWidth + ) { + weight = fourthChannel ? trustworthyColorsCount[line / channelsNum] : 1; + multiplier = fourthChannel + ? weight + ? 1 / weight + : 0 + : ratioWeightDivisor; + outputBuffer[pixelOffset] = output[line++] * multiplier; + outputBuffer[++pixelOffset] = output[line++] * multiplier; + outputBuffer[++pixelOffset] = output[line++] * multiplier; + if (fourthChannel) + outputBuffer[++pixelOffset] = output[line++] * ratioWeightDivisor; + } + + outputOffset += channelsNum; + } while (outputOffset < this.targetWidthMultipliedByChannels); + + return outputBuffer; +}; + +Resize.prototype._resizeHeightRGBChannels = function (buffer, fourthChannel) { + const ratioWeight = this.ratioWeightHeightPass; + const ratioWeightDivisor = 1 / ratioWeight; + const output = this.outputHeightWorkBench; + const outputBuffer = this.heightBuffer; + const trustworthyColorsCount = this.outputHeightWorkBenchOpaquePixelsCount; + + let weight = 0; + let amountToNext = 0; + let actualPosition = 0; + let currentPosition = 0; + let pixelOffset = 0; + let outputOffset = 0; + let caret = 0; + let multiplier = 1; + let r = 0; + let g = 0; + let b = 0; + let a = 0; + + do { + for ( + pixelOffset = 0; + pixelOffset < this.targetWidthMultipliedByChannels; + + ) { + output[pixelOffset++] = 0; + output[pixelOffset++] = 0; + output[pixelOffset++] = 0; + + if (fourthChannel) { + output[pixelOffset++] = 0; + trustworthyColorsCount[pixelOffset / 4 - 1] = 0; + } + } + + weight = ratioWeight; + + do { + amountToNext = 1 + actualPosition - currentPosition; + multiplier = Math.min(weight, amountToNext); + caret = actualPosition; + + for ( + pixelOffset = 0; + pixelOffset < this.targetWidthMultipliedByChannels; + + ) { + r = buffer[caret++]; + g = buffer[caret++]; + b = buffer[caret++]; + a = fourthChannel ? buffer[caret++] : 255; + // Ignore RGB values if pixel is completely transparent + output[pixelOffset++] += (a ? r : 0) * multiplier; + output[pixelOffset++] += (a ? g : 0) * multiplier; + output[pixelOffset++] += (a ? b : 0) * multiplier; + + if (fourthChannel) { + output[pixelOffset++] += a * multiplier; + trustworthyColorsCount[pixelOffset / 4 - 1] += a ? multiplier : 0; + } + } + + if (weight >= amountToNext) { + actualPosition = caret; + currentPosition = actualPosition; + weight -= amountToNext; + } else { + currentPosition += weight; + break; + } + } while (weight > 0 && actualPosition < this.widthPassResultSize); + + for ( + pixelOffset = 0; + pixelOffset < this.targetWidthMultipliedByChannels; + + ) { + weight = fourthChannel ? trustworthyColorsCount[pixelOffset / 4] : 1; + multiplier = fourthChannel + ? weight + ? 1 / weight + : 0 + : ratioWeightDivisor; + outputBuffer[outputOffset++] = Math.round( + output[pixelOffset++] * multiplier + ); + outputBuffer[outputOffset++] = Math.round( + output[pixelOffset++] * multiplier + ); + outputBuffer[outputOffset++] = Math.round( + output[pixelOffset++] * multiplier + ); + + if (fourthChannel) { + outputBuffer[outputOffset++] = Math.round( + output[pixelOffset++] * ratioWeightDivisor + ); + } + } + } while (outputOffset < this.finalResultSize); + + return outputBuffer; +}; + +Resize.prototype.resizeWidthInterpolatedRGB = function (buffer) { + return this._resizeWidthInterpolatedRGBChannels(buffer, false); +}; + +Resize.prototype.resizeWidthInterpolatedRGBA = function (buffer) { + return this._resizeWidthInterpolatedRGBChannels(buffer, true); +}; + +Resize.prototype.resizeWidthRGB = function (buffer) { + return this._resizeWidthRGBChannels(buffer, false); +}; + +Resize.prototype.resizeWidthRGBA = function (buffer) { + return this._resizeWidthRGBChannels(buffer, true); +}; + +Resize.prototype.resizeHeightInterpolated = function (buffer) { + const ratioWeight = this.ratioWeightHeightPass; + const outputBuffer = this.heightBuffer; + + let weight = 0; + let finalOffset = 0; + let pixelOffset = 0; + let pixelOffsetAccumulated = 0; + let pixelOffsetAccumulated2 = 0; + let firstWeight = 0; + let secondWeight = 0; + let interpolationHeightSourceReadStop; + + // Handle for only one interpolation input being valid for start calculation: + for (; weight < 1 / 3; weight += ratioWeight) { + for ( + pixelOffset = 0; + pixelOffset < this.targetWidthMultipliedByChannels; + + ) { + outputBuffer[finalOffset++] = Math.round(buffer[pixelOffset++]); + } + } + + // Adjust for overshoot of the last pass's counter: + weight -= 1 / 3; + + for ( + interpolationHeightSourceReadStop = this.heightOriginal - 1; + weight < interpolationHeightSourceReadStop; + weight += ratioWeight + ) { + // Calculate weightings: + secondWeight = weight % 1; + firstWeight = 1 - secondWeight; + // Interpolate: + pixelOffsetAccumulated = + Math.floor(weight) * this.targetWidthMultipliedByChannels; + pixelOffsetAccumulated2 = + pixelOffsetAccumulated + this.targetWidthMultipliedByChannels; + for ( + pixelOffset = 0; + pixelOffset < this.targetWidthMultipliedByChannels; + ++pixelOffset + ) { + outputBuffer[finalOffset++] = Math.round( + buffer[pixelOffsetAccumulated++] * firstWeight + + buffer[pixelOffsetAccumulated2++] * secondWeight + ); + } + } + + // Handle for only one interpolation input being valid for end calculation: + while (finalOffset < this.finalResultSize) { + for ( + pixelOffset = 0, + pixelOffsetAccumulated = + interpolationHeightSourceReadStop * + this.targetWidthMultipliedByChannels; + pixelOffset < this.targetWidthMultipliedByChannels; + ++pixelOffset + ) { + outputBuffer[finalOffset++] = Math.round( + buffer[pixelOffsetAccumulated++] + ); + } + } + + return outputBuffer; +}; + +Resize.prototype.resizeHeightRGB = function (buffer) { + return this._resizeHeightRGBChannels(buffer, false); +}; + +Resize.prototype.resizeHeightRGBA = function (buffer) { + return this._resizeHeightRGBChannels(buffer, true); +}; + +Resize.prototype.resize = function (buffer) { + this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer))); +}; + +Resize.prototype.bypassResizer = function (buffer) { + // Just return the buffer passed: + return buffer; +}; + +Resize.prototype.initializeFirstPassBuffers = function (BILINEARAlgo) { + // Initialize the internal width pass buffers: + this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize); + + if (!BILINEARAlgo) { + this.outputWidthWorkBench = this.generateFloatBuffer( + this.originalHeightMultipliedByChannels + ); + + if (this.colorChannels > 3) { + this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer( + this.heightOriginal + ); + } + } +}; + +Resize.prototype.initializeSecondPassBuffers = function (BILINEARAlgo) { + // Initialize the internal height pass buffers: + this.heightBuffer = this.generateUint8Buffer(this.finalResultSize); + + if (!BILINEARAlgo) { + this.outputHeightWorkBench = this.generateFloatBuffer( + this.targetWidthMultipliedByChannels + ); + + if (this.colorChannels > 3) { + this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer( + this.targetWidth + ); + } + } +}; + +Resize.prototype.generateFloatBuffer = function (bufferLength) { + // Generate a float32 typed array buffer: + try { + return new Float32Array(bufferLength); + } catch (error) { + return []; + } +}; + +Resize.prototype.generateFloat64Buffer = function (bufferLength) { + // Generate a float64 typed array buffer: + try { + return new Float64Array(bufferLength); + } catch (error) { + return []; + } +}; + +Resize.prototype.generateUint8Buffer = function (bufferLength) { + // Generate a uint8 typed array buffer: + try { + return new Uint8Array(bufferLength); + } catch (error) { + return []; + } +}; + +export default Resize; diff --git a/node_modules/@jimp/plugin-resize/src/modules/resize2.js b/node_modules/@jimp/plugin-resize/src/modules/resize2.js new file mode 100644 index 00000000..3774144d --- /dev/null +++ b/node_modules/@jimp/plugin-resize/src/modules/resize2.js @@ -0,0 +1,295 @@ +/** + * Copyright (c) 2015 Guyon Roche + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions:

+ * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +const operations = { + nearestNeighbor(src, dst) { + const wSrc = src.width; + const hSrc = src.height; + + const wDst = dst.width; + const hDst = dst.height; + + const bufSrc = src.data; + const bufDst = dst.data; + + for (let i = 0; i < hDst; i++) { + for (let j = 0; j < wDst; j++) { + let posDst = (i * wDst + j) * 4; + + const iSrc = Math.floor((i * hSrc) / hDst); + const jSrc = Math.floor((j * wSrc) / wDst); + let posSrc = (iSrc * wSrc + jSrc) * 4; + + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + } + } + }, + + bilinearInterpolation(src, dst) { + const wSrc = src.width; + const hSrc = src.height; + + const wDst = dst.width; + const hDst = dst.height; + + const bufSrc = src.data; + const bufDst = dst.data; + + const interpolate = function (k, kMin, vMin, kMax, vMax) { + // special case - k is integer + if (kMin === kMax) { + return vMin; + } + + return Math.round((k - kMin) * vMax + (kMax - k) * vMin); + }; + + const assign = function (pos, offset, x, xMin, xMax, y, yMin, yMax) { + let posMin = (yMin * wSrc + xMin) * 4 + offset; + let posMax = (yMin * wSrc + xMax) * 4 + offset; + const vMin = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]); + + // special case, y is integer + if (yMax === yMin) { + bufDst[pos + offset] = vMin; + } else { + posMin = (yMax * wSrc + xMin) * 4 + offset; + posMax = (yMax * wSrc + xMax) * 4 + offset; + const vMax = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]); + + bufDst[pos + offset] = interpolate(y, yMin, vMin, yMax, vMax); + } + }; + + for (let i = 0; i < hDst; i++) { + for (let j = 0; j < wDst; j++) { + const posDst = (i * wDst + j) * 4; + // x & y in src coordinates + const x = (j * wSrc) / wDst; + const xMin = Math.floor(x); + const xMax = Math.min(Math.ceil(x), wSrc - 1); + + const y = (i * hSrc) / hDst; + const yMin = Math.floor(y); + const yMax = Math.min(Math.ceil(y), hSrc - 1); + + assign(posDst, 0, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 1, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 2, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 3, x, xMin, xMax, y, yMin, yMax); + } + } + }, + + _interpolate2D(src, dst, options, interpolate) { + const bufSrc = src.data; + const bufDst = dst.data; + + const wSrc = src.width; + const hSrc = src.height; + + const wDst = dst.width; + const hDst = dst.height; + + // when dst smaller than src/2, interpolate first to a multiple between 0.5 and 1.0 src, then sum squares + const wM = Math.max(1, Math.floor(wSrc / wDst)); + const wDst2 = wDst * wM; + const hM = Math.max(1, Math.floor(hSrc / hDst)); + const hDst2 = hDst * hM; + + // =========================================================== + // Pass 1 - interpolate rows + // buf1 has width of dst2 and height of src + const buf1 = Buffer.alloc(wDst2 * hSrc * 4); + for (let i = 0; i < hSrc; i++) { + for (let j = 0; j < wDst2; j++) { + // i in src coords, j in dst coords + + // calculate x in src coords + // this interpolation requires 4 sample points and the two inner ones must be real + // the outer points can be fudged for the edges. + // therefore (wSrc-1)/wDst2 + const x = (j * (wSrc - 1)) / wDst2; + const xPos = Math.floor(x); + const t = x - xPos; + const srcPos = (i * wSrc + xPos) * 4; + const buf1Pos = (i * wDst2 + j) * 4; + + for (let k = 0; k < 4; k++) { + const kPos = srcPos + k; + const x0 = + xPos > 0 ? bufSrc[kPos - 4] : 2 * bufSrc[kPos] - bufSrc[kPos + 4]; + const x1 = bufSrc[kPos]; + const x2 = bufSrc[kPos + 4]; + const x3 = + xPos < wSrc - 2 + ? bufSrc[kPos + 8] + : 2 * bufSrc[kPos + 4] - bufSrc[kPos]; + buf1[buf1Pos + k] = interpolate(x0, x1, x2, x3, t); + } + } + } + // this._writeFile(wDst2, hSrc, buf1, "out/buf1.jpg"); + + // =========================================================== + // Pass 2 - interpolate columns + // buf2 has width and height of dst2 + const buf2 = Buffer.alloc(wDst2 * hDst2 * 4); + for (let i = 0; i < hDst2; i++) { + for (let j = 0; j < wDst2; j++) { + // i&j in dst2 coords + + // calculate y in buf1 coords + // this interpolation requires 4 sample points and the two inner ones must be real + // the outer points can be fudged for the edges. + // therefore (hSrc-1)/hDst2 + const y = (i * (hSrc - 1)) / hDst2; + const yPos = Math.floor(y); + const t = y - yPos; + const buf1Pos = (yPos * wDst2 + j) * 4; + const buf2Pos = (i * wDst2 + j) * 4; + for (let k = 0; k < 4; k++) { + const kPos = buf1Pos + k; + const y0 = + yPos > 0 + ? buf1[kPos - wDst2 * 4] + : 2 * buf1[kPos] - buf1[kPos + wDst2 * 4]; + const y1 = buf1[kPos]; + const y2 = buf1[kPos + wDst2 * 4]; + const y3 = + yPos < hSrc - 2 + ? buf1[kPos + wDst2 * 8] + : 2 * buf1[kPos + wDst2 * 4] - buf1[kPos]; + + buf2[buf2Pos + k] = interpolate(y0, y1, y2, y3, t); + } + } + } + // this._writeFile(wDst2, hDst2, buf2, "out/buf2.jpg"); + + // =========================================================== + // Pass 3 - scale to dst + const m = wM * hM; + if (m > 1) { + for (let i = 0; i < hDst; i++) { + for (let j = 0; j < wDst; j++) { + // i&j in dst bounded coords + let r = 0; + let g = 0; + let b = 0; + let a = 0; + let realColors = 0; + + for (let y = 0; y < hM; y++) { + const yPos = i * hM + y; + + for (let x = 0; x < wM; x++) { + const xPos = j * wM + x; + const xyPos = (yPos * wDst2 + xPos) * 4; + const pixelAlpha = buf2[xyPos + 3]; + + if (pixelAlpha) { + r += buf2[xyPos]; + g += buf2[xyPos + 1]; + b += buf2[xyPos + 2]; + realColors++; + } + + a += pixelAlpha; + } + } + + const pos = (i * wDst + j) * 4; + bufDst[pos] = realColors ? Math.round(r / realColors) : 0; + bufDst[pos + 1] = realColors ? Math.round(g / realColors) : 0; + bufDst[pos + 2] = realColors ? Math.round(b / realColors) : 0; + bufDst[pos + 3] = Math.round(a / m); + } + } + } else { + // replace dst buffer with buf2 + dst.data = buf2; + } + }, + + bicubicInterpolation(src, dst, options) { + const interpolateCubic = function (x0, x1, x2, x3, t) { + const a0 = x3 - x2 - x0 + x1; + const a1 = x0 - x1 - a0; + const a2 = x2 - x0; + const a3 = x1; + return Math.max( + 0, + Math.min(255, a0 * (t * t * t) + a1 * (t * t) + a2 * t + a3) + ); + }; + + return this._interpolate2D(src, dst, options, interpolateCubic); + }, + + hermiteInterpolation(src, dst, options) { + const interpolateHermite = function (x0, x1, x2, x3, t) { + const c0 = x1; + const c1 = 0.5 * (x2 - x0); + const c2 = x0 - 2.5 * x1 + 2 * x2 - 0.5 * x3; + const c3 = 0.5 * (x3 - x0) + 1.5 * (x1 - x2); + return Math.max( + 0, + Math.min(255, Math.round(((c3 * t + c2) * t + c1) * t + c0)) + ); + }; + + return this._interpolate2D(src, dst, options, interpolateHermite); + }, + + bezierInterpolation(src, dst, options) { + // between 2 points y(n), y(n+1), use next points out, y(n-1), y(n+2) + // to predict control points (a & b) to be placed at n+0.5 + // ya(n) = y(n) + (y(n+1)-y(n-1))/4 + // yb(n) = y(n+1) - (y(n+2)-y(n))/4 + // then use std bezier to interpolate [n,n+1) + // y(n+t) = y(n)*(1-t)^3 + 3 * ya(n)*(1-t)^2*t + 3 * yb(n)*(1-t)*t^2 + y(n+1)*t^3 + // note the 3* factor for the two control points + // for edge cases, can choose: + // y(-1) = y(0) - 2*(y(1)-y(0)) + // y(w) = y(w-1) + 2*(y(w-1)-y(w-2)) + // but can go with y(-1) = y(0) and y(w) = y(w-1) + const interpolateBezier = function (x0, x1, x2, x3, t) { + // x1, x2 are the knots, use x0 and x3 to calculate control points + const cp1 = x1 + (x2 - x0) / 4; + const cp2 = x2 - (x3 - x1) / 4; + const nt = 1 - t; + const c0 = x1 * nt * nt * nt; + const c1 = 3 * cp1 * nt * nt * t; + const c2 = 3 * cp2 * nt * t * t; + const c3 = x2 * t * t * t; + return Math.max(0, Math.min(255, Math.round(c0 + c1 + c2 + c3))); + }; + + return this._interpolate2D(src, dst, options, interpolateBezier); + }, +}; + +export default operations; diff --git a/node_modules/@jimp/plugin-resize/test/resize.test.js b/node_modules/@jimp/plugin-resize/test/resize.test.js new file mode 100644 index 00000000..5a6d1c40 --- /dev/null +++ b/node_modules/@jimp/plugin-resize/test/resize.test.js @@ -0,0 +1,301 @@ +import { Jimp, mkJGD, hashForEach } from "@jimp/test-utils"; +import configure from "@jimp/custom"; + +import resize from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [resize] }, Jimp); + +describe("Resize images", () => { + const testImages = [ + { + title: "max contrast 8x8", + src: jimp.read( + mkJGD( + "■■■■□□□□", + "■■■■□□□□", + "■■■■□□□□", + "■■■■□□□□", + "□□□□■■■■", + "□□□□■■■■", + "□□□□■■■■", + "□□□□■■■■" + ) + ), + results: { + "default 4x4": mkJGD("■■□□", "■■□□", "□□■■", "□□■■"), + "NEAREST_NEIGHBOR 4x4": mkJGD("■■□□", "■■□□", "□□■■", "□□■■"), + "BILINEAR 4x4": mkJGD("■■□□", "■■□□", "□□■■", "□□■■"), + "BICUBIC 4x4": { + width: 4, + height: 4, + data: [ + 0x000000ff, 0x000000ff, 0xbfbfbfff, 0xffffffff, 0x000000ff, + 0x000000ff, 0xbfbfbfff, 0xffffffff, 0xbfbfbfff, 0xbfbfbfff, + 0x5f5f5fff, 0x404040ff, 0xffffffff, 0xffffffff, 0x404040ff, + 0x000000ff, + ], + }, + "HERMITE 4x4": { + width: 4, + height: 4, + data: [ + 0x000000ff, 0x000000ff, 0xc0c0c0ff, 0xffffffff, 0x000000ff, + 0x000000ff, 0xc0c0c0ff, 0xffffffff, 0xc0c0c0ff, 0xc0c0c0ff, + 0x606060ff, 0x404040ff, 0xffffffff, 0xffffffff, 0x404040ff, + 0x000000ff, + ], + }, + "BEZIER 4x4": { + width: 4, + height: 4, + data: [ + 0x000000ff, 0x000000ff, 0xc0c0c0ff, 0xffffffff, 0x000000ff, + 0x000000ff, 0xc0c0c0ff, 0xffffffff, 0xc0c0c0ff, 0xc0c0c0ff, + 0x606060ff, 0x404040ff, 0xffffffff, 0xffffffff, 0x404040ff, + 0x000000ff, + ], + }, + "default 5x2": mkJGD("■■▦□□", "□□▦■■"), + "NEAREST_NEIGHBOR 5x2": mkJGD("■■■□□", "□□□■■"), + "BILINEAR 5x2": mkJGD("■■3□□", "□□C■■"), + "BICUBIC 5x2": { + width: 5, + height: 2, + data: [ + 0x000000ff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff, + 0xdfdfdfff, 0xdfdfdfff, 0xdfdfdfff, 0x202020ff, 0x202020ff, + ], + }, + "HERMITE 5x2": { + width: 5, + height: 2, + data: [ + 0x000000ff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff, + 0xdfdfdfff, 0xdfdfdfff, 0xdfdfdfff, 0x202020ff, 0x202020ff, + ], + }, + "BEZIER 5x2": { + width: 5, + height: 2, + data: [ + 0x000000ff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff, + 0xdfdfdfff, 0xdfdfdfff, 0xdfdfdfff, 0x202020ff, 0x202020ff, + ], + }, + }, + }, + /**********************************************************************/ + { + title: "max contrast 12x12 with dots", + src: jimp.read( + mkJGD( + "■■■■■■□□□□□□", + "■■■■■■□□□□□□", + "■■■□■■□□■□□□", + "■■■■■■□□□□□□", + "■■■■■■□□□□□□", + "■■■■■■□□□□□□", + "□□□□□□■■■■■■", + "□□□□□□■■■■■■", + "□□□□□□■■■■■■", + "□□□■□□■■□■■■", + "□□□□□□■■■■■■", + "□□□□□□■■■■■■" + ) + ), + results: { + "default 6x6": mkJGD( + "■■■□□□", + "■▩■□▥□", + "■■■□□□", + "□□□■■■", + "□▥□■▩■", + "□□□■■■" + ), + "NEAREST_NEIGHBOR 6x6": mkJGD( + "■■■□□□", + "■■■□■□", + "■■■□□□", + "□□□■■■", + "□□□■■■", + "□□□■■■" + ), + "BILINEAR 6x6": mkJGD( + "■■■□□□", + "■■■□■□", + "■■■□□□", + "□□□■■■", + "□□□■■■", + "□□□■■■" + ), + "BICUBIC 6x6": { + width: 6, + height: 6, + data: [ + 0x000000ff, 0x000000ff, 0x000000ff, 0xbfbfbfff, 0xffffffff, + 0xffffffff, 0x000000ff, 0x474747ff, 0x202020ff, 0xbfbfbfff, + 0x979797ff, 0xffffffff, 0x000000ff, 0x000000ff, 0x000000ff, + 0xbfbfbfff, 0xffffffff, 0xffffffff, 0xbfbfbfff, 0xbfbfbfff, + 0xbfbfbfff, 0x5f5f5fff, 0x404040ff, 0x404040ff, 0xffffffff, + 0xeeeeeeff, 0xf7f7f7ff, 0x404040ff, 0x181818ff, 0x000000ff, + 0xffffffff, 0xc9c9c9ff, 0xe6e6e6ff, 0x404040ff, 0x4e4e4eff, + 0x000000ff, + ], + }, + "HERMITE 6x6": { + width: 6, + height: 6, + data: [ + 0x000000ff, 0x000000ff, 0x000000ff, 0xc0c0c0ff, 0xffffffff, + 0xffffffff, 0x000000ff, 0x404040ff, 0x191919ff, 0xc0c0c0ff, + 0xa6a6a6ff, 0xffffffff, 0x000000ff, 0x000000ff, 0x000000ff, + 0xc0c0c0ff, 0xffffffff, 0xffffffff, 0xc0c0c0ff, 0xc0c0c0ff, + 0xc0c0c0ff, 0x606060ff, 0x404040ff, 0x404040ff, 0xffffffff, + 0xf3f3f3ff, 0xfafafaff, 0x404040ff, 0x111111ff, 0x000000ff, + 0xffffffff, 0xcbcbcbff, 0xebebebff, 0x404040ff, 0x484848ff, + 0x000000ff, + ], + }, + "BEZIER 6x6": { + width: 6, + height: 6, + data: [ + 0x000000ff, 0x000000ff, 0x000000ff, 0xc0c0c0ff, 0xffffffff, + 0xffffffff, 0x000000ff, 0x444444ff, 0x1d1d1dff, 0xc0c0c0ff, + 0x9f9f9fff, 0xffffffff, 0x000000ff, 0x000000ff, 0x000000ff, + 0xc0c0c0ff, 0xffffffff, 0xffffffff, 0xc0c0c0ff, 0xc0c0c0ff, + 0xc0c0c0ff, 0x606060ff, 0x404040ff, 0x404040ff, 0xffffffff, + 0xf0f0f0ff, 0xf9f9f9ff, 0x404040ff, 0x151515ff, 0x000000ff, + 0xffffffff, 0xcacacaff, 0xe9e9e9ff, 0x404040ff, 0x4b4b4bff, + 0x000000ff, + ], + }, + }, + }, + /**********************************************************************/ + { + title: "mutch contrast 4x4", + src: jimp.read(mkJGD("▩▩▥▥", "▩▩▥▥", "▥▥▩▩", "▥▥▩▩")), + results: { + "default 6x6": { + width: 6, + height: 6, + data: [ + 0x404040ff, 0x404040ff, 0x404040ff, 0x959595ff, 0xbfbfbfff, + 0xbfbfbfff, 0x404040ff, 0x404040ff, 0x404040ff, 0x959595ff, + 0xbfbfbfff, 0xbfbfbfff, 0x404040ff, 0x404040ff, 0x404040ff, + 0x959595ff, 0xbfbfbfff, 0xbfbfbfff, 0x959595ff, 0x959595ff, + 0x959595ff, 0x787878ff, 0x6a6a6aff, 0x6a6a6aff, 0xbfbfbfff, + 0xbfbfbfff, 0xbfbfbfff, 0x6a6a6aff, 0x404040ff, 0x404040ff, + 0xbfbfbfff, 0xbfbfbfff, 0xbfbfbfff, 0x6a6a6aff, 0x404040ff, + 0x404040ff, + ], + }, + "NEAREST_NEIGHBOR 6x6": { + width: 6, + height: 6, + data: [ + 0x404040ff, 0x404040ff, 0x404040ff, 0xbfbfbfff, 0xbfbfbfff, + 0xbfbfbfff, 0x404040ff, 0x404040ff, 0x404040ff, 0xbfbfbfff, + 0xbfbfbfff, 0xbfbfbfff, 0x404040ff, 0x404040ff, 0x404040ff, + 0xbfbfbfff, 0xbfbfbfff, 0xbfbfbfff, 0xbfbfbfff, 0xbfbfbfff, + 0xbfbfbfff, 0x404040ff, 0x404040ff, 0x404040ff, 0xbfbfbfff, + 0xbfbfbfff, 0xbfbfbfff, 0x404040ff, 0x404040ff, 0x404040ff, + 0xbfbfbfff, 0xbfbfbfff, 0xbfbfbfff, 0x404040ff, 0x404040ff, + 0x404040ff, + ], + }, + "BILINEAR 6x6": { + width: 6, + height: 6, + data: [ + 0x404040ff, 0x404040ff, 0x6a6a6aff, 0xbfbfbfff, 0xbfbfbfff, + 0xbfbfbfff, 0x404040ff, 0x404040ff, 0x6a6a6aff, 0xbfbfbfff, + 0xbfbfbfff, 0xbfbfbfff, 0x6a6a6aff, 0x6a6a6aff, 0x787878ff, + 0x959595ff, 0x959595ff, 0x959595ff, 0xbfbfbfff, 0xbfbfbfff, + 0x959595ff, 0x404040ff, 0x404040ff, 0x404040ff, 0xbfbfbfff, + 0xbfbfbfff, 0x959595ff, 0x404040ff, 0x404040ff, 0x404040ff, + 0xbfbfbfff, 0xbfbfbfff, 0x959595ff, 0x404040ff, 0x404040ff, + 0x404040ff, + ], + }, + "BICUBIC 6x6": { + width: 6, + height: 6, + data: [ + 0x404040ff, 0x303030ff, 0x404040ff, 0x7f7f7fff, 0xbfbfbfff, + 0xcececeff, 0x303030ff, 0x1c1c1cff, 0x303030ff, 0x7f7f7fff, + 0xcececeff, 0xe1e1e1ff, 0x404040ff, 0x303030ff, 0x404040ff, + 0x7f7f7fff, 0xbfbfbfff, 0xcececeff, 0x7f7f7fff, 0x7f7f7fff, + 0x7f7f7fff, 0x7f7f7fff, 0x7f7f7fff, 0x7f7f7fff, 0xbfbfbfff, + 0xcececeff, 0xbfbfbfff, 0x7f7f7fff, 0x404040ff, 0x303030ff, + 0xcececeff, 0xe1e1e1ff, 0xcececeff, 0x7f7f7fff, 0x303030ff, + 0x1c1c1cff, + ], + }, + "HERMITE 6x6": { + width: 6, + height: 6, + data: [ + 0x404040ff, 0x383838ff, 0x404040ff, 0x808080ff, 0xbfbfbfff, + 0xc7c7c7ff, 0x383838ff, 0x2f2f2fff, 0x383838ff, 0x808080ff, + 0xc7c7c7ff, 0xd0d0d0ff, 0x404040ff, 0x383838ff, 0x404040ff, + 0x808080ff, 0xbfbfbfff, 0xc7c7c7ff, 0x808080ff, 0x808080ff, + 0x808080ff, 0x808080ff, 0x808080ff, 0x808080ff, 0xbfbfbfff, + 0xc7c7c7ff, 0xbfbfbfff, 0x808080ff, 0x404040ff, 0x383838ff, + 0xc7c7c7ff, 0xd0d0d0ff, 0xc7c7c7ff, 0x808080ff, 0x383838ff, + 0x2f2f2fff, + ], + }, + "BEZIER 6x6": { + width: 6, + height: 6, + data: [ + 0x404040ff, 0x343434ff, 0x404040ff, 0x808080ff, 0xbfbfbfff, + 0xcbcbcbff, 0x343434ff, 0x262626ff, 0x343434ff, 0x808080ff, + 0xcbcbcbff, 0xd9d9d9ff, 0x404040ff, 0x343434ff, 0x404040ff, + 0x808080ff, 0xbfbfbfff, 0xcbcbcbff, 0x808080ff, 0x808080ff, + 0x808080ff, 0x808080ff, 0x808080ff, 0x808080ff, 0xbfbfbfff, + 0xcbcbcbff, 0xbfbfbfff, 0x808080ff, 0x404040ff, 0x343434ff, + 0xcbcbcbff, 0xd9d9d9ff, 0xcbcbcbff, 0x808080ff, 0x343434ff, + 0x262626ff, + ], + }, + }, + }, + ]; + + before((done) => { + const srcImgs = testImages.map((test) => test.src); + Promise.all(srcImgs) + .then((imgsJimp) => { + for (let i = 0; i < imgsJimp.length; i++) { + testImages[i].src = imgsJimp[i]; + } + + done(); + }) + .catch(done); + }); + + function testEach(test) { + describe(test.title, () => { + hashForEach(test.results, (expectedTitle, expectedJgd) => { + const mode = Jimp["RESIZE_" + expectedTitle.split(" ")[0]]; + const size = expectedTitle + .split(" ")[1] + .split("x") + .map((n) => parseInt(n, 10)); + it("to " + expectedTitle, () => { + expectToBeJGD( + test.src.clone().resize(size[0], size[1], mode).getJGDSync(), + expectedJgd + ); + }); + }); + }); + } + + testImages.forEach(testEach); +}); diff --git a/node_modules/@jimp/plugin-rotate/CHANGELOG.md b/node_modules/@jimp/plugin-rotate/CHANGELOG.md new file mode 100644 index 00000000..fff0ee5b --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/CHANGELOG.md @@ -0,0 +1,133 @@ +# v0.22.8 (Thu May 11 2023) + +#### 🚀 Enhancement + +- Fix: rotate resize param on multiples of 90 [#1229](https://github.com/jimp-dev/jimp/pull/1229) ([@sjoerd108](https://github.com/sjoerd108)) + +#### Authors: 1 + +- Sjoerd ([@sjoerd108](https://github.com/sjoerd108)) + +--- + +# v0.22.7 (Sat Feb 25 2023) + +:tada: This release contains work from a new contributor! :tada: + +Thank you, MD KHAIRUL ISLAM ([@black-turtle](https://github.com/black-turtle)), for all your work! + +### Release Notes + +#### use matrix rotate, if rotate angle is multiple of 90 degrees ([#1209](https://github.com/jimp-dev/jimp/pull/1209)) + +Fixes a bug where rotating by 90 degrees introduced extra pixels + +--- + +#### 🐛 Bug Fix + +- use matrix rotate, if rotate angle is multiple of 90 degrees [#1209](https://github.com/jimp-dev/jimp/pull/1209) ([@black-turtle](https://github.com/black-turtle)) + +#### Authors: 1 + +- MD KHAIRUL ISLAM ([@black-turtle](https://github.com/black-turtle)) + +--- + +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.17.6 (Sat Feb 04 2023) + +#### 🐛 Bug Fix + +- fix documentation about rotation direction. [#1062](https://github.com/jimp-dev/jimp/pull/1062) ([@fabb](https://github.com/fabb)) + +#### Authors: 1 + +- [@fabb](https://github.com/fabb) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-rotate/LICENSE b/node_modules/@jimp/plugin-rotate/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-rotate/README.md b/node_modules/@jimp/plugin-rotate/README.md new file mode 100644 index 00000000..510fea5c --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/README.md @@ -0,0 +1,26 @@ +
+ +

@jimp/plugin-rotate

+

Rotate an image.

+
+ +Rotates the image counter-clockwise by a number of degrees. By default the width and height of the image will be resized appropriately. + +## Usage + +- @param {number} deg the number of degrees to rotate the image by, counter-clockwise +- @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.rotate(90); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-rotate/es/index.js b/node_modules/@jimp/plugin-rotate/es/index.js new file mode 100644 index 00000000..396a9a67 --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/es/index.js @@ -0,0 +1,196 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Rotates an image counter-clockwise by multiple of 90 degrees. NB: 'this' must be a Jimp object. + * + * This function is based on matrix rotation. Check this to get an initial idea how it works: https://stackoverflow.com/a/8664879/10561909 + * + * @param {number} deg the number of degrees to rotate the image by, it should be a multiple of 90 + */ +function matrixRotate(deg) { + if (Math.abs(deg) % 90 !== 0) { + throw new Error("Unsupported matrix rotation degree"); + } + deg %= 360; + if (Math.abs(deg) === 0) { + // no rotation for 0, 360, -360, 720, -720, ... + return; + } + const w = this.bitmap.width; + const h = this.bitmap.height; + + // decide which rotation angle to use + let angle; + switch (deg) { + // 90 degree & -270 degree are same + case 90: + case -270: + angle = 90; + break; + case 180: + case -180: + angle = 180; + break; + case 270: + case -90: + angle = -90; + break; + default: + throw new Error("Unsupported matrix rotation degree"); + } + // After this switch block, angle will be 90, 180 or -90 + + // calculate the new width and height + const nW = angle === 180 ? w : h; + const nH = angle === 180 ? h : w; + const dstBuffer = Buffer.alloc(this.bitmap.data.length); + + // function to translate the x, y coordinate to the index of the pixel in the buffer + function createIdxTranslationFunction(w, h) { + return function (x, y) { + return y * w + x << 2; + }; + } + const srcIdxFunction = createIdxTranslationFunction(w, h); + const dstIdxFunction = createIdxTranslationFunction(nW, nH); + for (let x = 0; x < w; x++) { + for (let y = 0; y < h; y++) { + const srcIdx = srcIdxFunction(x, y); + const pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx); + let dstIdx; + switch (angle) { + case 90: + dstIdx = dstIdxFunction(y, w - x - 1); + break; + case -90: + dstIdx = dstIdxFunction(h - y - 1, x); + break; + case 180: + dstIdx = dstIdxFunction(w - x - 1, h - y - 1); + break; + default: + throw new Error("Unsupported matrix rotation angle"); + } + dstBuffer.writeUInt32BE(pixelRGBA, dstIdx); + } + } + this.bitmap.data = dstBuffer; + this.bitmap.width = nW; + this.bitmap.height = nH; +} + +/** + * Rotates an image counter-clockwise by an arbitrary number of degrees. NB: 'this' must be a Jimp object. + * @param {number} deg the number of degrees to rotate the image by + * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed + */ +function advancedRotate(deg, mode) { + deg %= 360; + const rad = deg * Math.PI / 180; + const cosine = Math.cos(rad); + const sine = Math.sin(rad); + + // the final width and height will change if resize == true + let w = this.bitmap.width; + let h = this.bitmap.height; + if (mode === true || typeof mode === "string") { + // resize the image to it maximum dimension and blit the existing image + // onto the center so that when it is rotated the image is kept in bounds + + // http://stackoverflow.com/questions/3231176/how-to-get-size-of-a-rotated-rectangle + // Plus 1 border pixel to ensure to show all rotated result for some cases. + w = Math.ceil(Math.abs(this.bitmap.width * cosine) + Math.abs(this.bitmap.height * sine)) + 1; + h = Math.ceil(Math.abs(this.bitmap.width * sine) + Math.abs(this.bitmap.height * cosine)) + 1; + // Ensure destination to have even size to a better result. + if (w % 2 !== 0) { + w++; + } + if (h % 2 !== 0) { + h++; + } + const c = this.cloneQuiet(); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data.writeUInt32BE(this._background, idx); + }); + const max = Math.max(w, h, this.bitmap.width, this.bitmap.height); + this.resize(max, max, mode); + this.blit(c, this.bitmap.width / 2 - c.bitmap.width / 2, this.bitmap.height / 2 - c.bitmap.height / 2); + } + const bW = this.bitmap.width; + const bH = this.bitmap.height; + const dstBuffer = Buffer.alloc(this.bitmap.data.length); + function createTranslationFunction(deltaX, deltaY) { + return function (x, y) { + return { + x: x + deltaX, + y: y + deltaY + }; + }; + } + const translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2)); + const translate2Screen = createTranslationFunction(bW / 2 + 0.5, bH / 2 + 0.5); + for (let y = 1; y <= bH; y++) { + for (let x = 1; x <= bW; x++) { + const cartesian = translate2Cartesian(x, y); + const source = translate2Screen(cosine * cartesian.x - sine * cartesian.y, cosine * cartesian.y + sine * cartesian.x); + const dstIdx = bW * (y - 1) + x - 1 << 2; + if (source.x >= 0 && source.x < bW && source.y >= 0 && source.y < bH) { + const srcIdx = (bW * (source.y | 0) + source.x | 0) << 2; + const pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx); + dstBuffer.writeUInt32BE(pixelRGBA, dstIdx); + } else { + // reset off-image pixels + dstBuffer.writeUInt32BE(this._background, dstIdx); + } + } + } + this.bitmap.data = dstBuffer; + if (mode === true || typeof mode === "string") { + // now crop the image to the final size + const x = bW / 2 - w / 2; + const y = bH / 2 - h / 2; + this.crop(x, y, w, h); + } +} +export default (() => ({ + /** + * Rotates the image counter-clockwise by a number of degrees. By default the width and height of the image will be resized appropriately. + * @param {number} deg the number of degrees to rotate the image by + * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + rotate(deg, mode, cb) { + // enable overloading + if (typeof mode === "undefined" || mode === null) { + // e.g. image.resize(120); + // e.g. image.resize(120, null, cb); + // e.g. image.resize(120, undefined, cb); + mode = true; + } + if (typeof mode === "function" && typeof cb === "undefined") { + // e.g. image.resize(120, cb); + cb = mode; + mode = true; + } + if (typeof deg !== "number") { + return throwError.call(this, "deg must be a number", cb); + } + if (typeof mode !== "boolean" && typeof mode !== "string") { + return throwError.call(this, "mode must be a boolean or a string", cb); + } + + // use matrixRotate if the angle is a multiple of 90 degrees (eg: 180 or -90) and resize is allowed or not needed. + const matrixRotateAllowed = deg % 90 === 0 && (mode || this.bitmap.width === this.bitmap.height || deg % 180 === 0); + if (matrixRotateAllowed) { + matrixRotate.call(this, deg); + } else { + advancedRotate.call(this, deg, mode, cb); + } + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-rotate/es/index.js.map b/node_modules/@jimp/plugin-rotate/es/index.js.map new file mode 100644 index 00000000..79faf103 --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","matrixRotate","deg","Math","abs","Error","w","bitmap","width","h","height","angle","nW","nH","dstBuffer","Buffer","alloc","data","length","createIdxTranslationFunction","x","y","srcIdxFunction","dstIdxFunction","srcIdx","pixelRGBA","readUInt32BE","dstIdx","writeUInt32BE","advancedRotate","mode","rad","PI","cosine","cos","sine","sin","ceil","c","cloneQuiet","scanQuiet","idx","_background","max","resize","blit","bW","bH","createTranslationFunction","deltaX","deltaY","translate2Cartesian","translate2Screen","cartesian","source","crop","rotate","cb","call","matrixRotateAllowed"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Rotates an image counter-clockwise by multiple of 90 degrees. NB: 'this' must be a Jimp object.\n *\n * This function is based on matrix rotation. Check this to get an initial idea how it works: https://stackoverflow.com/a/8664879/10561909\n *\n * @param {number} deg the number of degrees to rotate the image by, it should be a multiple of 90\n */\nfunction matrixRotate(deg) {\n if (Math.abs(deg) % 90 !== 0) {\n throw new Error(\"Unsupported matrix rotation degree\");\n }\n\n deg %= 360;\n if (Math.abs(deg) === 0) {\n // no rotation for 0, 360, -360, 720, -720, ...\n return;\n }\n\n const w = this.bitmap.width;\n const h = this.bitmap.height;\n\n // decide which rotation angle to use\n let angle;\n switch (deg) {\n // 90 degree & -270 degree are same\n case 90:\n case -270:\n angle = 90;\n break;\n\n case 180:\n case -180:\n angle = 180;\n break;\n\n case 270:\n case -90:\n angle = -90;\n break;\n\n default:\n throw new Error(\"Unsupported matrix rotation degree\");\n }\n // After this switch block, angle will be 90, 180 or -90\n\n // calculate the new width and height\n const nW = angle === 180 ? w : h;\n const nH = angle === 180 ? h : w;\n\n const dstBuffer = Buffer.alloc(this.bitmap.data.length);\n\n // function to translate the x, y coordinate to the index of the pixel in the buffer\n function createIdxTranslationFunction(w, h) {\n return function (x, y) {\n return (y * w + x) << 2;\n };\n }\n\n const srcIdxFunction = createIdxTranslationFunction(w, h);\n const dstIdxFunction = createIdxTranslationFunction(nW, nH);\n\n for (let x = 0; x < w; x++) {\n for (let y = 0; y < h; y++) {\n const srcIdx = srcIdxFunction(x, y);\n const pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx);\n\n let dstIdx;\n switch (angle) {\n case 90:\n dstIdx = dstIdxFunction(y, w - x - 1);\n break;\n case -90:\n dstIdx = dstIdxFunction(h - y - 1, x);\n break;\n case 180:\n dstIdx = dstIdxFunction(w - x - 1, h - y - 1);\n break;\n default:\n throw new Error(\"Unsupported matrix rotation angle\");\n }\n\n dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);\n }\n }\n\n this.bitmap.data = dstBuffer;\n this.bitmap.width = nW;\n this.bitmap.height = nH;\n}\n\n/**\n * Rotates an image counter-clockwise by an arbitrary number of degrees. NB: 'this' must be a Jimp object.\n * @param {number} deg the number of degrees to rotate the image by\n * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed\n */\nfunction advancedRotate(deg, mode) {\n deg %= 360;\n const rad = (deg * Math.PI) / 180;\n const cosine = Math.cos(rad);\n const sine = Math.sin(rad);\n\n // the final width and height will change if resize == true\n let w = this.bitmap.width;\n let h = this.bitmap.height;\n\n if (mode === true || typeof mode === \"string\") {\n // resize the image to it maximum dimension and blit the existing image\n // onto the center so that when it is rotated the image is kept in bounds\n\n // http://stackoverflow.com/questions/3231176/how-to-get-size-of-a-rotated-rectangle\n // Plus 1 border pixel to ensure to show all rotated result for some cases.\n w =\n Math.ceil(\n Math.abs(this.bitmap.width * cosine) +\n Math.abs(this.bitmap.height * sine)\n ) + 1;\n h =\n Math.ceil(\n Math.abs(this.bitmap.width * sine) +\n Math.abs(this.bitmap.height * cosine)\n ) + 1;\n // Ensure destination to have even size to a better result.\n if (w % 2 !== 0) {\n w++;\n }\n\n if (h % 2 !== 0) {\n h++;\n }\n\n const c = this.cloneQuiet();\n this.scanQuiet(\n 0,\n 0,\n this.bitmap.width,\n this.bitmap.height,\n function (x, y, idx) {\n this.bitmap.data.writeUInt32BE(this._background, idx);\n }\n );\n\n const max = Math.max(w, h, this.bitmap.width, this.bitmap.height);\n this.resize(max, max, mode);\n\n this.blit(\n c,\n this.bitmap.width / 2 - c.bitmap.width / 2,\n this.bitmap.height / 2 - c.bitmap.height / 2\n );\n }\n\n const bW = this.bitmap.width;\n const bH = this.bitmap.height;\n const dstBuffer = Buffer.alloc(this.bitmap.data.length);\n\n function createTranslationFunction(deltaX, deltaY) {\n return function (x, y) {\n return {\n x: x + deltaX,\n y: y + deltaY,\n };\n };\n }\n\n const translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2));\n const translate2Screen = createTranslationFunction(\n bW / 2 + 0.5,\n bH / 2 + 0.5\n );\n\n for (let y = 1; y <= bH; y++) {\n for (let x = 1; x <= bW; x++) {\n const cartesian = translate2Cartesian(x, y);\n const source = translate2Screen(\n cosine * cartesian.x - sine * cartesian.y,\n cosine * cartesian.y + sine * cartesian.x\n );\n const dstIdx = (bW * (y - 1) + x - 1) << 2;\n\n if (source.x >= 0 && source.x < bW && source.y >= 0 && source.y < bH) {\n const srcIdx = ((bW * (source.y | 0) + source.x) | 0) << 2;\n const pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx);\n dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);\n } else {\n // reset off-image pixels\n dstBuffer.writeUInt32BE(this._background, dstIdx);\n }\n }\n }\n\n this.bitmap.data = dstBuffer;\n\n if (mode === true || typeof mode === \"string\") {\n // now crop the image to the final size\n const x = bW / 2 - w / 2;\n const y = bH / 2 - h / 2;\n this.crop(x, y, w, h);\n }\n}\n\nexport default () => ({\n /**\n * Rotates the image counter-clockwise by a number of degrees. By default the width and height of the image will be resized appropriately.\n * @param {number} deg the number of degrees to rotate the image by\n * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n rotate(deg, mode, cb) {\n // enable overloading\n if (typeof mode === \"undefined\" || mode === null) {\n // e.g. image.resize(120);\n // e.g. image.resize(120, null, cb);\n // e.g. image.resize(120, undefined, cb);\n mode = true;\n }\n\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n // e.g. image.resize(120, cb);\n cb = mode;\n mode = true;\n }\n\n if (typeof deg !== \"number\") {\n return throwError.call(this, \"deg must be a number\", cb);\n }\n\n if (typeof mode !== \"boolean\" && typeof mode !== \"string\") {\n return throwError.call(this, \"mode must be a boolean or a string\", cb);\n }\n\n // use matrixRotate if the angle is a multiple of 90 degrees (eg: 180 or -90) and resize is allowed or not needed.\n const matrixRotateAllowed =\n deg % 90 === 0 &&\n (mode || this.bitmap.width === this.bitmap.height || deg % 180 === 0);\n\n if (matrixRotateAllowed) {\n matrixRotate.call(this, deg);\n } else {\n advancedRotate.call(this, deg, mode, cb);\n }\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;;AAEvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,YAAY,CAACC,GAAG,EAAE;EACzB,IAAIC,IAAI,CAACC,GAAG,CAACF,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE;IAC5B,MAAM,IAAIG,KAAK,CAAC,oCAAoC,CAAC;EACvD;EAEAH,GAAG,IAAI,GAAG;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F,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-rotate/index.d.ts b/node_modules/@jimp/plugin-rotate/index.d.ts new file mode 100644 index 00000000..23d2aa2f --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/index.d.ts @@ -0,0 +1,8 @@ +import { ImageCallback } from "@jimp/core"; + +interface Rotate { + rotate(deg: number, cb?: ImageCallback): this; + rotate(deg: number, mode: string | boolean, cb?: ImageCallback): this; +} + +export default function (): Rotate; diff --git a/node_modules/@jimp/plugin-rotate/package.json b/node_modules/@jimp/plugin-rotate/package.json new file mode 100644 index 00000000..651f0264 --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/package.json @@ -0,0 +1,43 @@ +{ + "name": "@jimp/plugin-rotate", + "version": "0.22.12", + "description": "Rotate an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-blit": ">=0.3.5", + "@jimp/plugin-crop": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/plugin-blit": "^0.22.12", + "@jimp/plugin-crop": "^0.22.12", + "@jimp/plugin-resize": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-rotate/src/index.js b/node_modules/@jimp/plugin-rotate/src/index.js new file mode 100644 index 00000000..7f430bae --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/src/index.js @@ -0,0 +1,251 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Rotates an image counter-clockwise by multiple of 90 degrees. NB: 'this' must be a Jimp object. + * + * This function is based on matrix rotation. Check this to get an initial idea how it works: https://stackoverflow.com/a/8664879/10561909 + * + * @param {number} deg the number of degrees to rotate the image by, it should be a multiple of 90 + */ +function matrixRotate(deg) { + if (Math.abs(deg) % 90 !== 0) { + throw new Error("Unsupported matrix rotation degree"); + } + + deg %= 360; + if (Math.abs(deg) === 0) { + // no rotation for 0, 360, -360, 720, -720, ... + return; + } + + const w = this.bitmap.width; + const h = this.bitmap.height; + + // decide which rotation angle to use + let angle; + switch (deg) { + // 90 degree & -270 degree are same + case 90: + case -270: + angle = 90; + break; + + case 180: + case -180: + angle = 180; + break; + + case 270: + case -90: + angle = -90; + break; + + default: + throw new Error("Unsupported matrix rotation degree"); + } + // After this switch block, angle will be 90, 180 or -90 + + // calculate the new width and height + const nW = angle === 180 ? w : h; + const nH = angle === 180 ? h : w; + + const dstBuffer = Buffer.alloc(this.bitmap.data.length); + + // function to translate the x, y coordinate to the index of the pixel in the buffer + function createIdxTranslationFunction(w, h) { + return function (x, y) { + return (y * w + x) << 2; + }; + } + + const srcIdxFunction = createIdxTranslationFunction(w, h); + const dstIdxFunction = createIdxTranslationFunction(nW, nH); + + for (let x = 0; x < w; x++) { + for (let y = 0; y < h; y++) { + const srcIdx = srcIdxFunction(x, y); + const pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx); + + let dstIdx; + switch (angle) { + case 90: + dstIdx = dstIdxFunction(y, w - x - 1); + break; + case -90: + dstIdx = dstIdxFunction(h - y - 1, x); + break; + case 180: + dstIdx = dstIdxFunction(w - x - 1, h - y - 1); + break; + default: + throw new Error("Unsupported matrix rotation angle"); + } + + dstBuffer.writeUInt32BE(pixelRGBA, dstIdx); + } + } + + this.bitmap.data = dstBuffer; + this.bitmap.width = nW; + this.bitmap.height = nH; +} + +/** + * Rotates an image counter-clockwise by an arbitrary number of degrees. NB: 'this' must be a Jimp object. + * @param {number} deg the number of degrees to rotate the image by + * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed + */ +function advancedRotate(deg, mode) { + deg %= 360; + const rad = (deg * Math.PI) / 180; + const cosine = Math.cos(rad); + const sine = Math.sin(rad); + + // the final width and height will change if resize == true + let w = this.bitmap.width; + let h = this.bitmap.height; + + if (mode === true || typeof mode === "string") { + // resize the image to it maximum dimension and blit the existing image + // onto the center so that when it is rotated the image is kept in bounds + + // http://stackoverflow.com/questions/3231176/how-to-get-size-of-a-rotated-rectangle + // Plus 1 border pixel to ensure to show all rotated result for some cases. + w = + Math.ceil( + Math.abs(this.bitmap.width * cosine) + + Math.abs(this.bitmap.height * sine) + ) + 1; + h = + Math.ceil( + Math.abs(this.bitmap.width * sine) + + Math.abs(this.bitmap.height * cosine) + ) + 1; + // Ensure destination to have even size to a better result. + if (w % 2 !== 0) { + w++; + } + + if (h % 2 !== 0) { + h++; + } + + const c = this.cloneQuiet(); + this.scanQuiet( + 0, + 0, + this.bitmap.width, + this.bitmap.height, + function (x, y, idx) { + this.bitmap.data.writeUInt32BE(this._background, idx); + } + ); + + const max = Math.max(w, h, this.bitmap.width, this.bitmap.height); + this.resize(max, max, mode); + + this.blit( + c, + this.bitmap.width / 2 - c.bitmap.width / 2, + this.bitmap.height / 2 - c.bitmap.height / 2 + ); + } + + const bW = this.bitmap.width; + const bH = this.bitmap.height; + const dstBuffer = Buffer.alloc(this.bitmap.data.length); + + function createTranslationFunction(deltaX, deltaY) { + return function (x, y) { + return { + x: x + deltaX, + y: y + deltaY, + }; + }; + } + + const translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2)); + const translate2Screen = createTranslationFunction( + bW / 2 + 0.5, + bH / 2 + 0.5 + ); + + for (let y = 1; y <= bH; y++) { + for (let x = 1; x <= bW; x++) { + const cartesian = translate2Cartesian(x, y); + const source = translate2Screen( + cosine * cartesian.x - sine * cartesian.y, + cosine * cartesian.y + sine * cartesian.x + ); + const dstIdx = (bW * (y - 1) + x - 1) << 2; + + if (source.x >= 0 && source.x < bW && source.y >= 0 && source.y < bH) { + const srcIdx = ((bW * (source.y | 0) + source.x) | 0) << 2; + const pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx); + dstBuffer.writeUInt32BE(pixelRGBA, dstIdx); + } else { + // reset off-image pixels + dstBuffer.writeUInt32BE(this._background, dstIdx); + } + } + } + + this.bitmap.data = dstBuffer; + + if (mode === true || typeof mode === "string") { + // now crop the image to the final size + const x = bW / 2 - w / 2; + const y = bH / 2 - h / 2; + this.crop(x, y, w, h); + } +} + +export default () => ({ + /** + * Rotates the image counter-clockwise by a number of degrees. By default the width and height of the image will be resized appropriately. + * @param {number} deg the number of degrees to rotate the image by + * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + rotate(deg, mode, cb) { + // enable overloading + if (typeof mode === "undefined" || mode === null) { + // e.g. image.resize(120); + // e.g. image.resize(120, null, cb); + // e.g. image.resize(120, undefined, cb); + mode = true; + } + + if (typeof mode === "function" && typeof cb === "undefined") { + // e.g. image.resize(120, cb); + cb = mode; + mode = true; + } + + if (typeof deg !== "number") { + return throwError.call(this, "deg must be a number", cb); + } + + if (typeof mode !== "boolean" && typeof mode !== "string") { + return throwError.call(this, "mode must be a boolean or a string", cb); + } + + // use matrixRotate if the angle is a multiple of 90 degrees (eg: 180 or -90) and resize is allowed or not needed. + const matrixRotateAllowed = + deg % 90 === 0 && + (mode || this.bitmap.width === this.bitmap.height || deg % 180 === 0); + + if (matrixRotateAllowed) { + matrixRotate.call(this, deg); + } else { + advancedRotate.call(this, deg, mode, cb); + } + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-rotate/test/rotation.test.js b/node_modules/@jimp/plugin-rotate/test/rotation.test.js new file mode 100644 index 00000000..45ee8d2b --- /dev/null +++ b/node_modules/@jimp/plugin-rotate/test/rotation.test.js @@ -0,0 +1,610 @@ +import { Jimp, mkJGD } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import blit from "@jimp/plugin-blit"; +import crop from "@jimp/plugin-crop"; +import resize from "@jimp/plugin-resize"; + +import rotate from "../src"; +import { expectToBeJGD } from "@jimp/test-utils/src"; + +const jimp = configure({ plugins: [rotate, blit, crop, resize] }, Jimp); + +describe("Rotate a image with even size", () => { + let imgSrc = null; + + before((done) => { + jimp + .read( + mkJGD( + "▰▴▴▴▪▪▪▰", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▦▪▪▪▴▴▴▦" + ) + ) + .then((imgJimp) => { + imgSrc = imgJimp; + done(); + }) + .catch(done); + }); + + it("1 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(1, true).getJGDSync(), + mkJGD( + "▰▴▴▴▪▪▪▰ ", + "▴▴▴▴▪▪▪▪ ", + "▴▴▴▴▪▪▪▪ ", + "▴▴▴▴▪▪▪▪ ", + "▪▪▪▪▴▴▴▴ ", + "▪▪▪▪▴▴▴▴ ", + "▪▪▪▪▴▴▴▴ ", + "▦▪▪▪▴▴▴▦ ", + " ", + " " + ) + ); + }); + + it("91 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(91, true).getJGDSync(), + mkJGD( + " ", + "▰▪▪▪▴▴▴▦ ", + "▪▪▪▪▴▴▴▴ ", + "▪▪▪▪▴▴▴▴ ", + "▪▪▪▪▴▴▴▴ ", + "▴▴▴▴▪▪▪▪ ", + "▴▴▴▴▪▪▪▪ ", + "▴▴▴▴▪▪▪▪ ", + "▰▴▴▴▪▪▪▦ ", + " " + ) + ); + }); + + it("30 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(30, true).getJGDSync(), + mkJGD( + " ▰▰ ", + " ▪▪▪▪ ", + " ▴▪▪▪▪▪ ", + "▴▴▴▴▪▪▪▪ ", + "▴▴▴▴▪▪▴▴▴ ", + "▴▴▴▴▪▴▴▴▴▴ ", + " ▴▴▪▪▴▴▴▴▦ ", + " ▪▪▪▪▪▴▴▴ ", + " ▪▪▪▪▪ ", + " ▪▪▪ ", + " ▦ ", + " " + ) + ); + }); + + it("45 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(45, true).getJGDSync(), + mkJGD( + " ", + " ▰ ", + " ▪▪▪ ", + " ▪▪▪▪▪ ", + " ▴▴▪▪▪▪▴ ", + " ▴▴▴▴▪▪▴▴▴ ", + "▰▰▴▴▴▴▴▴▴▴▦ ", + " ▴▴▴▴▪▪▴▴▴ ", + " ▴▴▪▪▪▪▴ ", + " ▪▪▪▪▪ ", + " ▪▪▪ ", + " ▦ ", + " ", + " " + ) + ); + }); + + it("60 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(60, true).getJGDSync(), + mkJGD( + " ▰ ", + " ▪▪▪ ", + " ▪▪▪▪▪ ", + " ▪▪▪▪▪▴▴▴ ", + " ▴▴▪▪▴▴▴▴▦ ", + "▴▴▴▴▪▴▴▴▴▴ ", + "▴▴▴▴▪▪▴▴▴ ", + "▴▴▴▴▪▪▪▪ ", + " ▴▪▪▪▪▪ ", + " ▪▪▪▪ ", + " ▦▦ ", + " " + ) + ); + }); + + it("90 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(90, true).getJGDSync(), + mkJGD( + "▰▪▪▪▴▴▴▦", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▰▴▴▴▪▪▪▦" + ) + ); + }); + + it("-90 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(-90, true).getJGDSync(), + mkJGD( + "▦▪▪▪▴▴▴▰", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▦▴▴▴▪▪▪▰" + ) + ); + }); + + it("120 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(120, true).getJGDSync(), + mkJGD( + " ", + " ▴▦ ", + " ▴▴▴▴ ", + " ▪▪▴▴▴▴ ", + "▰▪▪▪▴▴▴▴▪ ", + "▰▪▪▪▪▴▴▪▪▪ ", + " ▪▪▪▪▪▪▪▪▪ ", + " ▪▪▴▴▴▪▪▪▪▦ ", + " ▴▴▴▴▴▪▪ ", + " ▴▴▴▴▪ ", + " ▴▴▴ ", + " " + ) + ); + }); + + it("135 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(135, true).getJGDSync(), + mkJGD( + " ", + " ", + " ▦ ", + " ▴▴▴ ", + " ▴▴▴▴▴ ", + " ▪▪▴▴▴▪▪ ", + " ▪▪▪▪▴▪▪▪▪ ", + " ▰▪▪▪▪▴▪▪▪▪▦ ", + " ▪▪▪▴▴▴▪▪▪ ", + " ▪▴▴▴▴▴▪ ", + " ▴▴▴▴▴ ", + " ▴▰▴ ", + " ▰ ", + " " + ) + ); + }); + + it("180 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(180, true).getJGDSync(), + mkJGD( + "▦▴▴▴▪▪▪▦", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▰▪▪▪▴▴▴▰" + ) + ); + }); + + it("225 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(225, true).getJGDSync(), + mkJGD( + " ", + " ▦ ", + " ▪▪▪ ", + " ▪▪▪▪▪ ", + " ▴▪▪▪▪▴▴ ", + " ▴▴▴▪▪▴▴▴▴ ", + " ▦▴▴▴▴▴▴▴▴▰▰ ", + " ▴▴▴▪▪▴▴▴▴ ", + " ▴▪▪▪▪▴▴ ", + " ▪▪▪▪▪ ", + " ▪▪▪ ", + " ▰ ", + " ", + " " + ) + ); + }); + + it("270 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(270, true).getJGDSync(), + mkJGD( + "▦▪▪▪▴▴▴▰", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▦▴▴▴▪▪▪▰" + ) + ); + }); + + it("315 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(315, true).getJGDSync(), + mkJGD( + " ▰ ", + " ▴▰▴ ", + " ▴▴▴▴▴ ", + " ▪▴▴▴▴▴▪ ", + " ▪▪▪▴▴▴▪▪▪ ", + " ▦▪▪▪▪▴▪▪▪▪▰ ", + " ▪▪▪▪▴▪▪▪▪ ", + " ▪▪▴▴▴▪▪ ", + " ▴▴▴▴▴ ", + " ▴▴▴ ", + " ▦ ", + " ", + " ", + " " + ) + ); + }); + + it("360 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(360, true).getJGDSync(), + mkJGD( + "▰▴▴▴▪▪▪▰", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▴▴▴▴▪▪▪▪", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▪▪▪▪▴▴▴▴", + "▦▪▪▪▴▴▴▦" + ) + ); + }); +}); + +describe("Rotate a image with odd size", () => { + let imgSrc = null; + before((done) => { + jimp + .read( + mkJGD( + "▴▴▴▦▪▪▪", + "▴▴▴▦▪▪▪", + "▴▴▴▦▪▪▪", + "▦▦▦▦▦▦▦", + "▴▴▴▦▴▴▴", + "▴▴▴▦▴▴▴", + "▴▴▴▦▴▴▴" + ) + ) + .then((imgJimp) => { + imgSrc = imgJimp; + done(); + }) + .catch(done); + }); + + it("45 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(45, true).getJGDSync(), + mkJGD( + " ", + " ▪ ", + " ▪▪▪ ", + " ▦▪▪▪▦ ", + " ▴▴▦▪▦▴▴ ", + " ▴▴▴▴▦▴▴▴▴ ", + " ▴▴▦▴▦▴▴ ", + " ▦▴▴▴▦ ", + " ▴▴▴ ", + " ▴ ", + " ", + " " + ) + ); + }); + + it("135 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(135, true).getJGDSync(), + mkJGD( + " ", + " ▴ ", + " ▴▴▴ ", + " ▦▴▴▴▦ ", + " ▪▪▦▴▦▴▴ ", + " ▪▪▪▪▦▴▴▴▴ ", + " ▪▪▦▴▦▴▴ ", + " ▦▴▴▴▦ ", + " ▴▴▴ ", + " ▴ ", + " ", + " " + ) + ); + }); + + it("225 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(225, true).getJGDSync(), + mkJGD( + " ", + " ▴ ", + " ▴▴▴ ", + " ▦▴▴▴▦ ", + " ▴▴▦▴▦▴▴ ", + " ▴▴▴▴▦▴▴▴▴ ", + " ▴▴▦▪▦▴▴ ", + " ▦▪▪▪▦ ", + " ▪▪▪ ", + " ▪ ", + " ", + " " + ) + ); + }); + + it("315 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(315, true).getJGDSync(), + mkJGD( + " ", + " ▴ ", + " ▴▴▴ ", + " ▦▴▴▴▦ ", + " ▴▴▦▴▦▪▪ ", + " ▴▴▴▴▦▪▪▪▪ ", + " ▴▴▦▴▦▪▪ ", + " ▦▴▴▴▦ ", + " ▴▴▴ ", + " ▴ ", + " ", + " " + ) + ); + }); +}); + +describe("Rotate a non-square image", () => { + let imgSrc = null; + before((done) => { + jimp + .read(mkJGD("▴▴▴▴▪▪▪▪", "▴▴▴▴▪▪▪▪", "▦▦▦▦▴▴▴▴", "▦▦▦▦▴▴▴▴")) + .then((imgJimp) => { + imgSrc = imgJimp; + done(); + }) + .catch(done); + }); + + it("1 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(1, true).getJGDSync(), + mkJGD( + "▴▴▴▴▪▪▪▪ ", + "▴▴▴▴▪▪▪▪ ", + "▦▦▦▦▴▴▴▴ ", + "▦▦▦▦▴▴▴▴ ", + " ", + " " + ) + ); + }); + + it("10 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(10, true).getJGDSync(), + mkJGD( + " ▪ ", + " ▴▴▴▪▪▪▪ ", + "▴▴▴▴▪▪▪▴ ", + "▴▴▦▦▴▴▴▴ ", + "▦▦▦▦▴▴▴ ", + "▦▦ ", + " ", + " " + ) + ); + }); + + it("30 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(30, true).getJGDSync(), + mkJGD( + " ", + " ▪▪ ", + " ▪▪▪▪ ", + " ▴▴▪▪▴▴▴ ", + "▴▴▴▦▴▴▴ ", + "▴▴▦▦▴▴ ", + "▦▦▦▦ ", + " ▦ ", + " ", + " " + ) + ); + }); + + it("45 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(45, true).getJGDSync(), + mkJGD( + " ", + " ▪▪ ", + " ▪▪▪▴ ", + " ▴▪▪▴▴▴ ", + " ▴▴▴▴▴▴ ", + "▴▴▴▦▦▴ ", + "▴▴▦▦▦ ", + " ▦▦▦ ", + " ▦ ", + " " + ) + ); + }); + + it("90 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(90, true).getJGDSync(), + mkJGD("▪▪▴▴", "▪▪▴▴", "▪▪▴▴", "▪▪▴▴", "▴▴▦▦", "▴▴▦▦", "▴▴▦▦", "▴▴▦▦") + ); + }); + + it("-90 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(-90, true).getJGDSync(), + mkJGD("▦▦▴▴", "▦▦▴▴", "▦▦▴▴", "▦▦▴▴", "▴▴▪▪", "▴▴▪▪", "▴▴▪▪", "▴▴▪▪") + ); + }); + + it("135 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(135, true).getJGDSync(), + mkJGD( + " ", + " ▴ ", + " ▴▴▴ ", + " ▪▪▴▴▴ ", + " ▪▪▪▴▦▦ ", + " ▪▪▴▦▦▦ ", + " ▴▴▴▦▦▦ ", + " ▴▴▴▦ ", + " ▴▴ ", + " " + ) + ); + }); + + it("180 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(180, true).getJGDSync(), + mkJGD("▴▴▴▴▦▦▦▦", "▴▴▴▴▦▦▦▦", "▪▪▪▪▴▴▴▴", "▪▪▪▪▴▴▴▴") + ); + }); + + it("225 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(225, true).getJGDSync(), + mkJGD( + " ▦ ", + " ▦▦▦ ", + " ▦▦▦▴▴ ", + " ▴▦▦▴▴▴ ", + " ▴▴▴▴▴▴ ", + " ▴▴▴▪▪▴ ", + " ▴▪▪▪ ", + " ▪▪ ", + " ", + " " + ) + ); + }); + + it("315 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(315, true).getJGDSync(), + mkJGD( + " ▴▴ ", + " ▦▴▴▴ ", + "▦▦▦▴▴▴ ", + " ▦▦▦▴▪▪ ", + " ▦▦▴▪▪▪ ", + " ▴▴▴▪▪ ", + " ▴▴▴ ", + " ▴ ", + " ", + " " + ) + ); + }); + it("-180 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(-180, true).getJGDSync(), + mkJGD("▴▴▴▴▦▦▦▦", "▴▴▴▴▦▦▦▦", "▪▪▪▪▴▴▴▴", "▪▪▪▪▴▴▴▴") + ); + }); + + it("-270 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(-270, true).getJGDSync(), + mkJGD("▪▪▴▴", "▪▪▴▴", "▪▪▴▴", "▪▪▴▴", "▴▴▦▦", "▴▴▦▦", "▴▴▦▦", "▴▴▦▦") + ); + }); +}); + +describe("Rotate a non-square image without resizing", () => { + let imgSrc = null; + before((done) => { + jimp + .read(mkJGD("□□□□□□□□", "▹▹▹▹▹▹▹▹", "▿▿▿▿▿▿▿▿", "□□□□□□□□")) + .then((imgJimp) => { + imgSrc = imgJimp; + done(); + }) + .catch(done); + }); + + it("90 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(90, false).getJGDSync(), + mkJGD(" □▹▿□ ", " □▹▿□ ", " □▹▿□ ", " □▹▿□ ") + ); + }); + + it("180 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(180, false).getJGDSync(), + mkJGD("□□□□□□□□", "▿▿▿▿▿▿▿▿", "▹▹▹▹▹▹▹▹", "□□□□□□□□") + ); + }); + + it("270 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(270, false).getJGDSync(), + mkJGD(" □▿▹□ ", " □▿▹□ ", " □▿▹□ ", " □▿▹□ ") + ); + }); + + it("45 degrees", () => { + expectToBeJGD( + imgSrc.clone().rotate(45, false).getJGDSync(), + mkJGD(" □▹▹▿□□ ", "□▹▹▿□□ ", "▹▹▿□□ ", "▹▿□□ ") + ); + }); +}); diff --git a/node_modules/@jimp/plugin-scale/CHANGELOG.md b/node_modules/@jimp/plugin-scale/CHANGELOG.md new file mode 100644 index 00000000..8d029143 --- /dev/null +++ b/node_modules/@jimp/plugin-scale/CHANGELOG.md @@ -0,0 +1,71 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-scale/LICENSE b/node_modules/@jimp/plugin-scale/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-scale/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-scale/README.md b/node_modules/@jimp/plugin-scale/README.md new file mode 100644 index 00000000..708a7771 --- /dev/null +++ b/node_modules/@jimp/plugin-scale/README.md @@ -0,0 +1,48 @@ +
+ +

@jimp/plugin-scale

+

Scale an image.

+
+ +## scale + +Uniformly scales the image by a factor. + +- @param {number} f the factor to scale the image by +- @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.scale(2); + image.scale(2, jimp.RESIZE_BEZIER); +} + +main(); +``` + +## scaleToFit + +Scale the image to the largest size that fits inside the rectangle that has the given width and height. + +- @param {number} w the width to resize the image to +- @param {number} h the height to resize the image to +- @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.scaleToFit(100, 100); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-scale/es/index.js b/node_modules/@jimp/plugin-scale/es/index.js new file mode 100644 index 00000000..5f85aa5f --- /dev/null +++ b/node_modules/@jimp/plugin-scale/es/index.js @@ -0,0 +1,53 @@ +import { isNodePattern, throwError } from "@jimp/utils"; +export default (() => ({ + /** + * Uniformly scales the image by a factor. + * @param {number} f the factor to scale the image by + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + scale(f, mode, cb) { + if (typeof f !== "number") { + return throwError.call(this, "f must be a number", cb); + } + if (f < 0) { + return throwError.call(this, "f must be a positive number", cb); + } + if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + const w = this.bitmap.width * f; + const h = this.bitmap.height * f; + this.resize(w, h, mode); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Scale the image to the largest size that fits inside the rectangle that has the given width and height. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + scaleToFit(w, h, mode, cb) { + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + const f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width; + this.scale(f, mode); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-scale/es/index.js.map b/node_modules/@jimp/plugin-scale/es/index.js.map new file mode 100644 index 00000000..0cbef4fa --- /dev/null +++ b/node_modules/@jimp/plugin-scale/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","scale","f","mode","cb","call","w","bitmap","width","h","height","resize","scaleToFit"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\nexport default () => ({\n /**\n * Uniformly scales the image by a factor.\n * @param {number} f the factor to scale the image by\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n scale(f, mode, cb) {\n if (typeof f !== \"number\") {\n return throwError.call(this, \"f must be a number\", cb);\n }\n\n if (f < 0) {\n return throwError.call(this, \"f must be a positive number\", cb);\n }\n\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n\n const w = this.bitmap.width * f;\n const h = this.bitmap.height * f;\n this.resize(w, h, mode);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Scale the image to the largest size that fits inside the rectangle that has the given width and height.\n * @param {number} w the width to resize the image to\n * @param {number} h the height to resize the image to\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n scaleToFit(w, h, mode, cb) {\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n\n const f =\n w / h > this.bitmap.width / this.bitmap.height\n ? h / this.bitmap.height\n : w / this.bitmap.width;\n this.scale(f, mode);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;AAEvD,gBAAe,OAAO;EACpB;AACF;AACA;AACA;AACA;AACA;AACA;EACEC,KAAK,CAACC,CAAC,EAAEC,IAAI,EAAEC,EAAE,EAAE;IACjB,IAAI,OAAOF,CAAC,KAAK,QAAQ,EAAE;MACzB,OAAOF,UAAU,CAACK,IAAI,CAAC,IAAI,EAAE,oBAAoB,EAAED,EAAE,CAAC;IACxD;IAEA,IAAIF,CAAC,GAAG,CAAC,EAAE;MACT,OAAOF,UAAU,CAACK,IAAI,CAAC,IAAI,EAAE,6BAA6B,EAAED,EAAE,CAAC;IACjE;IAEA,IAAI,OAAOD,IAAI,KAAK,UAAU,IAAI,OAAOC,EAAE,KAAK,WAAW,EAAE;MAC3DA,EAAE,GAAGD,IAAI;MACTA,IAAI,GAAG,IAAI;IACb;IAEA,MAAMG,CAAC,GAAG,IAAI,CAACC,MAAM,CAACC,KAAK,GAAGN,CAAC;IAC/B,MAAMO,CAAC,GAAG,IAAI,CAACF,MAAM,CAACG,MAAM,GAAGR,CAAC;IAChC,IAAI,CAACS,MAAM,CAACL,CAAC,EAAEG,CAAC,EAAEN,IAAI,CAAC;IAEvB,IAAIJ,aAAa,CAACK,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb,CAAC;EAED;AACF;AACA;AACA;AACA;AACA;AACA;AACA;EACEO,UAAU,CAACN,CAAC,EAAEG,CAAC,EAAEN,IAAI,EAAEC,EAAE,EAAE;IACzB,IAAI,OAAOE,CAAC,KAAK,QAAQ,IAAI,OAAOG,CAAC,KAAK,QAAQ,EAAE;MAClD,OAAOT,UAAU,CAACK,IAAI,CAAC,IAAI,EAAE,yBAAyB,EAAED,EAAE,CAAC;IAC7D;IAEA,IAAI,OAAOD,IAAI,KAAK,UAAU,IAAI,OAAOC,EAAE,KAAK,WAAW,EAAE;MAC3DA,EAAE,GAAGD,IAAI;MACTA,IAAI,GAAG,IAAI;IACb;IAEA,MAAMD,CAAC,GACLI,CAAC,GAAGG,CAAC,GAAG,IAAI,CAACF,MAAM,CAACC,KAAK,GAAG,IAAI,CAACD,MAAM,CAACG,MAAM,GAC1CD,CAAC,GAAG,IAAI,CAACF,MAAM,CAACG,MAAM,GACtBJ,CAAC,GAAG,IAAI,CAACC,MAAM,CAACC,KAAK;IAC3B,IAAI,CAACP,KAAK,CAACC,CAAC,EAAEC,IAAI,CAAC;IAEnB,IAAIJ,aAAa,CAACK,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-scale/index.d.ts b/node_modules/@jimp/plugin-scale/index.d.ts new file mode 100644 index 00000000..28c26ba2 --- /dev/null +++ b/node_modules/@jimp/plugin-scale/index.d.ts @@ -0,0 +1,15 @@ +import { ImageCallback } from "@jimp/core"; + +interface Scale { + scale(f: number, cb?: ImageCallback): this; + scale(f: number, mode?: string, cb?: ImageCallback): this; + scaleToFit(w: number, h: number, cb?: ImageCallback): this; + scaleToFit( + w: number, + h: number, + mode?: string, + cb?: ImageCallback + ): this; +} + +export default function (): Scale; diff --git a/node_modules/@jimp/plugin-scale/package.json b/node_modules/@jimp/plugin-scale/package.json new file mode 100644 index 00000000..a4295426 --- /dev/null +++ b/node_modules/@jimp/plugin-scale/package.json @@ -0,0 +1,31 @@ +{ + "name": "@jimp/plugin-scale", + "version": "0.22.12", + "description": "scale an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-scale/src/index.js b/node_modules/@jimp/plugin-scale/src/index.js new file mode 100644 index 00000000..f67ce2b3 --- /dev/null +++ b/node_modules/@jimp/plugin-scale/src/index.js @@ -0,0 +1,66 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +export default () => ({ + /** + * Uniformly scales the image by a factor. + * @param {number} f the factor to scale the image by + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + scale(f, mode, cb) { + if (typeof f !== "number") { + return throwError.call(this, "f must be a number", cb); + } + + if (f < 0) { + return throwError.call(this, "f must be a positive number", cb); + } + + if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + + const w = this.bitmap.width * f; + const h = this.bitmap.height * f; + this.resize(w, h, mode); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Scale the image to the largest size that fits inside the rectangle that has the given width and height. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + scaleToFit(w, h, mode, cb) { + if (typeof w !== "number" || typeof h !== "number") { + return throwError.call(this, "w and h must be numbers", cb); + } + + if (typeof mode === "function" && typeof cb === "undefined") { + cb = mode; + mode = null; + } + + const f = + w / h > this.bitmap.width / this.bitmap.height + ? h / this.bitmap.height + : w / this.bitmap.width; + this.scale(f, mode); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-shadow/CHANGELOG.md b/node_modules/@jimp/plugin-shadow/CHANGELOG.md new file mode 100644 index 00000000..51272b3f --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/CHANGELOG.md @@ -0,0 +1,98 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.4 (Tue Mar 03 2020) + +#### 🐛 Bug Fix + +- `@jimp/plugin-shadow` + - Update plugin-shadow type definition. [#841](https://github.com/oliver-moran/jimp/pull/841) ([@lekoaf](https://github.com/lekoaf)) + +#### Authors: 1 + +- Martin ([@lekoaf](https://github.com/lekoaf)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-shadow/LICENSE b/node_modules/@jimp/plugin-shadow/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-shadow/README.md b/node_modules/@jimp/plugin-shadow/README.md new file mode 100644 index 00000000..b068cd22 --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/README.md @@ -0,0 +1,30 @@ +
+ +

@jimp/plugin-shadow

+

Creates a shadow on an image.

+
+ +## Usage + +- @param {function(Error, Jimp)} options (optional) + - opacity - opacity of the shadow between 0 and 1 + - size,- of the shadow + - blur - how blurry the shadow is + - x - x position of shadow + - y - y position of shadow +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.shadow(); + // or + image.shadow({ opacity: 0.8, size: 1.2, blur: 10, x: -75, y: -75 }); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-shadow/babel.config.js b/node_modules/@jimp/plugin-shadow/babel.config.js new file mode 100644 index 00000000..13e2603a --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/babel.config.js @@ -0,0 +1,38 @@ +module.exports = (api) => { + api.cache(true); + + return { + presets: [ + [ + "@babel/env", + { + useBuiltIns: "usage", + }, + ], + ], + + plugins: [ + "@babel/proposal-class-properties", + "@babel/syntax-object-rest-spread", + process.env.BABEL_ENV !== "module" && "add-module-exports", + [ + "transform-inline-environment-variables", + { include: ["BABEL_ENV", "ENV"] }, + ], + ].filter(Boolean), + + env: { + test: { + plugins: ["istanbul"], + }, + development: { + plugins: [process.env.ENV !== "browser" && "source-map-support"].filter( + Boolean + ), + }, + module: { + presets: [["@babel/env", { modules: false }]], + }, + }, + }; +}; diff --git a/node_modules/@jimp/plugin-shadow/es/index.js b/node_modules/@jimp/plugin-shadow/es/index.js new file mode 100644 index 00000000..3fc0485f --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/es/index.js @@ -0,0 +1,59 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Creates a circle out of an image. + * @param {function(Error, Jimp)} options (optional) + * opacity - opacity of the shadow between 0 and 1 + * size,- of the shadow + * blur - how blurry the shadow is + * x- x position of shadow + * y - y position of shadow + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default (() => ({ + shadow() { + let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + let cb = arguments.length > 1 ? arguments[1] : undefined; + if (typeof options === "function") { + cb = options; + options = {}; + } + const { + opacity = 0.7, + size = 1.1, + x = -25, + y = 25, + blur = 5 + } = options; + + // clone the image + const orig = this.clone(); + const shadow = this.clone(); + + // turn all it's pixels black + shadow.scan(0, 0, shadow.bitmap.width, shadow.bitmap.height, (x, y, idx) => { + shadow.bitmap.data[idx] = 0x00; + shadow.bitmap.data[idx + 1] = 0x00; + shadow.bitmap.data[idx + 2] = 0x00; + // up the opacity a little, + shadow.bitmap.data[idx + 3] = shadow.constructor.limit255(shadow.bitmap.data[idx + 3] * opacity); + this.bitmap.data[idx] = 0x00; + this.bitmap.data[idx + 1] = 0x00; + this.bitmap.data[idx + 2] = 0x00; + this.bitmap.data[idx + 3] = 0x00; + }); + + // enlarge it. This creates a "shadow". + shadow.resize(shadow.bitmap.width * size, shadow.bitmap.height * size).blur(blur); + + // Then blit the "shadow" onto the background and the image on top of that. + this.composite(shadow, x, y); + this.composite(orig, 0, 0); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-shadow/es/index.js.map b/node_modules/@jimp/plugin-shadow/es/index.js.map new file mode 100644 index 00000000..eefaa01c --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","shadow","options","cb","opacity","size","x","y","blur","orig","clone","scan","bitmap","width","height","idx","data","constructor","limit255","resize","composite","call"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Creates a circle out of an image.\n * @param {function(Error, Jimp)} options (optional)\n * opacity - opacity of the shadow between 0 and 1\n * size,- of the shadow\n * blur - how blurry the shadow is\n * x- x position of shadow\n * y - y position of shadow\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default () => ({\n shadow(options = {}, cb) {\n if (typeof options === \"function\") {\n cb = options;\n options = {};\n }\n\n const { opacity = 0.7, size = 1.1, x = -25, y = 25, blur = 5 } = options;\n\n // clone the image\n const orig = this.clone();\n const shadow = this.clone();\n\n // turn all it's pixels black\n shadow.scan(\n 0,\n 0,\n shadow.bitmap.width,\n shadow.bitmap.height,\n (x, y, idx) => {\n shadow.bitmap.data[idx] = 0x00;\n shadow.bitmap.data[idx + 1] = 0x00;\n shadow.bitmap.data[idx + 2] = 0x00;\n // up the opacity a little,\n shadow.bitmap.data[idx + 3] = shadow.constructor.limit255(\n shadow.bitmap.data[idx + 3] * opacity\n );\n\n this.bitmap.data[idx] = 0x00;\n this.bitmap.data[idx + 1] = 0x00;\n this.bitmap.data[idx + 2] = 0x00;\n this.bitmap.data[idx + 3] = 0x00;\n }\n );\n\n // enlarge it. This creates a \"shadow\".\n shadow\n .resize(shadow.bitmap.width * size, shadow.bitmap.height * size)\n .blur(blur);\n\n // Then blit the \"shadow\" onto the background and the image on top of that.\n this.composite(shadow, x, y);\n this.composite(orig, 0, 0);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,aAAa;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe,OAAO;EACpBC,MAAM,GAAmB;IAAA,IAAlBC,OAAO,uEAAG,CAAC,CAAC;IAAA,IAAEC,EAAE;IACrB,IAAI,OAAOD,OAAO,KAAK,UAAU,EAAE;MACjCC,EAAE,GAAGD,OAAO;MACZA,OAAO,GAAG,CAAC,CAAC;IACd;IAEA,MAAM;MAAEE,OAAO,GAAG,GAAG;MAAEC,IAAI,GAAG,GAAG;MAAEC,CAAC,GAAG,CAAC,EAAE;MAAEC,CAAC,GAAG,EAAE;MAAEC,IAAI,GAAG;IAAE,CAAC,GAAGN,OAAO;;IAExE;IACA,MAAMO,IAAI,GAAG,IAAI,CAACC,KAAK,EAAE;IACzB,MAAMT,MAAM,GAAG,IAAI,CAACS,KAAK,EAAE;;IAE3B;IACAT,MAAM,CAACU,IAAI,CACT,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AAE,CAAC,EAAE;MACrBA,EAAE,CAACkB,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-shadow/index.d.ts b/node_modules/@jimp/plugin-shadow/index.d.ts new file mode 100644 index 00000000..4e3c4841 --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/index.d.ts @@ -0,0 +1,17 @@ +import { ImageCallback } from "@jimp/core"; + +interface Shadow { + shadow( + options?: { + size?: number; + opacity?: number; + blur: number; + x?: number; + y?: number; + }, + cb?: ImageCallback + ): this; + shadow(cb?: ImageCallback): this; +} + +export default function (): Shadow; diff --git a/node_modules/@jimp/plugin-shadow/package.json b/node_modules/@jimp/plugin-shadow/package.json new file mode 100644 index 00000000..f1c0c592 --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/package.json @@ -0,0 +1,41 @@ +{ + "name": "@jimp/plugin-shadow", + "version": "0.22.12", + "description": "Creates a shadow on an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-blur": ">=0.3.5", + "@jimp/plugin-resize": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/plugin-blur": "^0.22.12", + "@jimp/plugin-resize": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-shadow/src/index.js b/node_modules/@jimp/plugin-shadow/src/index.js new file mode 100644 index 00000000..81c23c41 --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/src/index.js @@ -0,0 +1,64 @@ +import { isNodePattern } from "@jimp/utils"; + +/** + * Creates a circle out of an image. + * @param {function(Error, Jimp)} options (optional) + * opacity - opacity of the shadow between 0 and 1 + * size,- of the shadow + * blur - how blurry the shadow is + * x- x position of shadow + * y - y position of shadow + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +export default () => ({ + shadow(options = {}, cb) { + if (typeof options === "function") { + cb = options; + options = {}; + } + + const { opacity = 0.7, size = 1.1, x = -25, y = 25, blur = 5 } = options; + + // clone the image + const orig = this.clone(); + const shadow = this.clone(); + + // turn all it's pixels black + shadow.scan( + 0, + 0, + shadow.bitmap.width, + shadow.bitmap.height, + (x, y, idx) => { + shadow.bitmap.data[idx] = 0x00; + shadow.bitmap.data[idx + 1] = 0x00; + shadow.bitmap.data[idx + 2] = 0x00; + // up the opacity a little, + shadow.bitmap.data[idx + 3] = shadow.constructor.limit255( + shadow.bitmap.data[idx + 3] * opacity + ); + + this.bitmap.data[idx] = 0x00; + this.bitmap.data[idx + 1] = 0x00; + this.bitmap.data[idx + 2] = 0x00; + this.bitmap.data[idx + 3] = 0x00; + } + ); + + // enlarge it. This creates a "shadow". + shadow + .resize(shadow.bitmap.width * size, shadow.bitmap.height * size) + .blur(blur); + + // Then blit the "shadow" onto the background and the image on top of that. + this.composite(shadow, x, y); + this.composite(orig, 0, 0); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-shadow/test/images/shadow.png b/node_modules/@jimp/plugin-shadow/test/images/shadow.png new file mode 100644 index 00000000..5564dbb3 Binary files /dev/null and b/node_modules/@jimp/plugin-shadow/test/images/shadow.png differ diff --git a/node_modules/@jimp/plugin-shadow/test/shadow.test.js b/node_modules/@jimp/plugin-shadow/test/shadow.test.js new file mode 100644 index 00000000..2ee56166 --- /dev/null +++ b/node_modules/@jimp/plugin-shadow/test/shadow.test.js @@ -0,0 +1,32 @@ +import { Jimp, mkJGD, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import resize from "@jimp/plugin-resize"; +import blur from "@jimp/plugin-blur"; +import expect from "@storybook/expect"; + +import shadow from "../src"; + +const jimp = configure({ plugins: [shadow, resize, blur] }, Jimp); + +describe("Shadow", () => { + it("creates a shadow", async () => { + const expectedImg = await jimp.read( + getTestDir(__dirname) + "/images/shadow.png" + ); + const testImage = await jimp.read( + mkJGD( + " ", + " ◆◆ ", + " ◆▦▦◆ ", + " ◆▦▦▦▦◆ ", + " ◆▦▦◆ ", + " ◆◆ ", + " " + ) + ); + + expect(testImage.shadow({ x: -1, y: 1, blur: 1 }).bitmap.data).toEqual( + expectedImg.bitmap.data + ); + }); +}); diff --git a/node_modules/@jimp/plugin-threshold/CHANGELOG.md b/node_modules/@jimp/plugin-threshold/CHANGELOG.md new file mode 100644 index 00000000..7e842d38 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/CHANGELOG.md @@ -0,0 +1,97 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.7 (Fri Mar 27 2020) + +#### 🐛 Bug Fix + +- Relax version range of plugin-threshold peerDependencies [#859](https://github.com/oliver-moran/jimp/pull/859) ([@pasieronen](https://github.com/pasieronen)) + +#### Authors: 1 + +- Pasi Eronen ([@pasieronen](https://github.com/pasieronen)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugin-threshold/LICENSE b/node_modules/@jimp/plugin-threshold/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugin-threshold/README.md b/node_modules/@jimp/plugin-threshold/README.md new file mode 100644 index 00000000..57271c3b --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/README.md @@ -0,0 +1,30 @@ +
+ +

@jimp/plugin-threshold

+

Lightens an image.

+
+ +This is useful as a simplified method for processing scanned drawings, signatures, etc + +## Usage + +- @param {number} options object + - max: A number auto limited between 0 - 255 + - replace: (optional) A number auto limited between 0 - 255 (default 255) + - autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true) +- @param {function(Error, Jimp)} cb (optional) a callback for when complete + +```js +import jimp from "jimp"; + +async function main() { + const image = await jimp.read("test/image.png"); + + image.threshold({ max: 150 }); + // or + image.threshold({ max: 200, replace: 200, autoGreyscale: false }); +} + +main(); +``` diff --git a/node_modules/@jimp/plugin-threshold/babel.config.js b/node_modules/@jimp/plugin-threshold/babel.config.js new file mode 100644 index 00000000..13e2603a --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/babel.config.js @@ -0,0 +1,38 @@ +module.exports = (api) => { + api.cache(true); + + return { + presets: [ + [ + "@babel/env", + { + useBuiltIns: "usage", + }, + ], + ], + + plugins: [ + "@babel/proposal-class-properties", + "@babel/syntax-object-rest-spread", + process.env.BABEL_ENV !== "module" && "add-module-exports", + [ + "transform-inline-environment-variables", + { include: ["BABEL_ENV", "ENV"] }, + ], + ].filter(Boolean), + + env: { + test: { + plugins: ["istanbul"], + }, + development: { + plugins: [process.env.ENV !== "browser" && "source-map-support"].filter( + Boolean + ), + }, + module: { + presets: [["@babel/env", { modules: false }]], + }, + }, + }; +}; diff --git a/node_modules/@jimp/plugin-threshold/es/index.js b/node_modules/@jimp/plugin-threshold/es/index.js new file mode 100644 index 00000000..ee264b5f --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/es/index.js @@ -0,0 +1,45 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Applies a minimum color threshold to a greyscale image. Converts image to greyscale by default + * @param {number} options object + * max: A number auto limited between 0 - 255 + * replace: (optional) A number auto limited between 0 - 255 (default 255) + * autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true) + * @param {number} cb (optional) a callback for when complete + * @return {this} this for chaining of methods + */ +export default (() => ({ + threshold(_ref, cb) { + let { + max, + replace = 255, + autoGreyscale = true + } = _ref; + if (typeof max !== "number") { + return throwError.call(this, "max must be a number", cb); + } + if (typeof replace !== "number") { + return throwError.call(this, "replace must be a number", cb); + } + if (typeof autoGreyscale !== "boolean") { + return throwError.call(this, "autoGreyscale must be a boolean", cb); + } + max = this.constructor.limit255(max); + replace = this.constructor.limit255(replace); + if (autoGreyscale) { + this.greyscale(); + } + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => { + const grey = this.bitmap.data[idx] < max ? this.bitmap.data[idx] : replace; + this.bitmap.data[idx] = grey; + this.bitmap.data[idx + 1] = grey; + this.bitmap.data[idx + 2] = grey; + }); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugin-threshold/es/index.js.map b/node_modules/@jimp/plugin-threshold/es/index.js.map new file mode 100644 index 00000000..a63e69bc --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","throwError","threshold","cb","max","replace","autoGreyscale","call","constructor","limit255","greyscale","scanQuiet","bitmap","width","height","x","y","idx","grey","data"],"sources":["../src/index.js"],"sourcesContent":["import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Applies a minimum color threshold to a greyscale image. Converts image to greyscale by default\n * @param {number} options object\n * max: A number auto limited between 0 - 255\n * replace: (optional) A number auto limited between 0 - 255 (default 255)\n * autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true)\n * @param {number} cb (optional) a callback for when complete\n * @return {this} this for chaining of methods\n */\nexport default () => ({\n threshold({ max, replace = 255, autoGreyscale = true }, cb) {\n if (typeof max !== \"number\") {\n return throwError.call(this, \"max must be a number\", cb);\n }\n\n if (typeof replace !== \"number\") {\n return throwError.call(this, \"replace must be a number\", cb);\n }\n\n if (typeof autoGreyscale !== \"boolean\") {\n return throwError.call(this, \"autoGreyscale must be a boolean\", cb);\n }\n\n max = this.constructor.limit255(max);\n replace = this.constructor.limit255(replace);\n\n if (autoGreyscale) {\n this.greyscale();\n }\n\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {\n const grey =\n this.bitmap.data[idx] < max ? this.bitmap.data[idx] : replace;\n\n this.bitmap.data[idx] = grey;\n this.bitmap.data[idx + 1] = grey;\n this.bitmap.data[idx + 2] = grey;\n });\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n});\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,UAAU,QAAQ,aAAa;;AAEvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe,OAAO;EACpBC,SAAS,OAA+CC,EAAE,EAAE;IAAA,IAAlD;MAAEC,GAAG;MAAEC,OAAO,GAAG,GAAG;MAAEC,aAAa,GAAG;IAAK,CAAC;IACpD,IAAI,OAAOF,GAAG,KAAK,QAAQ,EAAE;MAC3B,OAAOH,UAAU,CAACM,IAAI,CAAC,IAAI,EAAE,sBAAsB,EAAEJ,EAAE,CAAC;IAC1D;IAEA,IAAI,OAAOE,OAAO,KAAK,QAAQ,EAAE;MAC/B,OAAOJ,UAAU,CAACM,IAAI,CAAC,IAAI,EAAE,0BAA0B,EAAEJ,EAAE,CAAC;IAC9D;IAEA,IAAI,OAAOG,aAAa,KAAK,SAAS,EAAE;MACtC,OAAOL,UAAU,CAACM,IAAI,CAAC,IAAI,EAAE,iCAAiC,EAAEJ,EAAE,CAAC;IACrE;IAEAC,GAAG,GAAG,IAAI,CAACI,WAAW,CAACC,QAAQ,CAACL,GAAG,CAAC;IACpCC,OAAO,GAAG,IAAI,CAACG,WAAW,CAACC,QAAQ,CAACJ,OAAO,CAAC;IAE5C,IAAIC,aAAa,EAAE;MACjB,IAAI,CAACI,SAAS,EAAE;IAClB;IAEA,IAAI,CAACC,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,CAACC,MAAM,CAACC,KAAK,EAAE,IAAI,CAACD,MAAM,CAACE,MAAM,EAAE,CAACC,CAAC,EAAEC,CAAC,EAAEC,GAAG,KAAK;MACzE,MAAMC,IAAI,GACR,IAAI,CAACN,MAAM,CAACO,IAAI,CAACF,GAAG,CAAC,GAAGb,GAAG,GAAG,IAAI,CAACQ,MAAM,CAACO,IAAI,CAACF,GAAG,CAAC,GAAGZ,OAAO;MAE/D,IAAI,CAACO,MAAM,CAACO,IAAI,CAACF,GAAG,CAAC,GAAGC,IAAI;MAC5B,IAAI,CAACN,MAAM,CAACO,IAAI,CAACF,GAAG,GAAG,CAAC,CAAC,GAAGC,IAAI;MAChC,IAAI,CAACN,MAAM,CAACO,IAAI,CAACF,GAAG,GAAG,CAAC,CAAC,GAAGC,IAAI;IAClC,CAAC,CAAC;IAEF,IAAIlB,aAAa,CAACG,EAAE,CAAC,EAAE;MACrBA,EAAE,CAACI,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugin-threshold/index.d.ts b/node_modules/@jimp/plugin-threshold/index.d.ts new file mode 100644 index 00000000..96ad193f --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/index.d.ts @@ -0,0 +1,14 @@ +import { ImageCallback } from "@jimp/core"; + +interface Threshold { + threshold( + opts: { + max: number; + replace?: number; + autoGreyscale?: boolean; + }, + cb?: ImageCallback + ): this; +} + +export default function (): Threshold; diff --git a/node_modules/@jimp/plugin-threshold/package.json b/node_modules/@jimp/plugin-threshold/package.json new file mode 100644 index 00000000..e49ad877 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/package.json @@ -0,0 +1,42 @@ +{ + "name": "@jimp/plugin-threshold", + "version": "0.22.12", + "description": "Lightens an image.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5", + "@jimp/plugin-color": ">=0.8.0", + "@jimp/plugin-resize": ">=0.8.0" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/jpeg": "^0.22.12", + "@jimp/plugin-color": "^0.22.12", + "@jimp/plugin-resize": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugin-threshold/src/index.js b/node_modules/@jimp/plugin-threshold/src/index.js new file mode 100644 index 00000000..fad06bac --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/src/index.js @@ -0,0 +1,48 @@ +import { isNodePattern, throwError } from "@jimp/utils"; + +/** + * Applies a minimum color threshold to a greyscale image. Converts image to greyscale by default + * @param {number} options object + * max: A number auto limited between 0 - 255 + * replace: (optional) A number auto limited between 0 - 255 (default 255) + * autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true) + * @param {number} cb (optional) a callback for when complete + * @return {this} this for chaining of methods + */ +export default () => ({ + threshold({ max, replace = 255, autoGreyscale = true }, cb) { + if (typeof max !== "number") { + return throwError.call(this, "max must be a number", cb); + } + + if (typeof replace !== "number") { + return throwError.call(this, "replace must be a number", cb); + } + + if (typeof autoGreyscale !== "boolean") { + return throwError.call(this, "autoGreyscale must be a boolean", cb); + } + + max = this.constructor.limit255(max); + replace = this.constructor.limit255(replace); + + if (autoGreyscale) { + this.greyscale(); + } + + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => { + const grey = + this.bitmap.data[idx] < max ? this.bitmap.data[idx] : replace; + + this.bitmap.data[idx] = grey; + this.bitmap.data[idx + 1] = grey; + this.bitmap.data[idx + 2] = grey; + }); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, +}); diff --git a/node_modules/@jimp/plugin-threshold/test/images/hands.jpg b/node_modules/@jimp/plugin-threshold/test/images/hands.jpg new file mode 100644 index 00000000..c3a874ed Binary files /dev/null and b/node_modules/@jimp/plugin-threshold/test/images/hands.jpg differ diff --git a/node_modules/@jimp/plugin-threshold/test/images/hands_mx200_rp255.jpg b/node_modules/@jimp/plugin-threshold/test/images/hands_mx200_rp255.jpg new file mode 100644 index 00000000..b0b85113 Binary files /dev/null and b/node_modules/@jimp/plugin-threshold/test/images/hands_mx200_rp255.jpg differ diff --git a/node_modules/@jimp/plugin-threshold/test/threshold.test.js b/node_modules/@jimp/plugin-threshold/test/threshold.test.js new file mode 100644 index 00000000..709da3e1 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/test/threshold.test.js @@ -0,0 +1,30 @@ +import { Jimp, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import jpeg from "@jimp/jpeg"; +import color from "@jimp/plugin-color"; +import resize from "@jimp/plugin-resize"; +import expect from "@storybook/expect"; + +import threshold from "../src"; + +const jimp = configure( + { types: [jpeg], plugins: [threshold, color, resize] }, + Jimp +); + +describe("Threshold", function () { + this.timeout(15000); + + it("defines default threshold for lighter backgrounds", async () => { + const expectedImage = await jimp.read( + getTestDir(__dirname) + "/images/hands_mx200_rp255.jpg" + ); + const testImage = await jimp.read( + getTestDir(__dirname) + "/images/hands.jpg" + ); + + expect(testImage.threshold({ max: 200, replace: 255 }).hash()).toBe( + expectedImage.hash() + ); + }); +}); diff --git a/node_modules/@jimp/plugins/CHANGELOG.md b/node_modules/@jimp/plugins/CHANGELOG.md new file mode 100644 index 00000000..2bc31ab4 --- /dev/null +++ b/node_modules/@jimp/plugins/CHANGELOG.md @@ -0,0 +1,95 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.8 (Sat Mar 28 2020) + +#### 🐛 Bug Fix + +- Export the four missing plugins from plugin package [#866](https://github.com/oliver-moran/jimp/pull/866) ([@crutchcorn](https://github.com/crutchcorn)) + +#### Authors: 1 + +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) + +--- + +# v0.9.7 (Fri Mar 27 2020) + +#### 🐛 Bug Fix + +- Added missing plugins to the types [#863](https://github.com/oliver-moran/jimp/pull/863) ([@crutchcorn](https://github.com/crutchcorn)) + +#### Authors: 1 + +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/plugins/LICENSE b/node_modules/@jimp/plugins/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/plugins/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/plugins/README.md b/node_modules/@jimp/plugins/README.md new file mode 100644 index 00000000..11defb95 --- /dev/null +++ b/node_modules/@jimp/plugins/README.md @@ -0,0 +1,25 @@ +
+ +

@jimp/plugins

+

Default Jimp plugins.

+
+ +## Included Plugins + +- [blit](../plugin-blit) +- [blur](../plugin-blur) +- [color](../plugin-color) +- [contain](../plugin-contain) +- [cover](../plugin-cover) +- [displace](../plugin-displace) +- [dither](../plugin-dither) +- [flip](../plugin-flip) +- [gaussian](../plugin-gaussian) +- [invert](../plugin-invert) +- [mask](../plugin-mask) +- [normalize](../plugin-normalize) +- [print](../plugin-print) +- [resize](../plugin-resize) +- [rotate](../plugin-rotate) +- [scale](../plugin-scale) diff --git a/node_modules/@jimp/plugins/es/index.js b/node_modules/@jimp/plugins/es/index.js new file mode 100644 index 00000000..22a58977 --- /dev/null +++ b/node_modules/@jimp/plugins/es/index.js @@ -0,0 +1,37 @@ +import { mergeDeep } from "timm"; +import blit from "@jimp/plugin-blit"; +import blur from "@jimp/plugin-blur"; +import circle from "@jimp/plugin-circle"; +import color from "@jimp/plugin-color"; +import contain from "@jimp/plugin-contain"; +import cover from "@jimp/plugin-cover"; +import crop from "@jimp/plugin-crop"; +import displace from "@jimp/plugin-displace"; +import dither from "@jimp/plugin-dither"; +import fisheye from "@jimp/plugin-fisheye"; +import flip from "@jimp/plugin-flip"; +import gaussian from "@jimp/plugin-gaussian"; +import invert from "@jimp/plugin-invert"; +import mask from "@jimp/plugin-mask"; +import normalize from "@jimp/plugin-normalize"; +import print from "@jimp/plugin-print"; +import resize from "@jimp/plugin-resize"; +import rotate from "@jimp/plugin-rotate"; +import scale from "@jimp/plugin-scale"; +import shadow from "@jimp/plugin-shadow"; +import threshold from "@jimp/plugin-threshold"; +const plugins = [blit, blur, circle, color, contain, cover, crop, displace, dither, fisheye, flip, gaussian, invert, mask, normalize, print, resize, rotate, scale, shadow, threshold]; +export default (jimpEvChange => { + const initializedPlugins = plugins.map(pluginModule => { + let plugin = pluginModule(jimpEvChange) || {}; + if (!plugin.class && !plugin.constants) { + // Default to class function + plugin = { + class: plugin + }; + } + return plugin; + }); + return mergeDeep(...initializedPlugins); +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/plugins/es/index.js.map b/node_modules/@jimp/plugins/es/index.js.map new file mode 100644 index 00000000..fb2069cf --- /dev/null +++ b/node_modules/@jimp/plugins/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["mergeDeep","blit","blur","circle","color","contain","cover","crop","displace","dither","fisheye","flip","gaussian","invert","mask","normalize","print","resize","rotate","scale","shadow","threshold","plugins","jimpEvChange","initializedPlugins","map","pluginModule","plugin","class","constants"],"sources":["../src/index.js"],"sourcesContent":["import { mergeDeep } from \"timm\";\n\nimport blit from \"@jimp/plugin-blit\";\nimport blur from \"@jimp/plugin-blur\";\nimport circle from \"@jimp/plugin-circle\";\nimport color from \"@jimp/plugin-color\";\nimport contain from \"@jimp/plugin-contain\";\nimport cover from \"@jimp/plugin-cover\";\nimport crop from \"@jimp/plugin-crop\";\nimport displace from \"@jimp/plugin-displace\";\nimport dither from \"@jimp/plugin-dither\";\nimport fisheye from \"@jimp/plugin-fisheye\";\nimport flip from \"@jimp/plugin-flip\";\nimport gaussian from \"@jimp/plugin-gaussian\";\nimport invert from \"@jimp/plugin-invert\";\nimport mask from \"@jimp/plugin-mask\";\nimport normalize from \"@jimp/plugin-normalize\";\nimport print from \"@jimp/plugin-print\";\nimport resize from \"@jimp/plugin-resize\";\nimport rotate from \"@jimp/plugin-rotate\";\nimport scale from \"@jimp/plugin-scale\";\nimport shadow from \"@jimp/plugin-shadow\";\nimport threshold from \"@jimp/plugin-threshold\";\n\nconst plugins = [\n blit,\n blur,\n circle,\n color,\n contain,\n cover,\n crop,\n displace,\n dither,\n fisheye,\n flip,\n gaussian,\n invert,\n mask,\n normalize,\n print,\n resize,\n rotate,\n scale,\n shadow,\n threshold,\n];\n\nexport default (jimpEvChange) => {\n const initializedPlugins = plugins.map((pluginModule) => {\n let plugin = pluginModule(jimpEvChange) || {};\n\n if (!plugin.class && !plugin.constants) {\n // Default to class function\n plugin = { class: plugin };\n }\n\n return plugin;\n });\n\n return mergeDeep(...initializedPlugins);\n};\n"],"mappings":"AAAA,SAASA,SAAS,QAAQ,MAAM;AAEhC,OAAOC,IAAI,MAAM,mBAAmB;AACpC,OAAOC,IAAI,MAAM,mBAAmB;AACpC,OAAOC,MAAM,MAAM,qBAAqB;AACxC,OAAOC,KAAK,MAAM,oBAAoB;AACtC,OAAOC,OAAO,MAAM,sBA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AC"} \ No newline at end of file diff --git a/node_modules/@jimp/plugins/index.d.ts b/node_modules/@jimp/plugins/index.d.ts new file mode 100644 index 00000000..0184bbcc --- /dev/null +++ b/node_modules/@jimp/plugins/index.d.ts @@ -0,0 +1,76 @@ +import blit from "@jimp/plugin-blit"; +import blur from "@jimp/plugin-blur"; +import circle from "@jimp/plugin-circle"; +import color from "@jimp/plugin-color"; +import contain from "@jimp/plugin-contain"; +import cover from "@jimp/plugin-cover"; +import crop from "@jimp/plugin-crop"; +import displace from "@jimp/plugin-displace"; +import dither from "@jimp/plugin-dither"; +import fisheye from "@jimp/plugin-fisheye"; +import flip from "@jimp/plugin-flip"; +import gaussian from "@jimp/plugin-gaussian"; +import invert from "@jimp/plugin-invert"; +import mask from "@jimp/plugin-mask"; +import normalize from "@jimp/plugin-normalize"; +import print from "@jimp/plugin-print"; +import resize from "@jimp/plugin-resize"; +import rotate from "@jimp/plugin-rotate"; +import scale from "@jimp/plugin-scale"; +import shadow from "@jimp/plugin-shadow"; +import threshold from "@jimp/plugin-threshold"; + +type BlitRet = ReturnType; +type BlurRet = ReturnType; +type CircleRet = ReturnType; +type ColorRet = ReturnType; +type ContainRet = ReturnType; +type CoverRet = ReturnType; +type CropRet = ReturnType; +type DisplaceRet = ReturnType; +type DitherRet = ReturnType; +type FlipRet = ReturnType; +type FisheyeRet = ReturnType; +type GaussianRet = ReturnType; +type InvertRet = ReturnType; +type MaskRet = ReturnType; +type NormalizeRet = ReturnType; +type PrintRet = ReturnType; +type ResizeRet = ReturnType; +type RotateRet = ReturnType; +type ScaleRet = ReturnType; +type ShadowRet = ReturnType; +type ThresholdRet = ReturnType; + +/** + * This is made union and not intersection to avoid issues with + * `IllformedPlugin` and `WellFormedPlugin` when using typings with Jimp + * generic + * + * In reality, this should be an intersection but our type data isn't + * clever enough to figure out what's a class and what's not/etc + */ +type Plugins = + | BlitRet + | BlurRet + | CircleRet + | ColorRet + | ContainRet + | CoverRet + | CropRet + | DisplaceRet + | DitherRet + | FlipRet + | FisheyeRet + | GaussianRet + | InvertRet + | MaskRet + | NormalizeRet + | PrintRet + | ResizeRet + | RotateRet + | ScaleRet + | ShadowRet + | ThresholdRet; + +export default function (): Plugins; diff --git a/node_modules/@jimp/plugins/package.json b/node_modules/@jimp/plugins/package.json new file mode 100644 index 00000000..35c37031 --- /dev/null +++ b/node_modules/@jimp/plugins/package.json @@ -0,0 +1,51 @@ +{ + "name": "@jimp/plugins", + "version": "0.22.12", + "description": "Default Jimp plugin.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/plugin-blit": "^0.22.12", + "@jimp/plugin-blur": "^0.22.12", + "@jimp/plugin-circle": "^0.22.12", + "@jimp/plugin-color": "^0.22.12", + "@jimp/plugin-contain": "^0.22.12", + "@jimp/plugin-cover": "^0.22.12", + "@jimp/plugin-crop": "^0.22.12", + "@jimp/plugin-displace": "^0.22.12", + "@jimp/plugin-dither": "^0.22.12", + "@jimp/plugin-fisheye": "^0.22.12", + "@jimp/plugin-flip": "^0.22.12", + "@jimp/plugin-gaussian": "^0.22.12", + "@jimp/plugin-invert": "^0.22.12", + "@jimp/plugin-mask": "^0.22.12", + "@jimp/plugin-normalize": "^0.22.12", + "@jimp/plugin-print": "^0.22.12", + "@jimp/plugin-resize": "^0.22.12", + "@jimp/plugin-rotate": "^0.22.12", + "@jimp/plugin-scale": "^0.22.12", + "@jimp/plugin-shadow": "^0.22.12", + "@jimp/plugin-threshold": "^0.22.12", + "timm": "^1.6.1" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/plugins/src/index.js b/node_modules/@jimp/plugins/src/index.js new file mode 100644 index 00000000..a31740cf --- /dev/null +++ b/node_modules/@jimp/plugins/src/index.js @@ -0,0 +1,62 @@ +import { mergeDeep } from "timm"; + +import blit from "@jimp/plugin-blit"; +import blur from "@jimp/plugin-blur"; +import circle from "@jimp/plugin-circle"; +import color from "@jimp/plugin-color"; +import contain from "@jimp/plugin-contain"; +import cover from "@jimp/plugin-cover"; +import crop from "@jimp/plugin-crop"; +import displace from "@jimp/plugin-displace"; +import dither from "@jimp/plugin-dither"; +import fisheye from "@jimp/plugin-fisheye"; +import flip from "@jimp/plugin-flip"; +import gaussian from "@jimp/plugin-gaussian"; +import invert from "@jimp/plugin-invert"; +import mask from "@jimp/plugin-mask"; +import normalize from "@jimp/plugin-normalize"; +import print from "@jimp/plugin-print"; +import resize from "@jimp/plugin-resize"; +import rotate from "@jimp/plugin-rotate"; +import scale from "@jimp/plugin-scale"; +import shadow from "@jimp/plugin-shadow"; +import threshold from "@jimp/plugin-threshold"; + +const plugins = [ + blit, + blur, + circle, + color, + contain, + cover, + crop, + displace, + dither, + fisheye, + flip, + gaussian, + invert, + mask, + normalize, + print, + resize, + rotate, + scale, + shadow, + threshold, +]; + +export default (jimpEvChange) => { + const initializedPlugins = plugins.map((pluginModule) => { + let plugin = pluginModule(jimpEvChange) || {}; + + if (!plugin.class && !plugin.constants) { + // Default to class function + plugin = { class: plugin }; + } + + return plugin; + }); + + return mergeDeep(...initializedPlugins); +}; diff --git a/node_modules/@jimp/png/CHANGELOG.md b/node_modules/@jimp/png/CHANGELOG.md new file mode 100644 index 00000000..01459825 --- /dev/null +++ b/node_modules/@jimp/png/CHANGELOG.md @@ -0,0 +1,110 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.18.0 (Sun Feb 05 2023) + +### Release Notes + +#### switch from browserify to webpack ([#1140](https://github.com/jimp-dev/jimp/pull/1140)) + +This PR can be considered a breaking change as it remove the `jimp.min.js` file. + +Instead there is now only the `jimp.js` file and we ship source maps for it. + +We also configured the `browser` field so jimp will be automatically bundled better + +--- + +#### 💥 Breaking Change + +- switch from browserify to webpack [#1140](https://github.com/jimp-dev/jimp/pull/1140) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- update linting ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/png/LICENSE b/node_modules/@jimp/png/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/png/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/png/README.md b/node_modules/@jimp/png/README.md new file mode 100644 index 00000000..da13e482 --- /dev/null +++ b/node_modules/@jimp/png/README.md @@ -0,0 +1,35 @@ +
+ +

@jimp/png

+

Default Jimp png encoder/decoder.

+
+ +## Available Methods + +### Jimp.deflateLevel + +Sets the deflate level used when saving as PNG format (default is 9) + +### Jimp.deflateStrategy + +Sets the deflate strategy used when saving as PNG format (default is 3) + +### Jimp.filterType + +Sets the filter type used when saving as PNG format (default is automatic filters) + +### Jimp.colorType + +Sets the color type used when saving as PNG format (one of 0, 2, 4, 6) + +### Filter Types + +```js +Jimp.PNG_FILTER_AUTO; +Jimp.PNG_FILTER_NONE; +Jimp.PNG_FILTER_SUB; +Jimp.PNG_FILTER_UP; +Jimp.PNG_FILTER_AVERAGE; +Jimp.PNG_FILTER_PATH; +``` diff --git a/node_modules/@jimp/png/es/index.js b/node_modules/@jimp/png/es/index.js new file mode 100644 index 00000000..16e1397a --- /dev/null +++ b/node_modules/@jimp/png/es/index.js @@ -0,0 +1,130 @@ +import { PNG } from "pngjs"; +import { throwError, isNodePattern } from "@jimp/utils"; +const MIME_TYPE = "image/png"; + +// PNG filter types +const PNG_FILTER_AUTO = -1; +const PNG_FILTER_NONE = 0; +const PNG_FILTER_SUB = 1; +const PNG_FILTER_UP = 2; +const PNG_FILTER_AVERAGE = 3; +const PNG_FILTER_PATH = 4; +export default (() => ({ + mime: { + [MIME_TYPE]: ["png"] + }, + constants: { + MIME_PNG: MIME_TYPE, + PNG_FILTER_AUTO, + PNG_FILTER_NONE, + PNG_FILTER_SUB, + PNG_FILTER_UP, + PNG_FILTER_AVERAGE, + PNG_FILTER_PATH + }, + hasAlpha: { + [MIME_TYPE]: true + }, + decoders: { + [MIME_TYPE]: PNG.sync.read + }, + encoders: { + [MIME_TYPE](data) { + const png = new PNG({ + width: data.bitmap.width, + height: data.bitmap.height + }); + png.data = data.bitmap.data; + return PNG.sync.write(png, { + deflateLevel: data._deflateLevel, + deflateStrategy: data._deflateStrategy, + filterType: data._filterType, + colorType: typeof data._colorType === "number" ? data._colorType : data._rgba ? 6 : 2, + inputHasAlpha: data._rgba + }); + } + }, + class: { + _deflateLevel: 9, + _deflateStrategy: 3, + _filterType: PNG_FILTER_AUTO, + _colorType: null, + /** + * Sets the deflate level used when saving as PNG format (default is 9) + * @param {number} l Deflate level to use 0-9. 0 is no compression. 9 (default) is maximum compression. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + deflateLevel(l, cb) { + if (typeof l !== "number") { + return throwError.call(this, "l must be a number", cb); + } + if (l < 0 || l > 9) { + return throwError.call(this, "l must be a number 0 - 9", cb); + } + this._deflateLevel = Math.round(l); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Sets the deflate strategy used when saving as PNG format (default is 3) + * @param {number} s Deflate strategy to use 0-3. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + deflateStrategy(s, cb) { + if (typeof s !== "number") { + return throwError.call(this, "s must be a number", cb); + } + if (s < 0 || s > 3) { + return throwError.call(this, "s must be a number 0 - 3", cb); + } + this._deflateStrategy = Math.round(s); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Sets the filter type used when saving as PNG format (default is automatic filters) + * @param {number} f The quality to use -1-4. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + filterType(f, cb) { + if (typeof f !== "number") { + return throwError.call(this, "n must be a number", cb); + } + if (f < -1 || f > 4) { + return throwError.call(this, "n must be -1 (auto) or a number 0 - 4", cb); + } + this._filterType = Math.round(f); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + }, + /** + * Sets the color type used when saving as PNG format + * @param {number} s color type to use 0, 2, 4, 6. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + colorType(s, cb) { + if (typeof s !== "number") { + return throwError.call(this, "s must be a number", cb); + } + if (s !== 0 && s !== 2 && s !== 4 && s !== 6) { + return throwError.call(this, "s must be a number 0, 2, 4, 6.", cb); + } + this._colorType = Math.round(s); + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + return this; + } + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/png/es/index.js.map b/node_modules/@jimp/png/es/index.js.map new file mode 100644 index 00000000..e1070dae --- /dev/null +++ b/node_modules/@jimp/png/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["PNG","throwError","isNodePattern","MIME_TYPE","PNG_FILTER_AUTO","PNG_FILTER_NONE","PNG_FILTER_SUB","PNG_FILTER_UP","PNG_FILTER_AVERAGE","PNG_FILTER_PATH","mime","constants","MIME_PNG","hasAlpha","decoders","sync","read","encoders","data","png","width","bitmap","height","write","deflateLevel","_deflateLevel","deflateStrategy","_deflateStrategy","filterType","_filterType","colorType","_colorType","_rgba","inputHasAlpha","class","l","cb","call","Math","round","s","f"],"sources":["../src/index.js"],"sourcesContent":["import { PNG } from \"pngjs\";\nimport { throwError, isNodePattern } from \"@jimp/utils\";\n\nconst MIME_TYPE = \"image/png\";\n\n// PNG filter types\nconst PNG_FILTER_AUTO = -1;\nconst PNG_FILTER_NONE = 0;\nconst PNG_FILTER_SUB = 1;\nconst PNG_FILTER_UP = 2;\nconst PNG_FILTER_AVERAGE = 3;\nconst PNG_FILTER_PATH = 4;\n\nexport default () => ({\n mime: { [MIME_TYPE]: [\"png\"] },\n\n constants: {\n MIME_PNG: MIME_TYPE,\n PNG_FILTER_AUTO,\n PNG_FILTER_NONE,\n PNG_FILTER_SUB,\n PNG_FILTER_UP,\n PNG_FILTER_AVERAGE,\n PNG_FILTER_PATH,\n },\n\n hasAlpha: { [MIME_TYPE]: true },\n decoders: { [MIME_TYPE]: PNG.sync.read },\n encoders: {\n [MIME_TYPE](data) {\n const png = new PNG({\n width: data.bitmap.width,\n height: data.bitmap.height,\n });\n\n png.data = data.bitmap.data;\n\n return PNG.sync.write(png, {\n deflateLevel: data._deflateLevel,\n deflateStrategy: data._deflateStrategy,\n filterType: data._filterType,\n colorType:\n typeof data._colorType === \"number\"\n ? data._colorType\n : data._rgba\n ? 6\n : 2,\n inputHasAlpha: data._rgba,\n });\n },\n },\n\n class: {\n _deflateLevel: 9,\n _deflateStrategy: 3,\n _filterType: PNG_FILTER_AUTO,\n _colorType: null,\n\n /**\n * Sets the deflate level used when saving as PNG format (default is 9)\n * @param {number} l Deflate level to use 0-9. 0 is no compression. 9 (default) is maximum compression.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n deflateLevel(l, cb) {\n if (typeof l !== \"number\") {\n return throwError.call(this, \"l must be a number\", cb);\n }\n\n if (l < 0 || l > 9) {\n return throwError.call(this, \"l must be a number 0 - 9\", cb);\n }\n\n this._deflateLevel = Math.round(l);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Sets the deflate strategy used when saving as PNG format (default is 3)\n * @param {number} s Deflate strategy to use 0-3.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n deflateStrategy(s, cb) {\n if (typeof s !== \"number\") {\n return throwError.call(this, \"s must be a number\", cb);\n }\n\n if (s < 0 || s > 3) {\n return throwError.call(this, \"s must be a number 0 - 3\", cb);\n }\n\n this._deflateStrategy = Math.round(s);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n\n /**\n * Sets the filter type used when saving as PNG format (default is automatic filters)\n * @param {number} f The quality to use -1-4.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n filterType(f, cb) {\n if (typeof f !== \"number\") {\n return throwError.call(this, \"n must be a number\", cb);\n }\n\n if (f < -1 || f > 4) {\n return throwError.call(\n this,\n \"n must be -1 (auto) or a number 0 - 4\",\n cb\n );\n }\n\n this._filterType = Math.round(f);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n /**\n * Sets the color type used when saving as PNG format\n * @param {number} s color type to use 0, 2, 4, 6.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */ colorType(s, cb) {\n if (typeof s !== \"number\") {\n return throwError.call(this, \"s must be a number\", cb);\n }\n\n if (s !== 0 && s !== 2 && s !== 4 && s !== 6) {\n return throwError.call(this, \"s must be a number 0, 2, 4, 6.\", cb);\n }\n\n this._colorType = Math.round(s);\n\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n\n return this;\n },\n },\n});\n"],"mappings":"AAAA,SAASA,GAAG,QAAQ,OAAO;AAC3B,SAASC,UAAU,EAAEC,aAAa,QAAQ,aAAa;AAEvD,MAAMC,SAAS,GAAG,WAAW;;AAE7B;AACA,MAAMC,eA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imp/png/index.d.ts b/node_modules/@jimp/png/index.d.ts new file mode 100644 index 00000000..52bcda0c --- /dev/null +++ b/node_modules/@jimp/png/index.d.ts @@ -0,0 +1,40 @@ +import { DecoderFn, EncoderFn, ImageCallback } from "@jimp/core"; + +interface PNGClass { + _deflateLevel: number; + _deflateStrategy: number; + _filterType: number; + _colorType: number; + deflateLevel(l: number, cb?: ImageCallback): this; + deflateStrategy(s: number, cb?: ImageCallback): this; + filterType(f: number, cb?: ImageCallback): this; + colorType(s: number, cb?: ImageCallback): this; +} + +interface PNG { + mime: { "image/png": string[] }; + + hasAlpha: { "image/png": true }; + + decoders: { + "image/png": DecoderFn; + }; + encoders: { + "image/png": EncoderFn; + }; + + class: PNGClass; + + constants: { + MIME_PNG: "image/png"; + // PNG filter types + PNG_FILTER_AUTO: -1; + PNG_FILTER_NONE: 0; + PNG_FILTER_SUB: 1; + PNG_FILTER_UP: 2; + PNG_FILTER_AVERAGE: 3; + PNG_FILTER_PATH: 4; + }; +} + +export default function (): PNG; diff --git a/node_modules/@jimp/png/node_modules/pngjs/LICENSE b/node_modules/@jimp/png/node_modules/pngjs/LICENSE new file mode 100644 index 00000000..6942e254 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/LICENSE @@ -0,0 +1,20 @@ +pngjs2 original work Copyright (c) 2015 Luke Page & Original Contributors +pngjs derived work Copyright (c) 2012 Kuba Niegowski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/png/node_modules/pngjs/README.md b/node_modules/@jimp/png/node_modules/pngjs/README.md new file mode 100644 index 00000000..2aef03d9 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/README.md @@ -0,0 +1,433 @@ +[![Build Status](https://travis-ci.com/lukeapage/pngjs.svg?branch=master)](https://travis-ci.com/lukeapage/pngjs) [![Build status](https://ci.appveyor.com/api/projects/status/qo5x8ayutr028108/branch/master?svg=true)](https://ci.appveyor.com/project/lukeapage/pngjs/branch/master) [![codecov](https://codecov.io/gh/lukeapage/pngjs/branch/master/graph/badge.svg)](https://codecov.io/gh/lukeapage/pngjs) [![npm version](https://badge.fury.io/js/pngjs.svg)](http://badge.fury.io/js/pngjs) + +# pngjs + +Simple PNG encoder/decoder for Node.js with no dependencies. + +Based on the original [pngjs](https://github.com/niegowski/node-pngjs) with the follow enhancements. + +- Support for reading 1,2,4 & 16 bit files +- Support for reading interlace files +- Support for reading `tTRNS` transparent colours +- Support for writing colortype 0 (grayscale), colortype 2 (RGB), colortype 4 (grayscale alpha) and colortype 6 (RGBA) +- Sync interface as well as async +- API compatible with pngjs and node-pngjs + +Known lack of support for: + +- Extended PNG e.g. Animation +- Writing in colortype 3 (indexed color) + +# Table of Contents + +- [Requirements](#requirements) +- [Comparison Table](#comparison-table) +- [Tests](#tests) +- [Installation](#installation) +- [Browser](#browser) +- [Example](#example) +- [Async API](#async-api) +- [Sync API](#sync-api) +- [Changelog](#changelog) + +# Comparison Table + +| Name | Forked From | Sync | Async | 16 Bit | 1/2/4 Bit | Interlace | Gamma | Encodes | Tested | +| ------------- | ----------- | ---- | ----- | ------ | --------- | --------- | ------ | ------- | ------ | +| pngjs | | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | +| node-png | pngjs | No | Yes | No | No | No | Hidden | Yes | Manual | +| png-coder | pngjs | No | Yes | Yes | No | No | Hidden | Yes | Manual | +| pngparse | | No | Yes | No | Yes | No | No | No | Yes | +| pngparse-sync | pngparse | Yes | No | No | Yes | No | No | No | Yes | +| png-async | | No | Yes | No | No | No | No | Yes | Yes | +| png-js | | No | Yes | No | No | No | No | No | No | + +Native C++ node decoders: + +- png +- png-sync (sync version of above) +- pixel-png +- png-img + +# Tests + +Tested using [PNG Suite](http://www.schaik.com/pngsuite/). We read every file into pngjs, output it in standard 8bit colour, synchronously and asynchronously, then compare the original with the newly saved images. + +To run the tests, fetch the repo (tests are not distributed via npm) and install with `npm i`, run `npm test`. + +The only thing not converted is gamma correction - this is because multiple vendors will do gamma correction differently, so the tests will have different results on different browsers. + +# Installation + +``` +$ npm install pngjs --save +``` + +# Browser + +The package has been build with a [Browserify](browserify.org) version (`npm run browserify`) and you can use the browser version by including in your code: + +``` +import { PNG } from 'pngjs/browser'; +``` + +# Example + +```js +var fs = require("fs"), + PNG = require("pngjs").PNG; + +fs.createReadStream("in.png") + .pipe( + new PNG({ + filterType: 4, + }) + ) + .on("parsed", function () { + for (var y = 0; y < this.height; y++) { + for (var x = 0; x < this.width; x++) { + var idx = (this.width * y + x) << 2; + + // invert color + this.data[idx] = 255 - this.data[idx]; + this.data[idx + 1] = 255 - this.data[idx + 1]; + this.data[idx + 2] = 255 - this.data[idx + 2]; + + // and reduce opacity + this.data[idx + 3] = this.data[idx + 3] >> 1; + } + } + + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +For more examples see `examples` folder. + +# Async API + +As input any color type is accepted (grayscale, rgb, palette, grayscale with alpha, rgb with alpha) but 8 bit per sample (channel) is the only supported bit depth. Interlaced mode is not supported. + +## Class: PNG + +`PNG` is readable and writable `Stream`. + +### Options + +- `width` - use this with `height` if you want to create png from scratch +- `height` - as above +- `checkCRC` - whether parser should be strict about checksums in source stream (default: `true`) +- `deflateChunkSize` - chunk size used for deflating data chunks, this should be power of 2 and must not be less than 256 and more than 32\*1024 (default: 32 kB) +- `deflateLevel` - compression level for deflate (default: 9) +- `deflateStrategy` - compression strategy for deflate (default: 3) +- `deflateFactory` - deflate stream factory (default: `zlib.createDeflate`) +- `filterType` - png filtering method for scanlines (default: -1 => auto, accepts array of numbers 0-4) +- `colorType` - the output colorType - see constants. 0 = grayscale, no alpha, 2 = color, no alpha, 4 = grayscale & alpha, 6 = color & alpha. Default currently 6, but in the future may calculate best mode. +- `inputColorType` - the input colorType - see constants. Default is 6 (RGBA) +- `bitDepth` - the bitDepth of the output, 8 or 16 bits. Input data is expected to have this bit depth. + 16 bit data is expected in the system endianness (Default: 8) +- `inputHasAlpha` - whether the input bitmap has 4 bytes per pixel (rgb and alpha) or 3 (rgb - no alpha). +- `bgColor` - an object containing red, green, and blue values between 0 and 255 + that is used when packing a PNG if alpha is not to be included (default: 255,255,255) + +### Event "metadata" + +`function(metadata) { }` +Image's header has been parsed, metadata contains this information: + +- `width` image size in pixels +- `height` image size in pixels +- `palette` image is paletted +- `color` image is not grayscale +- `alpha` image contains alpha channel +- `interlace` image is interlaced + +### Event: "parsed" + +`function(data) { }` +Input image has been completely parsed, `data` is complete and ready for modification. + +### Event: "error" + +`function(error) { }` + +### png.parse(data, [callback]) + +Parses PNG file data. Can be `String` or `Buffer`. Alternatively you can stream data to instance of PNG. + +Optional `callback` is once called on `error` or `parsed`. The callback gets +two arguments `(err, data)`. + +Returns `this` for method chaining. + +#### Example + +```js +new PNG({ filterType: 4 }).parse(imageData, function (error, data) { + console.log(error, data); +}); +``` + +### png.pack() + +Starts converting data to PNG file Stream. + +Returns `this` for method chaining. + +### png.bitblt(dst, sx, sy, w, h, dx, dy) + +Helper for image manipulation, copies a rectangle of pixels from current (i.e. the source) image (`sx`, `sy`, `w`, `h`) to `dst` image (at `dx`, `dy`). + +Returns `this` for method chaining. + +For example, the following code copies the top-left 100x50 px of `in.png` into dst and writes it to `out.png`: + +```js +var dst = new PNG({ width: 100, height: 50 }); +fs.createReadStream("in.png") + .pipe(new PNG()) + .on("parsed", function () { + this.bitblt(dst, 0, 0, 100, 50, 0, 0); + dst.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +### Property: adjustGamma() + +Helper that takes data and adjusts it to be gamma corrected. Note that it is not 100% reliable with transparent colours because that requires knowing the background colour the bitmap is rendered on to. + +In tests against PNG suite it compared 100% with chrome on all 8 bit and below images. On IE there were some differences. + +The following example reads a file, adjusts the gamma (which sets the gamma to 0) and writes it out again, effectively removing any gamma correction from the image. + +```js +fs.createReadStream("in.png") + .pipe(new PNG()) + .on("parsed", function () { + this.adjustGamma(); + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +### Property: width + +Width of image in pixels + +### Property: height + +Height of image in pixels + +### Property: data + +Buffer of image pixel data. Every pixel consists 4 bytes: R, G, B, A (opacity). + +### Property: gamma + +Gamma of image (0 if not specified) + +## Packing a PNG and removing alpha (RGBA to RGB) + +When removing the alpha channel from an image, there needs to be a background color to correctly +convert each pixel's transparency to the appropriate RGB value. By default, pngjs will flatten +the image against a white background. You can override this in the options: + +```js +var fs = require("fs"), + PNG = require("pngjs").PNG; + +fs.createReadStream("in.png") + .pipe( + new PNG({ + colorType: 2, + bgColor: { + red: 0, + green: 255, + blue: 0, + }, + }) + ) + .on("parsed", function () { + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +# Sync API + +## PNG.sync + +### PNG.sync.read(buffer) + +Take a buffer and returns a PNG image. The properties on the image include the meta data and `data` as per the async API above. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +``` + +### PNG.sync.write(png) + +Take a PNG image and returns a buffer. The properties on the image include the meta data and `data` as per the async API above. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +var options = { colorType: 6 }; +var buffer = PNG.sync.write(png, options); +fs.writeFileSync('out.png', buffer); +``` + +### PNG.adjustGamma(src) + +Adjusts the gamma of a sync image. See the async adjustGamma. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +PNG.adjustGamma(png); +``` + +# Changelog + +### 6.0.0 - 24/10/2020 + +- BREAKING - Sync version now throws if there is unexpected content at the end of the stream. +- BREAKING - Drop support for node 10 (Though nothing incompatible in this release yet) +- Reduce the number of files included in the package + +### 5.1.0 - 13/09/2020 + +- Add option to skip rescaling + +### 5.0.0 - 15/04/2020 + +- Drop support for Node 8 +- Browserified bundle may now contain ES20(15-20) code if the supported node version supports it. Please run the browserified version through babel if you need to support older browsers. + +### 4.0.1 - 15/04/2020 + +- Fix to possible null reference in nextTick of async method + +### 4.0.0 - 09/04/2020 + +- Fix issue in newer nodes with using Buffer +- Fix async issue with some png files +- Drop support for Node 4 & 6 + +### 3.4.0 - 09/03/2019 + +- Include whether the png has alpha in the meta data +- emit an error if the image is truncated instead of hanging +- Add a browserified version +- speed up some mapping functions + +### 3.3.3 - 19/04/2018 + +- Real fix for node 9 + +### 3.3.2 - 16/02/2018 + +- Fix for node 9 + +### 3.3.1 - 15/11/2017 + +- Bugfixes and removal of es6 + +### 3.3.0 + +- Add writing 16 bit channels and support for grayscale input + +### 3.2.0 - 30/04/2017 + +- Support for encoding 8-bit grayscale images + +### 3.1.0 - 30/04/2017 + +- Support for pngs with zlib chunks that are malformed after valid data + +### 3.0.1 - 16/02/2017 + +- Fix single pixel pngs + +### 3.0.0 - 03/08/2016 + +- Drop support for node below v4 and iojs. Pin to 2.3.0 to use with old, unsupported or patched node versions. + +### 2.3.0 - 22/04/2016 + +- Support for sync in node 0.10 + +### 2.2.0 - 04/12/2015 + +- Add sync write api +- Fix newfile example +- Correct comparison table + +### 2.1.0 - 28/10/2015 + +- rename package to pngjs +- added 'bgColor' option + +### 2.0.0 - 08/10/2015 + +- fixes to readme +- _breaking change_ - bitblt on the png prototype now doesn't take a unused, unnecessary src first argument + +### 1.2.0 - 13/09/2015 + +- support passing colorType to write PNG's and writing bitmaps without alpha information + +### 1.1.0 - 07/09/2015 + +- support passing a deflate factory for controlled compression + +### 1.0.2 - 22/08/2015 + +- Expose all PNG creation info + +### 1.0.1 - 21/08/2015 + +- Fix non square interlaced files + +### 1.0.0 - 08/08/2015 + +- More tests +- source linted +- maintainability refactorings +- async API - exceptions in reading now emit warnings +- documentation improvement - sync api now documented, adjustGamma documented +- breaking change - gamma chunk is now written. previously a read then write would destroy gamma information, now it is persisted. + +### 0.0.3 - 03/08/2015 + +- Error handling fixes +- ignore files for smaller npm footprint + +### 0.0.2 - 02/08/2015 + +- Bugfixes to interlacing, support for transparent colours + +### 0.0.1 - 02/08/2015 + +- Initial release, see pngjs for older changelog. + +# License + +(The MIT License) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@jimp/png/node_modules/pngjs/browser.js b/node_modules/@jimp/png/node_modules/pngjs/browser.js new file mode 100644 index 00000000..9b7a5c1d --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/browser.js @@ -0,0 +1,18554 @@ +(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.png = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= data.length) { + throw new Error("Ran out of data"); + } + + let pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = data[rawPos + 1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, data, pxPos, rawPos) { + if (rawPos + 2 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = 0xff; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, data, pxPos, rawPos) { + if (rawPos + 3 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = data[rawPos + 3]; + }, +]; + +let pixelBppCustomMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = maxBit; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function (pxData, pixelData, pxPos) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = pixelData[1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = maxBit; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, pixelData, pxPos) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = pixelData[3]; + }, +]; + +function bitRetriever(data, depth) { + let leftOver = []; + let i = 0; + + function split() { + if (i === data.length) { + throw new Error("Ran out of data"); + } + let byte = data[i]; + i++; + let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1; + switch (depth) { + default: + throw new Error("unrecognised depth"); + case 16: + byte2 = data[i]; + i++; + leftOver.push((byte << 8) + byte2); + break; + case 4: + byte2 = byte & 0x0f; + byte1 = byte >> 4; + leftOver.push(byte1, byte2); + break; + case 2: + byte4 = byte & 3; + byte3 = (byte >> 2) & 3; + byte2 = (byte >> 4) & 3; + byte1 = (byte >> 6) & 3; + leftOver.push(byte1, byte2, byte3, byte4); + break; + case 1: + byte8 = byte & 1; + byte7 = (byte >> 1) & 1; + byte6 = (byte >> 2) & 1; + byte5 = (byte >> 3) & 1; + byte4 = (byte >> 4) & 1; + byte3 = (byte >> 5) & 1; + byte2 = (byte >> 6) & 1; + byte1 = (byte >> 7) & 1; + leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8); + break; + } + } + + return { + get: function (count) { + while (leftOver.length < count) { + split(); + } + let returner = leftOver.slice(0, count); + leftOver = leftOver.slice(count); + return returner; + }, + resetAfterLine: function () { + leftOver.length = 0; + }, + end: function () { + if (i !== data.length) { + throw new Error("extra data found"); + } + }, + }; +} + +function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pxPos = getPxPos(x, y, imagePass); + pixelBppMapper[bpp](pxData, data, pxPos, rawPos); + rawPos += bpp; //eslint-disable-line no-param-reassign + } + } + return rawPos; +} + +function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pixelData = bits.get(bpp); + let pxPos = getPxPos(x, y, imagePass); + pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); + } + bits.resetAfterLine(); + } +} + +exports.dataToBitMap = function (data, bitmapInfo) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let depth = bitmapInfo.depth; + let bpp = bitmapInfo.bpp; + let interlace = bitmapInfo.interlace; + let bits; + + if (depth !== 8) { + bits = bitRetriever(data, depth); + } + let pxData; + if (depth <= 8) { + pxData = Buffer.alloc(width * height * 4); + } else { + pxData = new Uint16Array(width * height * 4); + } + let maxBit = Math.pow(2, depth) - 1; + let rawPos = 0; + let images; + let getPxPos; + + if (interlace) { + images = interlaceUtils.getImagePasses(width, height); + getPxPos = interlaceUtils.getInterlaceIterator(width, height); + } else { + let nonInterlacedPxPos = 0; + getPxPos = function () { + let returner = nonInterlacedPxPos; + nonInterlacedPxPos += 4; + return returner; + }; + images = [{ width: width, height: height }]; + } + + for (let imageIndex = 0; imageIndex < images.length; imageIndex++) { + if (depth === 8) { + rawPos = mapImage8Bit( + images[imageIndex], + pxData, + getPxPos, + bpp, + data, + rawPos + ); + } else { + mapImageCustomBit( + images[imageIndex], + pxData, + getPxPos, + bpp, + bits, + maxBit + ); + } + } + if (depth === 8) { + if (rawPos !== data.length) { + throw new Error("extra data found"); + } + } else { + bits.end(); + } + + return pxData; +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./interlace":11,"buffer":33}],2:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let constants = require("./constants"); + +module.exports = function (dataIn, width, height, options) { + let outHasAlpha = + [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf( + options.colorType + ) !== -1; + if (options.colorType === options.inputColorType) { + let bigEndian = (function () { + let buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] !== 256; + })(); + // If no need to convert to grayscale and alpha is present/absent in both, take a fast route + if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) { + return dataIn; + } + } + + // map to a UInt16 array if data is 16bit, fix endianness below + let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); + + let maxValue = 255; + let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType]; + if (inBpp === 4 && !options.inputHasAlpha) { + inBpp = 3; + } + let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType]; + if (options.bitDepth === 16) { + maxValue = 65535; + outBpp *= 2; + } + let outData = Buffer.alloc(width * height * outBpp); + + let inIndex = 0; + let outIndex = 0; + + let bgColor = options.bgColor || {}; + if (bgColor.red === undefined) { + bgColor.red = maxValue; + } + if (bgColor.green === undefined) { + bgColor.green = maxValue; + } + if (bgColor.blue === undefined) { + bgColor.blue = maxValue; + } + + function getRGBA() { + let red; + let green; + let blue; + let alpha = maxValue; + switch (options.inputColorType) { + case constants.COLORTYPE_COLOR_ALPHA: + alpha = data[inIndex + 3]; + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_COLOR: + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_ALPHA: + alpha = data[inIndex + 1]; + red = data[inIndex]; + green = red; + blue = red; + break; + case constants.COLORTYPE_GRAYSCALE: + red = data[inIndex]; + green = red; + blue = red; + break; + default: + throw new Error( + "input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + + if (options.inputHasAlpha) { + if (!outHasAlpha) { + alpha /= maxValue; + red = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), + maxValue + ); + green = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), + maxValue + ); + blue = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), + maxValue + ); + } + } + return { red: red, green: green, blue: blue, alpha: alpha }; + } + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let rgba = getRGBA(data, inIndex); + + switch (options.colorType) { + case constants.COLORTYPE_COLOR_ALPHA: + case constants.COLORTYPE_COLOR: + if (options.bitDepth === 8) { + outData[outIndex] = rgba.red; + outData[outIndex + 1] = rgba.green; + outData[outIndex + 2] = rgba.blue; + if (outHasAlpha) { + outData[outIndex + 3] = rgba.alpha; + } + } else { + outData.writeUInt16BE(rgba.red, outIndex); + outData.writeUInt16BE(rgba.green, outIndex + 2); + outData.writeUInt16BE(rgba.blue, outIndex + 4); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 6); + } + } + break; + case constants.COLORTYPE_ALPHA: + case constants.COLORTYPE_GRAYSCALE: { + // Convert to grayscale and alpha + let grayscale = (rgba.red + rgba.green + rgba.blue) / 3; + if (options.bitDepth === 8) { + outData[outIndex] = grayscale; + if (outHasAlpha) { + outData[outIndex + 1] = rgba.alpha; + } + } else { + outData.writeUInt16BE(grayscale, outIndex); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 2); + } + } + break; + } + default: + throw new Error("unrecognised color Type " + options.colorType); + } + + inIndex += inBpp; + outIndex += outBpp; + } + } + + return outData; +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./constants":4,"buffer":33}],3:[function(require,module,exports){ +(function (process,Buffer){(function (){ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); + +let ChunkStream = (module.exports = function () { + Stream.call(this); + + this._buffers = []; + this._buffered = 0; + + this._reads = []; + this._paused = false; + + this._encoding = "utf8"; + this.writable = true; +}); +util.inherits(ChunkStream, Stream); + +ChunkStream.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); + + process.nextTick( + function () { + this._process(); + + // its paused and there is not enought data then ask for more + if (this._paused && this._reads && this._reads.length > 0) { + this._paused = false; + + this.emit("drain"); + } + }.bind(this) + ); +}; + +ChunkStream.prototype.write = function (data, encoding) { + if (!this.writable) { + this.emit("error", new Error("Stream not writable")); + return false; + } + + let dataBuffer; + if (Buffer.isBuffer(data)) { + dataBuffer = data; + } else { + dataBuffer = Buffer.from(data, encoding || this._encoding); + } + + this._buffers.push(dataBuffer); + this._buffered += dataBuffer.length; + + this._process(); + + // ok if there are no more read requests + if (this._reads && this._reads.length === 0) { + this._paused = true; + } + + return this.writable && !this._paused; +}; + +ChunkStream.prototype.end = function (data, encoding) { + if (data) { + this.write(data, encoding); + } + + this.writable = false; + + // already destroyed + if (!this._buffers) { + return; + } + + // enqueue or handle end + if (this._buffers.length === 0) { + this._end(); + } else { + this._buffers.push(null); + this._process(); + } +}; + +ChunkStream.prototype.destroySoon = ChunkStream.prototype.end; + +ChunkStream.prototype._end = function () { + if (this._reads.length > 0) { + this.emit("error", new Error("Unexpected end of input")); + } + + this.destroy(); +}; + +ChunkStream.prototype.destroy = function () { + if (!this._buffers) { + return; + } + + this.writable = false; + this._reads = null; + this._buffers = null; + + this.emit("close"); +}; + +ChunkStream.prototype._processReadAllowingLess = function (read) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + // first we need to peek into first buffer + let smallerBuf = this._buffers[0]; + + // ok there is more data than we need + if (smallerBuf.length > read.length) { + this._buffered -= read.length; + this._buffers[0] = smallerBuf.slice(read.length); + + read.func.call(this, smallerBuf.slice(0, read.length)); + } else { + // ok this is less than maximum length so use it all + this._buffered -= smallerBuf.length; + this._buffers.shift(); // == smallerBuf + + read.func.call(this, smallerBuf); + } +}; + +ChunkStream.prototype._processRead = function (read) { + this._reads.shift(); // == read + + let pos = 0; + let count = 0; + let data = Buffer.alloc(read.length); + + // create buffer for all data + while (pos < read.length) { + let buf = this._buffers[count++]; + let len = Math.min(buf.length, read.length - pos); + + buf.copy(data, pos, 0, len); + pos += len; + + // last buffer wasn't used all so just slice it and leave + if (len !== buf.length) { + this._buffers[--count] = buf.slice(len); + } + } + + // remove all used buffers + if (count > 0) { + this._buffers.splice(0, count); + } + + this._buffered -= read.length; + + read.func.call(this, data); +}; + +ChunkStream.prototype._process = function () { + try { + // as long as there is any data and read requests + while (this._buffered > 0 && this._reads && this._reads.length > 0) { + let read = this._reads[0]; + + // read any data (but no more than length) + if (read.allowLess) { + this._processReadAllowingLess(read); + } else if (this._buffered >= read.length) { + // ok we can meet some expectations + + this._processRead(read); + } else { + // not enought data to satisfy first request in queue + // so we need to wait for more + break; + } + } + + if (this._buffers && !this.writable) { + this._end(); + } + } catch (ex) { + this.emit("error", ex); + } +}; + +}).call(this)}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":60,"buffer":33,"stream":61,"util":81}],4:[function(require,module,exports){ +"use strict"; + +module.exports = { + PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], + + TYPE_IHDR: 0x49484452, + TYPE_IEND: 0x49454e44, + TYPE_IDAT: 0x49444154, + TYPE_PLTE: 0x504c5445, + TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase + TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase + + // color-type bits + COLORTYPE_GRAYSCALE: 0, + COLORTYPE_PALETTE: 1, + COLORTYPE_COLOR: 2, + COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha + + // color-type combinations + COLORTYPE_PALETTE_COLOR: 3, + COLORTYPE_COLOR_ALPHA: 6, + + COLORTYPE_TO_BPP_MAP: { + 0: 1, + 2: 3, + 3: 1, + 4: 2, + 6: 4, + }, + + GAMMA_DIVISION: 100000, +}; + +},{}],5:[function(require,module,exports){ +"use strict"; + +let crcTable = []; + +(function () { + for (let i = 0; i < 256; i++) { + let currentCrc = i; + for (let j = 0; j < 8; j++) { + if (currentCrc & 1) { + currentCrc = 0xedb88320 ^ (currentCrc >>> 1); + } else { + currentCrc = currentCrc >>> 1; + } + } + crcTable[i] = currentCrc; + } +})(); + +let CrcCalculator = (module.exports = function () { + this._crc = -1; +}); + +CrcCalculator.prototype.write = function (data) { + for (let i = 0; i < data.length; i++) { + this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8); + } + return true; +}; + +CrcCalculator.prototype.crc32 = function () { + return this._crc ^ -1; +}; + +CrcCalculator.crc32 = function (buf) { + let crc = -1; + for (let i = 0; i < buf.length; i++) { + crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return crc ^ -1; +}; + +},{}],6:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let paethPredictor = require("./paeth-predictor"); + +function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + rawData[rawPos + x] = pxData[pxPos + x]; + } +} + +function filterSumNone(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + + for (let i = pxPos; i < length; i++) { + sum += Math.abs(pxData[i]); + } + return sum; +} + +function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + rawData[rawPos + x] = val; + } +} + +function filterSumSub(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + sum += Math.abs(val); + } + + return sum; +} + +function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - up; + + rawData[rawPos + x] = val; + } +} + +function filterSumUp(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + for (let x = pxPos; x < length; x++) { + let up = pxPos > 0 ? pxData[x - byteWidth] : 0; + let val = pxData[x] - up; + + sum += Math.abs(val); + } + + return sum; +} + +function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + rawData[rawPos + x] = val; + } +} + +function filterSumAvg(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + sum += Math.abs(val); + } + + return sum; +} + +function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + rawData[rawPos + x] = val; + } +} + +function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + sum += Math.abs(val); + } + + return sum; +} + +let filters = { + 0: filterNone, + 1: filterSub, + 2: filterUp, + 3: filterAvg, + 4: filterPaeth, +}; + +let filterSums = { + 0: filterSumNone, + 1: filterSumSub, + 2: filterSumUp, + 3: filterSumAvg, + 4: filterSumPaeth, +}; + +module.exports = function (pxData, width, height, options, bpp) { + let filterTypes; + if (!("filterType" in options) || options.filterType === -1) { + filterTypes = [0, 1, 2, 3, 4]; + } else if (typeof options.filterType === "number") { + filterTypes = [options.filterType]; + } else { + throw new Error("unrecognised filter types"); + } + + if (options.bitDepth === 16) { + bpp *= 2; + } + let byteWidth = width * bpp; + let rawPos = 0; + let pxPos = 0; + let rawData = Buffer.alloc((byteWidth + 1) * height); + + let sel = filterTypes[0]; + + for (let y = 0; y < height; y++) { + if (filterTypes.length > 1) { + // find best filter for this line (with lowest sum of values) + let min = Infinity; + + for (let i = 0; i < filterTypes.length; i++) { + let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp); + if (sum < min) { + sel = filterTypes[i]; + min = sum; + } + } + } + + rawData[rawPos] = sel; + rawPos++; + filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); + rawPos += byteWidth; + pxPos += byteWidth; + } + return rawData; +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./paeth-predictor":15,"buffer":33}],7:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let util = require("util"); +let ChunkStream = require("./chunkstream"); +let Filter = require("./filter-parse"); + +let FilterAsync = (module.exports = function (bitmapInfo) { + ChunkStream.call(this); + + let buffers = []; + let that = this; + this._filter = new Filter(bitmapInfo, { + read: this.read.bind(this), + write: function (buffer) { + buffers.push(buffer); + }, + complete: function () { + that.emit("complete", Buffer.concat(buffers)); + }, + }); + + this._filter.start(); +}); +util.inherits(FilterAsync, ChunkStream); + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./chunkstream":3,"./filter-parse":9,"buffer":33,"util":81}],8:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let SyncReader = require("./sync-reader"); +let Filter = require("./filter-parse"); + +exports.process = function (inBuffer, bitmapInfo) { + let outBuffers = []; + let reader = new SyncReader(inBuffer); + let filter = new Filter(bitmapInfo, { + read: reader.read.bind(reader), + write: function (bufferPart) { + outBuffers.push(bufferPart); + }, + complete: function () {}, + }); + + filter.start(); + reader.process(); + + return Buffer.concat(outBuffers); +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./filter-parse":9,"./sync-reader":22,"buffer":33}],9:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let interlaceUtils = require("./interlace"); +let paethPredictor = require("./paeth-predictor"); + +function getByteWidth(width, bpp, depth) { + let byteWidth = width * bpp; + if (depth !== 8) { + byteWidth = Math.ceil(byteWidth / (8 / depth)); + } + return byteWidth; +} + +let Filter = (module.exports = function (bitmapInfo, dependencies) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let interlace = bitmapInfo.interlace; + let bpp = bitmapInfo.bpp; + let depth = bitmapInfo.depth; + + this.read = dependencies.read; + this.write = dependencies.write; + this.complete = dependencies.complete; + + this._imageIndex = 0; + this._images = []; + if (interlace) { + let passes = interlaceUtils.getImagePasses(width, height); + for (let i = 0; i < passes.length; i++) { + this._images.push({ + byteWidth: getByteWidth(passes[i].width, bpp, depth), + height: passes[i].height, + lineIndex: 0, + }); + } + } else { + this._images.push({ + byteWidth: getByteWidth(width, bpp, depth), + height: height, + lineIndex: 0, + }); + } + + // when filtering the line we look at the pixel to the left + // the spec also says it is done on a byte level regardless of the number of pixels + // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back + // a pixel rather than just a different byte part. However if we are sub byte, we ignore. + if (depth === 8) { + this._xComparison = bpp; + } else if (depth === 16) { + this._xComparison = bpp * 2; + } else { + this._xComparison = 1; + } +}); + +Filter.prototype.start = function () { + this.read( + this._images[this._imageIndex].byteWidth + 1, + this._reverseFilterLine.bind(this) + ); +}; + +Filter.prototype._unFilterType1 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + unfilteredLine[x] = rawByte + f1Left; + } +}; + +Filter.prototype._unFilterType2 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f2Up = lastLine ? lastLine[x] : 0; + unfilteredLine[x] = rawByte + f2Up; + } +}; + +Filter.prototype._unFilterType3 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f3Up = lastLine ? lastLine[x] : 0; + let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f3Add = Math.floor((f3Left + f3Up) / 2); + unfilteredLine[x] = rawByte + f3Add; + } +}; + +Filter.prototype._unFilterType4 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f4Up = lastLine ? lastLine[x] : 0; + let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; + let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); + unfilteredLine[x] = rawByte + f4Add; + } +}; + +Filter.prototype._reverseFilterLine = function (rawData) { + let filter = rawData[0]; + let unfilteredLine; + let currentImage = this._images[this._imageIndex]; + let byteWidth = currentImage.byteWidth; + + if (filter === 0) { + unfilteredLine = rawData.slice(1, byteWidth + 1); + } else { + unfilteredLine = Buffer.alloc(byteWidth); + + switch (filter) { + case 1: + this._unFilterType1(rawData, unfilteredLine, byteWidth); + break; + case 2: + this._unFilterType2(rawData, unfilteredLine, byteWidth); + break; + case 3: + this._unFilterType3(rawData, unfilteredLine, byteWidth); + break; + case 4: + this._unFilterType4(rawData, unfilteredLine, byteWidth); + break; + default: + throw new Error("Unrecognised filter type - " + filter); + } + } + + this.write(unfilteredLine); + + currentImage.lineIndex++; + if (currentImage.lineIndex >= currentImage.height) { + this._lastLine = null; + this._imageIndex++; + currentImage = this._images[this._imageIndex]; + } else { + this._lastLine = unfilteredLine; + } + + if (currentImage) { + // read, using the byte width that may be from the new current image + this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this)); + } else { + this._lastLine = null; + this.complete(); + } +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./interlace":11,"./paeth-predictor":15,"buffer":33}],10:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +function dePalette(indata, outdata, width, height, palette) { + let pxPos = 0; + // use values from palette + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let color = palette[indata[pxPos]]; + + if (!color) { + throw new Error("index " + indata[pxPos] + " not in palette"); + } + + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = color[i]; + } + pxPos += 4; + } + } +} + +function replaceTransparentColor(indata, outdata, width, height, transColor) { + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let makeTrans = false; + + if (transColor.length === 1) { + if (transColor[0] === indata[pxPos]) { + makeTrans = true; + } + } else if ( + transColor[0] === indata[pxPos] && + transColor[1] === indata[pxPos + 1] && + transColor[2] === indata[pxPos + 2] + ) { + makeTrans = true; + } + if (makeTrans) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = 0; + } + } + pxPos += 4; + } + } +} + +function scaleDepth(indata, outdata, width, height, depth) { + let maxOutSample = 255; + let maxInSample = Math.pow(2, depth) - 1; + let pxPos = 0; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = Math.floor( + (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5 + ); + } + pxPos += 4; + } + } +} + +module.exports = function (indata, imageData, skipRescale = false) { + let depth = imageData.depth; + let width = imageData.width; + let height = imageData.height; + let colorType = imageData.colorType; + let transColor = imageData.transColor; + let palette = imageData.palette; + + let outdata = indata; // only different for 16 bits + + if (colorType === 3) { + // paletted + dePalette(indata, outdata, width, height, palette); + } else { + if (transColor) { + replaceTransparentColor(indata, outdata, width, height, transColor); + } + // if it needs scaling + if (depth !== 8 && !skipRescale) { + // if we need to change the buffer size + if (depth === 16) { + outdata = Buffer.alloc(width * height * 4); + } + scaleDepth(indata, outdata, width, height, depth); + } + } + return outdata; +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":33}],11:[function(require,module,exports){ +"use strict"; + +// Adam 7 +// 0 1 2 3 4 5 6 7 +// 0 x 6 4 6 x 6 4 6 +// 1 7 7 7 7 7 7 7 7 +// 2 5 6 5 6 5 6 5 6 +// 3 7 7 7 7 7 7 7 7 +// 4 3 6 4 6 3 6 4 6 +// 5 7 7 7 7 7 7 7 7 +// 6 5 6 5 6 5 6 5 6 +// 7 7 7 7 7 7 7 7 7 + +let imagePasses = [ + { + // pass 1 - 1px + x: [0], + y: [0], + }, + { + // pass 2 - 1px + x: [4], + y: [0], + }, + { + // pass 3 - 2px + x: [0, 4], + y: [4], + }, + { + // pass 4 - 4px + x: [2, 6], + y: [0, 4], + }, + { + // pass 5 - 8px + x: [0, 2, 4, 6], + y: [2, 6], + }, + { + // pass 6 - 16px + x: [1, 3, 5, 7], + y: [0, 2, 4, 6], + }, + { + // pass 7 - 32px + x: [0, 1, 2, 3, 4, 5, 6, 7], + y: [1, 3, 5, 7], + }, +]; + +exports.getImagePasses = function (width, height) { + let images = []; + let xLeftOver = width % 8; + let yLeftOver = height % 8; + let xRepeats = (width - xLeftOver) / 8; + let yRepeats = (height - yLeftOver) / 8; + for (let i = 0; i < imagePasses.length; i++) { + let pass = imagePasses[i]; + let passWidth = xRepeats * pass.x.length; + let passHeight = yRepeats * pass.y.length; + for (let j = 0; j < pass.x.length; j++) { + if (pass.x[j] < xLeftOver) { + passWidth++; + } else { + break; + } + } + for (let j = 0; j < pass.y.length; j++) { + if (pass.y[j] < yLeftOver) { + passHeight++; + } else { + break; + } + } + if (passWidth > 0 && passHeight > 0) { + images.push({ width: passWidth, height: passHeight, index: i }); + } + } + return images; +}; + +exports.getInterlaceIterator = function (width) { + return function (x, y, pass) { + let outerXLeftOver = x % imagePasses[pass].x.length; + let outerX = + ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 + + imagePasses[pass].x[outerXLeftOver]; + let outerYLeftOver = y % imagePasses[pass].y.length; + let outerY = + ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 + + imagePasses[pass].y[outerYLeftOver]; + return outerX * 4 + outerY * width * 4; + }; +}; + +},{}],12:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let constants = require("./constants"); +let Packer = require("./packer"); + +let PackerAsync = (module.exports = function (opt) { + Stream.call(this); + + let options = opt || {}; + + this._packer = new Packer(options); + this._deflate = this._packer.createDeflate(); + + this.readable = true; +}); +util.inherits(PackerAsync, Stream); + +PackerAsync.prototype.pack = function (data, width, height, gamma) { + // Signature + this.emit("data", Buffer.from(constants.PNG_SIGNATURE)); + this.emit("data", this._packer.packIHDR(width, height)); + + if (gamma) { + this.emit("data", this._packer.packGAMA(gamma)); + } + + let filteredData = this._packer.filterData(data, width, height); + + // compress it + this._deflate.on("error", this.emit.bind(this, "error")); + + this._deflate.on( + "data", + function (compressedData) { + this.emit("data", this._packer.packIDAT(compressedData)); + }.bind(this) + ); + + this._deflate.on( + "end", + function () { + this.emit("data", this._packer.packIEND()); + this.emit("end"); + }.bind(this) + ); + + this._deflate.end(filteredData); +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./constants":4,"./packer":14,"buffer":33,"stream":61,"util":81}],13:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let constants = require("./constants"); +let Packer = require("./packer"); + +module.exports = function (metaData, opt) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let options = opt || {}; + + let packer = new Packer(options); + + let chunks = []; + + // Signature + chunks.push(Buffer.from(constants.PNG_SIGNATURE)); + + // Header + chunks.push(packer.packIHDR(metaData.width, metaData.height)); + + if (metaData.gamma) { + chunks.push(packer.packGAMA(metaData.gamma)); + } + + let filteredData = packer.filterData( + metaData.data, + metaData.width, + metaData.height + ); + + // compress it + let compressedData = zlib.deflateSync( + filteredData, + packer.getDeflateOptions() + ); + filteredData = null; + + if (!compressedData || !compressedData.length) { + throw new Error("bad png - invalid compressed data response"); + } + chunks.push(packer.packIDAT(compressedData)); + + // End + chunks.push(packer.packIEND()); + + return Buffer.concat(chunks); +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./constants":4,"./packer":14,"buffer":33,"zlib":32}],14:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let constants = require("./constants"); +let CrcStream = require("./crc"); +let bitPacker = require("./bitpacker"); +let filter = require("./filter-pack"); +let zlib = require("zlib"); + +let Packer = (module.exports = function (options) { + this._options = options; + + options.deflateChunkSize = options.deflateChunkSize || 32 * 1024; + options.deflateLevel = + options.deflateLevel != null ? options.deflateLevel : 9; + options.deflateStrategy = + options.deflateStrategy != null ? options.deflateStrategy : 3; + options.inputHasAlpha = + options.inputHasAlpha != null ? options.inputHasAlpha : true; + options.deflateFactory = options.deflateFactory || zlib.createDeflate; + options.bitDepth = options.bitDepth || 8; + // This is outputColorType + options.colorType = + typeof options.colorType === "number" + ? options.colorType + : constants.COLORTYPE_COLOR_ALPHA; + options.inputColorType = + typeof options.inputColorType === "number" + ? options.inputColorType + : constants.COLORTYPE_COLOR_ALPHA; + + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.colorType) === -1 + ) { + throw new Error( + "option color type:" + options.colorType + " is not supported at present" + ); + } + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.inputColorType) === -1 + ) { + throw new Error( + "option input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + if (options.bitDepth !== 8 && options.bitDepth !== 16) { + throw new Error( + "option bit depth:" + options.bitDepth + " is not supported at present" + ); + } +}); + +Packer.prototype.getDeflateOptions = function () { + return { + chunkSize: this._options.deflateChunkSize, + level: this._options.deflateLevel, + strategy: this._options.deflateStrategy, + }; +}; + +Packer.prototype.createDeflate = function () { + return this._options.deflateFactory(this.getDeflateOptions()); +}; + +Packer.prototype.filterData = function (data, width, height) { + // convert to correct format for filtering (e.g. right bpp and bit depth) + let packedData = bitPacker(data, width, height, this._options); + + // filter pixel data + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType]; + let filteredData = filter(packedData, width, height, this._options, bpp); + return filteredData; +}; + +Packer.prototype._packChunk = function (type, data) { + let len = data ? data.length : 0; + let buf = Buffer.alloc(len + 12); + + buf.writeUInt32BE(len, 0); + buf.writeUInt32BE(type, 4); + + if (data) { + data.copy(buf, 8); + } + + buf.writeInt32BE( + CrcStream.crc32(buf.slice(4, buf.length - 4)), + buf.length - 4 + ); + return buf; +}; + +Packer.prototype.packGAMA = function (gamma) { + let buf = Buffer.alloc(4); + buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0); + return this._packChunk(constants.TYPE_gAMA, buf); +}; + +Packer.prototype.packIHDR = function (width, height) { + let buf = Buffer.alloc(13); + buf.writeUInt32BE(width, 0); + buf.writeUInt32BE(height, 4); + buf[8] = this._options.bitDepth; // Bit depth + buf[9] = this._options.colorType; // colorType + buf[10] = 0; // compression + buf[11] = 0; // filter + buf[12] = 0; // interlace + + return this._packChunk(constants.TYPE_IHDR, buf); +}; + +Packer.prototype.packIDAT = function (data) { + return this._packChunk(constants.TYPE_IDAT, data); +}; + +Packer.prototype.packIEND = function () { + return this._packChunk(constants.TYPE_IEND, null); +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./bitpacker":2,"./constants":4,"./crc":5,"./filter-pack":6,"buffer":33,"zlib":32}],15:[function(require,module,exports){ +"use strict"; + +module.exports = function paethPredictor(left, above, upLeft) { + let paeth = left + above - upLeft; + let pLeft = Math.abs(paeth - left); + let pAbove = Math.abs(paeth - above); + let pUpLeft = Math.abs(paeth - upLeft); + + if (pLeft <= pAbove && pLeft <= pUpLeft) { + return left; + } + if (pAbove <= pUpLeft) { + return above; + } + return upLeft; +}; + +},{}],16:[function(require,module,exports){ +"use strict"; + +let util = require("util"); +let zlib = require("zlib"); +let ChunkStream = require("./chunkstream"); +let FilterAsync = require("./filter-parse-async"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +let ParserAsync = (module.exports = function (options) { + ChunkStream.call(this); + + this._parser = new Parser(options, { + read: this.read.bind(this), + error: this._handleError.bind(this), + metadata: this._handleMetaData.bind(this), + gamma: this.emit.bind(this, "gamma"), + palette: this._handlePalette.bind(this), + transColor: this._handleTransColor.bind(this), + finished: this._finished.bind(this), + inflateData: this._inflateData.bind(this), + simpleTransparency: this._simpleTransparency.bind(this), + headersFinished: this._headersFinished.bind(this), + }); + this._options = options; + this.writable = true; + + this._parser.start(); +}); +util.inherits(ParserAsync, ChunkStream); + +ParserAsync.prototype._handleError = function (err) { + this.emit("error", err); + + this.writable = false; + + this.destroy(); + + if (this._inflate && this._inflate.destroy) { + this._inflate.destroy(); + } + + if (this._filter) { + this._filter.destroy(); + // For backward compatibility with Node 7 and below. + // Suppress errors due to _inflate calling write() even after + // it's destroy()'ed. + this._filter.on("error", function () {}); + } + + this.errord = true; +}; + +ParserAsync.prototype._inflateData = function (data) { + if (!this._inflate) { + if (this._bitmapInfo.interlace) { + this._inflate = zlib.createInflate(); + + this._inflate.on("error", this.emit.bind(this, "error")); + this._filter.on("complete", this._complete.bind(this)); + + this._inflate.pipe(this._filter); + } else { + let rowSize = + ((this._bitmapInfo.width * + this._bitmapInfo.bpp * + this._bitmapInfo.depth + + 7) >> + 3) + + 1; + let imageSize = rowSize * this._bitmapInfo.height; + let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); + + this._inflate = zlib.createInflate({ chunkSize: chunkSize }); + let leftToInflate = imageSize; + + let emitError = this.emit.bind(this, "error"); + this._inflate.on("error", function (err) { + if (!leftToInflate) { + return; + } + + emitError(err); + }); + this._filter.on("complete", this._complete.bind(this)); + + let filterWrite = this._filter.write.bind(this._filter); + this._inflate.on("data", function (chunk) { + if (!leftToInflate) { + return; + } + + if (chunk.length > leftToInflate) { + chunk = chunk.slice(0, leftToInflate); + } + + leftToInflate -= chunk.length; + + filterWrite(chunk); + }); + + this._inflate.on("end", this._filter.end.bind(this._filter)); + } + } + this._inflate.write(data); +}; + +ParserAsync.prototype._handleMetaData = function (metaData) { + this._metaData = metaData; + this._bitmapInfo = Object.create(metaData); + + this._filter = new FilterAsync(this._bitmapInfo); +}; + +ParserAsync.prototype._handleTransColor = function (transColor) { + this._bitmapInfo.transColor = transColor; +}; + +ParserAsync.prototype._handlePalette = function (palette) { + this._bitmapInfo.palette = palette; +}; + +ParserAsync.prototype._simpleTransparency = function () { + this._metaData.alpha = true; +}; + +ParserAsync.prototype._headersFinished = function () { + // Up until this point, we don't know if we have a tRNS chunk (alpha) + // so we can't emit metadata any earlier + this.emit("metadata", this._metaData); +}; + +ParserAsync.prototype._finished = function () { + if (this.errord) { + return; + } + + if (!this._inflate) { + this.emit("error", "No Inflate block"); + } else { + // no more data to inflate + this._inflate.end(); + } +}; + +ParserAsync.prototype._complete = function (filteredData) { + if (this.errord) { + return; + } + + let normalisedBitmapData; + + try { + let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); + + normalisedBitmapData = formatNormaliser( + bitmapData, + this._bitmapInfo, + this._options.skipRescale + ); + bitmapData = null; + } catch (ex) { + this._handleError(ex); + return; + } + + this.emit("parsed", normalisedBitmapData); +}; + +},{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,"util":81,"zlib":32}],17:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +let inflateSync = require("./sync-inflate"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let SyncReader = require("./sync-reader"); +let FilterSync = require("./filter-parse-sync"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +module.exports = function (buffer, options) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let err; + function handleError(_err_) { + err = _err_; + } + + let metaData; + function handleMetaData(_metaData_) { + metaData = _metaData_; + } + + function handleTransColor(transColor) { + metaData.transColor = transColor; + } + + function handlePalette(palette) { + metaData.palette = palette; + } + + function handleSimpleTransparency() { + metaData.alpha = true; + } + + let gamma; + function handleGamma(_gamma_) { + gamma = _gamma_; + } + + let inflateDataList = []; + function handleInflateData(inflatedData) { + inflateDataList.push(inflatedData); + } + + let reader = new SyncReader(buffer); + + let parser = new Parser(options, { + read: reader.read.bind(reader), + error: handleError, + metadata: handleMetaData, + gamma: handleGamma, + palette: handlePalette, + transColor: handleTransColor, + inflateData: handleInflateData, + simpleTransparency: handleSimpleTransparency, + }); + + parser.start(); + reader.process(); + + if (err) { + throw err; + } + + //join together the inflate datas + let inflateData = Buffer.concat(inflateDataList); + inflateDataList.length = 0; + + let inflatedData; + if (metaData.interlace) { + inflatedData = zlib.inflateSync(inflateData); + } else { + let rowSize = + ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1; + let imageSize = rowSize * metaData.height; + inflatedData = inflateSync(inflateData, { + chunkSize: imageSize, + maxLength: imageSize, + }); + } + inflateData = null; + + if (!inflatedData || !inflatedData.length) { + throw new Error("bad png - invalid inflate data response"); + } + + let unfilteredData = FilterSync.process(inflatedData, metaData); + inflateData = null; + + let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); + unfilteredData = null; + + let normalisedBitmapData = formatNormaliser( + bitmapData, + metaData, + options.skipRescale + ); + + metaData.data = normalisedBitmapData; + metaData.gamma = gamma || 0; + + return metaData; +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./bitmapper":1,"./filter-parse-sync":8,"./format-normaliser":10,"./parser":18,"./sync-inflate":21,"./sync-reader":22,"buffer":33,"zlib":32}],18:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; + +let constants = require("./constants"); +let CrcCalculator = require("./crc"); + +let Parser = (module.exports = function (options, dependencies) { + this._options = options; + options.checkCRC = options.checkCRC !== false; + + this._hasIHDR = false; + this._hasIEND = false; + this._emittedHeadersFinished = false; + + // input flags/metadata + this._palette = []; + this._colorType = 0; + + this._chunks = {}; + this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this); + this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this); + this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this); + this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this); + this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this); + this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this); + + this.read = dependencies.read; + this.error = dependencies.error; + this.metadata = dependencies.metadata; + this.gamma = dependencies.gamma; + this.transColor = dependencies.transColor; + this.palette = dependencies.palette; + this.parsed = dependencies.parsed; + this.inflateData = dependencies.inflateData; + this.finished = dependencies.finished; + this.simpleTransparency = dependencies.simpleTransparency; + this.headersFinished = dependencies.headersFinished || function () {}; +}); + +Parser.prototype.start = function () { + this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this)); +}; + +Parser.prototype._parseSignature = function (data) { + let signature = constants.PNG_SIGNATURE; + + for (let i = 0; i < signature.length; i++) { + if (data[i] !== signature[i]) { + this.error(new Error("Invalid file signature")); + return; + } + } + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._parseChunkBegin = function (data) { + // chunk content length + let length = data.readUInt32BE(0); + + // chunk type + let type = data.readUInt32BE(4); + let name = ""; + for (let i = 4; i < 8; i++) { + name += String.fromCharCode(data[i]); + } + + //console.log('chunk ', name, length); + + // chunk flags + let ancillary = Boolean(data[4] & 0x20); // or critical + // priv = Boolean(data[5] & 0x20), // or public + // safeToCopy = Boolean(data[7] & 0x20); // or unsafe + + if (!this._hasIHDR && type !== constants.TYPE_IHDR) { + this.error(new Error("Expected IHDR on beggining")); + return; + } + + this._crc = new CrcCalculator(); + this._crc.write(Buffer.from(name)); + + if (this._chunks[type]) { + return this._chunks[type](length); + } + + if (!ancillary) { + this.error(new Error("Unsupported critical chunk type " + name)); + return; + } + + this.read(length + 4, this._skipChunk.bind(this)); +}; + +Parser.prototype._skipChunk = function (/*data*/) { + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._handleChunkEnd = function () { + this.read(4, this._parseChunkEnd.bind(this)); +}; + +Parser.prototype._parseChunkEnd = function (data) { + let fileCrc = data.readInt32BE(0); + let calcCrc = this._crc.crc32(); + + // check CRC + if (this._options.checkCRC && calcCrc !== fileCrc) { + this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc)); + return; + } + + if (!this._hasIEND) { + this.read(8, this._parseChunkBegin.bind(this)); + } +}; + +Parser.prototype._handleIHDR = function (length) { + this.read(length, this._parseIHDR.bind(this)); +}; +Parser.prototype._parseIHDR = function (data) { + this._crc.write(data); + + let width = data.readUInt32BE(0); + let height = data.readUInt32BE(4); + let depth = data[8]; + let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha + let compr = data[10]; + let filter = data[11]; + let interlace = data[12]; + + // console.log(' width', width, 'height', height, + // 'depth', depth, 'colorType', colorType, + // 'compr', compr, 'filter', filter, 'interlace', interlace + // ); + + if ( + depth !== 8 && + depth !== 4 && + depth !== 2 && + depth !== 1 && + depth !== 16 + ) { + this.error(new Error("Unsupported bit depth " + depth)); + return; + } + if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) { + this.error(new Error("Unsupported color type")); + return; + } + if (compr !== 0) { + this.error(new Error("Unsupported compression method")); + return; + } + if (filter !== 0) { + this.error(new Error("Unsupported filter method")); + return; + } + if (interlace !== 0 && interlace !== 1) { + this.error(new Error("Unsupported interlace method")); + return; + } + + this._colorType = colorType; + + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; + + this._hasIHDR = true; + + this.metadata({ + width: width, + height: height, + depth: depth, + interlace: Boolean(interlace), + palette: Boolean(colorType & constants.COLORTYPE_PALETTE), + color: Boolean(colorType & constants.COLORTYPE_COLOR), + alpha: Boolean(colorType & constants.COLORTYPE_ALPHA), + bpp: bpp, + colorType: colorType, + }); + + this._handleChunkEnd(); +}; + +Parser.prototype._handlePLTE = function (length) { + this.read(length, this._parsePLTE.bind(this)); +}; +Parser.prototype._parsePLTE = function (data) { + this._crc.write(data); + + let entries = Math.floor(data.length / 3); + // console.log('Palette:', entries); + + for (let i = 0; i < entries; i++) { + this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]); + } + + this.palette(this._palette); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleTRNS = function (length) { + this.simpleTransparency(); + this.read(length, this._parseTRNS.bind(this)); +}; +Parser.prototype._parseTRNS = function (data) { + this._crc.write(data); + + // palette + if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) { + if (this._palette.length === 0) { + this.error(new Error("Transparency chunk must be after palette")); + return; + } + if (data.length > this._palette.length) { + this.error(new Error("More transparent colors than palette size")); + return; + } + for (let i = 0; i < data.length; i++) { + this._palette[i][3] = data[i]; + } + this.palette(this._palette); + } + + // for colorType 0 (grayscale) and 2 (rgb) + // there might be one gray/color defined as transparent + if (this._colorType === constants.COLORTYPE_GRAYSCALE) { + // grey, 2 bytes + this.transColor([data.readUInt16BE(0)]); + } + if (this._colorType === constants.COLORTYPE_COLOR) { + this.transColor([ + data.readUInt16BE(0), + data.readUInt16BE(2), + data.readUInt16BE(4), + ]); + } + + this._handleChunkEnd(); +}; + +Parser.prototype._handleGAMA = function (length) { + this.read(length, this._parseGAMA.bind(this)); +}; +Parser.prototype._parseGAMA = function (data) { + this._crc.write(data); + this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleIDAT = function (length) { + if (!this._emittedHeadersFinished) { + this._emittedHeadersFinished = true; + this.headersFinished(); + } + this.read(-length, this._parseIDAT.bind(this, length)); +}; +Parser.prototype._parseIDAT = function (length, data) { + this._crc.write(data); + + if ( + this._colorType === constants.COLORTYPE_PALETTE_COLOR && + this._palette.length === 0 + ) { + throw new Error("Expected palette not found"); + } + + this.inflateData(data); + let leftOverLength = length - data.length; + + if (leftOverLength > 0) { + this._handleIDAT(leftOverLength); + } else { + this._handleChunkEnd(); + } +}; + +Parser.prototype._handleIEND = function (length) { + this.read(length, this._parseIEND.bind(this)); +}; +Parser.prototype._parseIEND = function (data) { + this._crc.write(data); + + this._hasIEND = true; + this._handleChunkEnd(); + + if (this.finished) { + this.finished(); + } +}; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./constants":4,"./crc":5,"buffer":33}],19:[function(require,module,exports){ +"use strict"; + +let parse = require("./parser-sync"); +let pack = require("./packer-sync"); + +exports.read = function (buffer, options) { + return parse(buffer, options || {}); +}; + +exports.write = function (png, options) { + return pack(png, options); +}; + +},{"./packer-sync":13,"./parser-sync":17}],20:[function(require,module,exports){ +(function (process,Buffer){(function (){ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let Parser = require("./parser-async"); +let Packer = require("./packer-async"); +let PNGSync = require("./png-sync"); + +let PNG = (exports.PNG = function (options) { + Stream.call(this); + + options = options || {}; // eslint-disable-line no-param-reassign + + // coerce pixel dimensions to integers (also coerces undefined -> 0): + this.width = options.width | 0; + this.height = options.height | 0; + + this.data = + this.width > 0 && this.height > 0 + ? Buffer.alloc(4 * this.width * this.height) + : null; + + if (options.fill && this.data) { + this.data.fill(0); + } + + this.gamma = 0; + this.readable = this.writable = true; + + this._parser = new Parser(options); + + this._parser.on("error", this.emit.bind(this, "error")); + this._parser.on("close", this._handleClose.bind(this)); + this._parser.on("metadata", this._metadata.bind(this)); + this._parser.on("gamma", this._gamma.bind(this)); + this._parser.on( + "parsed", + function (data) { + this.data = data; + this.emit("parsed", data); + }.bind(this) + ); + + this._packer = new Packer(options); + this._packer.on("data", this.emit.bind(this, "data")); + this._packer.on("end", this.emit.bind(this, "end")); + this._parser.on("close", this._handleClose.bind(this)); + this._packer.on("error", this.emit.bind(this, "error")); +}); +util.inherits(PNG, Stream); + +PNG.sync = PNGSync; + +PNG.prototype.pack = function () { + if (!this.data || !this.data.length) { + this.emit("error", "No data provided"); + return this; + } + + process.nextTick( + function () { + this._packer.pack(this.data, this.width, this.height, this.gamma); + }.bind(this) + ); + + return this; +}; + +PNG.prototype.parse = function (data, callback) { + if (callback) { + let onParsed, onError; + + onParsed = function (parsedData) { + this.removeListener("error", onError); + + this.data = parsedData; + callback(null, this); + }.bind(this); + + onError = function (err) { + this.removeListener("parsed", onParsed); + + callback(err, null); + }.bind(this); + + this.once("parsed", onParsed); + this.once("error", onError); + } + + this.end(data); + return this; +}; + +PNG.prototype.write = function (data) { + this._parser.write(data); + return true; +}; + +PNG.prototype.end = function (data) { + this._parser.end(data); +}; + +PNG.prototype._metadata = function (metadata) { + this.width = metadata.width; + this.height = metadata.height; + + this.emit("metadata", metadata); +}; + +PNG.prototype._gamma = function (gamma) { + this.gamma = gamma; +}; + +PNG.prototype._handleClose = function () { + if (!this._parser.writable && !this._packer.readable) { + this.emit("close"); + } +}; + +PNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) { + // eslint-disable-line max-params + // coerce pixel dimensions to integers (also coerces undefined -> 0): + /* eslint-disable no-param-reassign */ + srcX |= 0; + srcY |= 0; + width |= 0; + height |= 0; + deltaX |= 0; + deltaY |= 0; + /* eslint-enable no-param-reassign */ + + if ( + srcX > src.width || + srcY > src.height || + srcX + width > src.width || + srcY + height > src.height + ) { + throw new Error("bitblt reading outside image"); + } + + if ( + deltaX > dst.width || + deltaY > dst.height || + deltaX + width > dst.width || + deltaY + height > dst.height + ) { + throw new Error("bitblt writing outside image"); + } + + for (let y = 0; y < height; y++) { + src.data.copy( + dst.data, + ((deltaY + y) * dst.width + deltaX) << 2, + ((srcY + y) * src.width + srcX) << 2, + ((srcY + y) * src.width + srcX + width) << 2 + ); + } +}; + +PNG.prototype.bitblt = function ( + dst, + srcX, + srcY, + width, + height, + deltaX, + deltaY +) { + // eslint-disable-line max-params + + PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); + return this; +}; + +PNG.adjustGamma = function (src) { + if (src.gamma) { + for (let y = 0; y < src.height; y++) { + for (let x = 0; x < src.width; x++) { + let idx = (src.width * y + x) << 2; + + for (let i = 0; i < 3; i++) { + let sample = src.data[idx + i] / 255; + sample = Math.pow(sample, 1 / 2.2 / src.gamma); + src.data[idx + i] = Math.round(sample * 255); + } + } + } + src.gamma = 0; + } +}; + +PNG.prototype.adjustGamma = function () { + PNG.adjustGamma(this); +}; + +}).call(this)}).call(this,require('_process'),require("buffer").Buffer) +},{"./packer-async":12,"./parser-async":16,"./png-sync":19,"_process":60,"buffer":33,"stream":61,"util":81}],21:[function(require,module,exports){ +(function (process,Buffer){(function (){ +"use strict"; + +let assert = require("assert").ok; +let zlib = require("zlib"); +let util = require("util"); + +let kMaxLength = require("buffer").kMaxLength; + +function Inflate(opts) { + if (!(this instanceof Inflate)) { + return new Inflate(opts); + } + + if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { + opts.chunkSize = zlib.Z_MIN_CHUNK; + } + + zlib.Inflate.call(this, opts); + + // Node 8 --> 9 compatibility check + this._offset = this._offset === undefined ? this._outOffset : this._offset; + this._buffer = this._buffer || this._outBuffer; + + if (opts && opts.maxLength != null) { + this._maxLength = opts.maxLength; + } +} + +function createInflate(opts) { + return new Inflate(opts); +} + +function _close(engine, callback) { + if (callback) { + process.nextTick(callback); + } + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) { + return; + } + + engine._handle.close(); + engine._handle = null; +} + +Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) { + if (typeof asyncCb === "function") { + return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); + } + + let self = this; + + let availInBefore = chunk && chunk.length; + let availOutBefore = this._chunkSize - this._offset; + let leftToInflate = this._maxLength; + let inOff = 0; + + let buffers = []; + let nread = 0; + + let error; + this.on("error", function (err) { + error = err; + }); + + function handleChunk(availInAfter, availOutAfter) { + if (self._hadError) { + return; + } + + let have = availOutBefore - availOutAfter; + assert(have >= 0, "have should not go down"); + + if (have > 0) { + let out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + + if (out.length > leftToInflate) { + out = out.slice(0, leftToInflate); + } + + buffers.push(out); + nread += out.length; + leftToInflate -= out.length; + + if (leftToInflate === 0) { + return false; + } + } + + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + return true; + } + + return false; + } + + assert(this._handle, "zlib binding closed"); + let res; + do { + res = this._handle.writeSync( + flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore + ); // out_len + // Node 8 --> 9 compatibility check + res = res || this._writeState; + } while (!this._hadError && handleChunk(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError( + "Cannot create final Buffer. It would be larger than 0x" + + kMaxLength.toString(16) + + " bytes" + ); + } + + let buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; +}; + +util.inherits(Inflate, zlib.Inflate); + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === "string") { + buffer = Buffer.from(buffer); + } + if (!(buffer instanceof Buffer)) { + throw new TypeError("Not a string or buffer"); + } + + let flushFlag = engine._finishFlushFlag; + if (flushFlag == null) { + flushFlag = zlib.Z_FINISH; + } + + return engine._processChunk(buffer, flushFlag); +} + +function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +} + +module.exports = exports = inflateSync; +exports.Inflate = Inflate; +exports.createInflate = createInflate; +exports.inflateSync = inflateSync; + +}).call(this)}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":60,"assert":23,"buffer":33,"util":81,"zlib":32}],22:[function(require,module,exports){ +"use strict"; + +let SyncReader = (module.exports = function (buffer) { + this._buffer = buffer; + this._reads = []; +}); + +SyncReader.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); +}; + +SyncReader.prototype.process = function () { + // as long as there is any data and read requests + while (this._reads.length > 0 && this._buffer.length) { + let read = this._reads[0]; + + if ( + this._buffer.length && + (this._buffer.length >= read.length || read.allowLess) + ) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + let buf = this._buffer; + + this._buffer = buf.slice(read.length); + + read.func.call(this, buf.slice(0, read.length)); + } else { + break; + } + } + + if (this._reads.length > 0) { + throw new Error("There are some read requests waitng on finished stream"); + } + + if (this._buffer.length > 0) { + throw new Error("unrecognised content at end of stream"); + } +}; + +},{}],23:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} + +// based on node assert, original notice: + +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION 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 util = require('util/'); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; + +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} + + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; +} + +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function(err) { if (err) throw err; }; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"util/":26}],24:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],25:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],26:[function(require,module,exports){ +(function (process,global){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":25,"_process":60,"inherits":24}],27:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +var filter = require('array-filter'); + +module.exports = function availableTypedArrays() { + return filter([ + 'BigInt64Array', + 'BigUint64Array', + 'Float32Array', + 'Float64Array', + 'Int16Array', + 'Int32Array', + 'Int8Array', + 'Uint16Array', + 'Uint32Array', + 'Uint8Array', + 'Uint8ClampedArray' + ], function (typedArray) { + return typeof global[typedArray] === 'function'; + }); +}; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"array-filter":28}],28:[function(require,module,exports){ + +/** + * Array#filter. + * + * @param {Array} arr + * @param {Function} fn + * @param {Object=} self + * @return {Array} + * @throw TypeError + */ + +module.exports = function (arr, fn, self) { + if (arr.filter) return arr.filter(fn, self); + if (void 0 === arr || null === arr) throw new TypeError; + if ('function' != typeof fn) throw new TypeError; + var ret = []; + for (var i = 0; i < arr.length; i++) { + if (!hasOwn.call(arr, i)) continue; + var val = arr[i]; + if (fn.call(self, val, i, arr)) ret.push(val); + } + return ret; +}; + +var hasOwn = Object.prototype.hasOwnProperty; + +},{}],29:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + +},{}],30:[function(require,module,exports){ + +},{}],31:[function(require,module,exports){ +(function (process,Buffer){(function (){ +'use strict'; +/* eslint camelcase: "off" */ + +var assert = require('assert'); + +var Zstream = require('pako/lib/zlib/zstream'); +var zlib_deflate = require('pako/lib/zlib/deflate.js'); +var zlib_inflate = require('pako/lib/zlib/inflate.js'); +var constants = require('pako/lib/zlib/constants'); + +for (var key in constants) { + exports[key] = constants[key]; +} + +// zlib modes +exports.NONE = 0; +exports.DEFLATE = 1; +exports.INFLATE = 2; +exports.GZIP = 3; +exports.GUNZIP = 4; +exports.DEFLATERAW = 5; +exports.INFLATERAW = 6; +exports.UNZIP = 7; + +var GZIP_HEADER_ID1 = 0x1f; +var GZIP_HEADER_ID2 = 0x8b; + +/** + * Emulate Node's zlib C++ layer for use by the JS layer in index.js + */ +function Zlib(mode) { + if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) { + throw new TypeError('Bad argument'); + } + + this.dictionary = null; + this.err = 0; + this.flush = 0; + this.init_done = false; + this.level = 0; + this.memLevel = 0; + this.mode = mode; + this.strategy = 0; + this.windowBits = 0; + this.write_in_progress = false; + this.pending_close = false; + this.gzip_id_bytes_read = 0; +} + +Zlib.prototype.close = function () { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + + this.pending_close = false; + + assert(this.init_done, 'close before init'); + assert(this.mode <= exports.UNZIP); + + if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { + zlib_deflate.deflateEnd(this.strm); + } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) { + zlib_inflate.inflateEnd(this.strm); + } + + this.mode = exports.NONE; + + this.dictionary = null; +}; + +Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(true, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(false, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) { + assert.equal(arguments.length, 8); + + assert(this.init_done, 'write before init'); + assert(this.mode !== exports.NONE, 'already finalized'); + assert.equal(false, this.write_in_progress, 'write already in progress'); + assert.equal(false, this.pending_close, 'close is pending'); + + this.write_in_progress = true; + + assert.equal(false, flush === undefined, 'must provide flush value'); + + this.write_in_progress = true; + + if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) { + throw new Error('Invalid flush value'); + } + + if (input == null) { + input = Buffer.alloc(0); + in_len = 0; + in_off = 0; + } + + this.strm.avail_in = in_len; + this.strm.input = input; + this.strm.next_in = in_off; + this.strm.avail_out = out_len; + this.strm.output = out; + this.strm.next_out = out_off; + this.flush = flush; + + if (!async) { + // sync version + this._process(); + + if (this._checkError()) { + return this._afterSync(); + } + return; + } + + // async version + var self = this; + process.nextTick(function () { + self._process(); + self._after(); + }); + + return this; +}; + +Zlib.prototype._afterSync = function () { + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + return [avail_in, avail_out]; +}; + +Zlib.prototype._process = function () { + var next_expected_header_byte = null; + + // If the avail_out is left at 0, then it means that it ran out + // of room. If there was avail_out left over, then it means + // that all of the input was consumed. + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflate(this.strm, this.flush); + break; + case exports.UNZIP: + if (this.strm.avail_in > 0) { + next_expected_header_byte = this.strm.next_in; + } + + switch (this.gzip_id_bytes_read) { + case 0: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) { + this.gzip_id_bytes_read = 1; + next_expected_header_byte++; + + if (this.strm.avail_in === 1) { + // The only available byte was already read. + break; + } + } else { + this.mode = exports.INFLATE; + break; + } + + // fallthrough + case 1: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) { + this.gzip_id_bytes_read = 2; + this.mode = exports.GUNZIP; + } else { + // There is no actual difference between INFLATE and INFLATERAW + // (after initialization). + this.mode = exports.INFLATE; + } + + break; + default: + throw new Error('invalid number of gzip magic number bytes read'); + } + + // fallthrough + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + this.err = zlib_inflate.inflate(this.strm, this.flush + + // If data was encoded with dictionary + );if (this.err === exports.Z_NEED_DICT && this.dictionary) { + // Load it + this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); + if (this.err === exports.Z_OK) { + // And try to decode again + this.err = zlib_inflate.inflate(this.strm, this.flush); + } else if (this.err === exports.Z_DATA_ERROR) { + // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR. + // Make it possible for After() to tell a bad dictionary from bad + // input. + this.err = exports.Z_NEED_DICT; + } + } + while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) { + // Bytes remain in input buffer. Perhaps this is another compressed + // member in the same archive, or just trailing garbage. + // Trailing zero bytes are okay, though, since they are frequently + // used for padding. + + this.reset(); + this.err = zlib_inflate.inflate(this.strm, this.flush); + } + break; + default: + throw new Error('Unknown mode ' + this.mode); + } +}; + +Zlib.prototype._checkError = function () { + // Acceptable error states depend on the type of zlib stream. + switch (this.err) { + case exports.Z_OK: + case exports.Z_BUF_ERROR: + if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) { + this._error('unexpected end of file'); + return false; + } + break; + case exports.Z_STREAM_END: + // normal statuses, not fatal + break; + case exports.Z_NEED_DICT: + if (this.dictionary == null) { + this._error('Missing dictionary'); + } else { + this._error('Bad dictionary'); + } + return false; + default: + // something else. + this._error('Zlib error'); + return false; + } + + return true; +}; + +Zlib.prototype._after = function () { + if (!this._checkError()) { + return; + } + + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + // call the write() cb + this.callback(avail_in, avail_out); + + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype._error = function (message) { + if (this.strm.msg) { + message = this.strm.msg; + } + this.onerror(message, this.err + + // no hope of rescue. + );this.write_in_progress = false; + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) { + assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])'); + + assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits'); + assert(level >= -1 && level <= 9, 'invalid compression level'); + + assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel'); + + assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy'); + + this._init(level, windowBits, memLevel, strategy, dictionary); + this._setDictionary(); +}; + +Zlib.prototype.params = function () { + throw new Error('deflateParams Not supported'); +}; + +Zlib.prototype.reset = function () { + this._reset(); + this._setDictionary(); +}; + +Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) { + this.level = level; + this.windowBits = windowBits; + this.memLevel = memLevel; + this.strategy = strategy; + + this.flush = exports.Z_NO_FLUSH; + + this.err = exports.Z_OK; + + if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) { + this.windowBits += 16; + } + + if (this.mode === exports.UNZIP) { + this.windowBits += 32; + } + + if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) { + this.windowBits = -1 * this.windowBits; + } + + this.strm = new Zstream(); + + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); + break; + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + case exports.UNZIP: + this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (this.err !== exports.Z_OK) { + this._error('Init error'); + } + + this.dictionary = dictionary; + + this.write_in_progress = false; + this.init_done = true; +}; + +Zlib.prototype._setDictionary = function () { + if (this.dictionary == null) { + return; + } + + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to set dictionary'); + } +}; + +Zlib.prototype._reset = function () { + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + case exports.GZIP: + this.err = zlib_deflate.deflateReset(this.strm); + break; + case exports.INFLATE: + case exports.INFLATERAW: + case exports.GUNZIP: + this.err = zlib_inflate.inflateReset(this.strm); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to reset stream'); + } +}; + +exports.Zlib = Zlib; +}).call(this)}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":60,"assert":23,"buffer":33,"pako/lib/zlib/constants":51,"pako/lib/zlib/deflate.js":53,"pako/lib/zlib/inflate.js":55,"pako/lib/zlib/zstream":59}],32:[function(require,module,exports){ +(function (process){(function (){ +'use strict'; + +var Buffer = require('buffer').Buffer; +var Transform = require('stream').Transform; +var binding = require('./binding'); +var util = require('util'); +var assert = require('assert').ok; +var kMaxLength = require('buffer').kMaxLength; +var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes'; + +// zlib doesn't provide these, so kludge them in following the same +// const naming scheme zlib uses. +binding.Z_MIN_WINDOWBITS = 8; +binding.Z_MAX_WINDOWBITS = 15; +binding.Z_DEFAULT_WINDOWBITS = 15; + +// fewer than 64 bytes per chunk is stupid. +// technically it could work with as few as 8, but even 64 bytes +// is absurdly low. Usually a MB or more is best. +binding.Z_MIN_CHUNK = 64; +binding.Z_MAX_CHUNK = Infinity; +binding.Z_DEFAULT_CHUNK = 16 * 1024; + +binding.Z_MIN_MEMLEVEL = 1; +binding.Z_MAX_MEMLEVEL = 9; +binding.Z_DEFAULT_MEMLEVEL = 8; + +binding.Z_MIN_LEVEL = -1; +binding.Z_MAX_LEVEL = 9; +binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; + +// expose all the zlib constants +var bkeys = Object.keys(binding); +for (var bk = 0; bk < bkeys.length; bk++) { + var bkey = bkeys[bk]; + if (bkey.match(/^Z/)) { + Object.defineProperty(exports, bkey, { + enumerable: true, value: binding[bkey], writable: false + }); + } +} + +// translation table for return codes. +var codes = { + Z_OK: binding.Z_OK, + Z_STREAM_END: binding.Z_STREAM_END, + Z_NEED_DICT: binding.Z_NEED_DICT, + Z_ERRNO: binding.Z_ERRNO, + Z_STREAM_ERROR: binding.Z_STREAM_ERROR, + Z_DATA_ERROR: binding.Z_DATA_ERROR, + Z_MEM_ERROR: binding.Z_MEM_ERROR, + Z_BUF_ERROR: binding.Z_BUF_ERROR, + Z_VERSION_ERROR: binding.Z_VERSION_ERROR +}; + +var ckeys = Object.keys(codes); +for (var ck = 0; ck < ckeys.length; ck++) { + var ckey = ckeys[ck]; + codes[codes[ckey]] = ckey; +} + +Object.defineProperty(exports, 'codes', { + enumerable: true, value: Object.freeze(codes), writable: false +}); + +exports.Deflate = Deflate; +exports.Inflate = Inflate; +exports.Gzip = Gzip; +exports.Gunzip = Gunzip; +exports.DeflateRaw = DeflateRaw; +exports.InflateRaw = InflateRaw; +exports.Unzip = Unzip; + +exports.createDeflate = function (o) { + return new Deflate(o); +}; + +exports.createInflate = function (o) { + return new Inflate(o); +}; + +exports.createDeflateRaw = function (o) { + return new DeflateRaw(o); +}; + +exports.createInflateRaw = function (o) { + return new InflateRaw(o); +}; + +exports.createGzip = function (o) { + return new Gzip(o); +}; + +exports.createGunzip = function (o) { + return new Gunzip(o); +}; + +exports.createUnzip = function (o) { + return new Unzip(o); +}; + +// Convenience methods. +// compress/decompress a string or buffer in one step. +exports.deflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer, callback); +}; + +exports.deflateSync = function (buffer, opts) { + return zlibBufferSync(new Deflate(opts), buffer); +}; + +exports.gzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer, callback); +}; + +exports.gzipSync = function (buffer, opts) { + return zlibBufferSync(new Gzip(opts), buffer); +}; + +exports.deflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer, callback); +}; + +exports.deflateRawSync = function (buffer, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer); +}; + +exports.unzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer, callback); +}; + +exports.unzipSync = function (buffer, opts) { + return zlibBufferSync(new Unzip(opts), buffer); +}; + +exports.inflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer, callback); +}; + +exports.inflateSync = function (buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +}; + +exports.gunzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer, callback); +}; + +exports.gunzipSync = function (buffer, opts) { + return zlibBufferSync(new Gunzip(opts), buffer); +}; + +exports.inflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer, callback); +}; + +exports.inflateRawSync = function (buffer, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer); +}; + +function zlibBuffer(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once('readable', flow); + } + + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); + } + + function onEnd() { + var buf; + var err = null; + + if (nread >= kMaxLength) { + err = new RangeError(kRangeErrorMessage); + } else { + buf = Buffer.concat(buffers, nread); + } + + buffers = []; + engine.close(); + callback(err, buf); + } +} + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') buffer = Buffer.from(buffer); + + if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer'); + + var flushFlag = engine._finishFlushFlag; + + return engine._processChunk(buffer, flushFlag); +} + +// generic zlib +// minimal 2-byte header +function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib.call(this, opts, binding.DEFLATE); +} + +function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib.call(this, opts, binding.INFLATE); +} + +// gzip - bigger header, same deflate compression +function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib.call(this, opts, binding.GZIP); +} + +function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib.call(this, opts, binding.GUNZIP); +} + +// raw - no header +function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib.call(this, opts, binding.DEFLATERAW); +} + +function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib.call(this, opts, binding.INFLATERAW); +} + +// auto-detect header. +function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib.call(this, opts, binding.UNZIP); +} + +function isValidFlushFlag(flag) { + return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK; +} + +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. + +function Zlib(opts, mode) { + var _this = this; + + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; + + Transform.call(this, opts); + + if (opts.flush && !isValidFlushFlag(opts.flush)) { + throw new Error('Invalid flush flag: ' + opts.flush); + } + if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { + throw new Error('Invalid flush flag: ' + opts.finishFlush); + } + + this._flushFlag = opts.flush || binding.Z_NO_FLUSH; + this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH; + + if (opts.chunkSize) { + if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); + } + } + + if (opts.windowBits) { + if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!Buffer.isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._handle = new binding.Zlib(mode); + + var self = this; + this._hadError = false; + this._handle.onerror = function (message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + _close(self); + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = exports.codes[errno]; + self.emit('error', error); + }; + + var level = exports.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = exports.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); + + this._buffer = Buffer.allocUnsafe(this._chunkSize); + this._offset = 0; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); + + Object.defineProperty(this, '_closed', { + get: function () { + return !_this._handle; + }, + configurable: true, + enumerable: true + }); +} + +util.inherits(Zlib, Transform); + +Zlib.prototype.params = function (level, strategy, callback) { + if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding.Z_SYNC_FLUSH, function () { + assert(self._handle, 'zlib binding closed'); + self._handle.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); + } + }); + } else { + process.nextTick(callback); + } +}; + +Zlib.prototype.reset = function () { + assert(this._handle, 'zlib binding closed'); + return this._handle.reset(); +}; + +// This is the _flush function called by the transform class, +// internally, when the last chunk has been written. +Zlib.prototype._flush = function (callback) { + this._transform(Buffer.alloc(0), '', callback); +}; + +Zlib.prototype.flush = function (kind, callback) { + var _this2 = this; + + var ws = this._writableState; + + if (typeof kind === 'function' || kind === undefined && !callback) { + callback = kind; + kind = binding.Z_FULL_FLUSH; + } + + if (ws.ended) { + if (callback) process.nextTick(callback); + } else if (ws.ending) { + if (callback) this.once('end', callback); + } else if (ws.needDrain) { + if (callback) { + this.once('drain', function () { + return _this2.flush(kind, callback); + }); + } + } else { + this._flushFlag = kind; + this.write(Buffer.alloc(0), '', callback); + } +}; + +Zlib.prototype.close = function (callback) { + _close(this, callback); + process.nextTick(emitCloseNT, this); +}; + +function _close(engine, callback) { + if (callback) process.nextTick(callback); + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) return; + + engine._handle.close(); + engine._handle = null; +} + +function emitCloseNT(self) { + self.emit('close'); +} + +Zlib.prototype._transform = function (chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input')); + + if (!this._handle) return cb(new Error('zlib binding closed')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag + // (or whatever flag was provided using opts.finishFlush). + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) flushFlag = this._finishFlushFlag;else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; + } + } + + this._processChunk(chunk, flushFlag, cb); +}; + +Zlib.prototype._processChunk = function (chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function (er) { + error = er; + }); + + assert(this._handle, 'zlib binding closed'); + do { + var res = this._handle.writeSync(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError(kRangeErrorMessage); + } + + var buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; + } + + assert(this._handle, 'zlib binding closed'); + var req = this._handle.write(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + // When the callback is used in an async write, the callback's + // context is the `req` object that was created. The req object + // is === this._handle, and that's why it's important to null + // out the values after they are done being used. `this._handle` + // can stay in memory longer than the callback and buffer are needed. + if (this) { + this.buffer = null; + this.callback = null; + } + + if (self._hadError) return; + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + if (!async) return true; + + var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) return false; + + // finished with the chunk. + cb(); + } +}; + +util.inherits(Deflate, Zlib); +util.inherits(Inflate, Zlib); +util.inherits(Gzip, Zlib); +util.inherits(Gunzip, Zlib); +util.inherits(DeflateRaw, Zlib); +util.inherits(InflateRaw, Zlib); +util.inherits(Unzip, Zlib); +}).call(this)}).call(this,require('_process')) +},{"./binding":31,"_process":60,"assert":23,"buffer":33,"stream":61,"util":81}],33:[function(require,module,exports){ +(function (Buffer){(function (){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) + } + + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"base64-js":29,"buffer":33,"ieee754":44}],34:[function(require,module,exports){ +'use strict'; + +/* globals + Atomics, + SharedArrayBuffer, +*/ + +var undefined; + +var $TypeError = TypeError; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { throw new $TypeError(); }; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); + +var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto + +var generator; // = function * () {}; +var generatorFunction = generator ? getProto(generator) : undefined; +var asyncFn; // async function() {}; +var asyncFunction = asyncFn ? asyncFn.constructor : undefined; +var asyncGen; // async function * () {}; +var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; +var asyncGenIterator = asyncGen ? asyncGen() : undefined; + +var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, + '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, + '%ArrayPrototype%': Array.prototype, + '%ArrayProto_entries%': Array.prototype.entries, + '%ArrayProto_forEach%': Array.prototype.forEach, + '%ArrayProto_keys%': Array.prototype.keys, + '%ArrayProto_values%': Array.prototype.values, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': asyncFunction, + '%AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, + '%AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, + '%AsyncGeneratorFunction%': asyncGenFunction, + '%AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, + '%AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%Boolean%': Boolean, + '%BooleanPrototype%': Boolean.prototype, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, + '%Date%': Date, + '%DatePrototype%': Date.prototype, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%ErrorPrototype%': Error.prototype, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%EvalErrorPrototype%': EvalError.prototype, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, + '%Function%': Function, + '%FunctionPrototype%': Function.prototype, + '%Generator%': generator ? getProto(generator()) : undefined, + '%GeneratorFunction%': generatorFunction, + '%GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%JSONParse%': typeof JSON === 'object' ? JSON.parse : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), + '%MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, + '%Math%': Math, + '%Number%': Number, + '%NumberPrototype%': Number.prototype, + '%Object%': Object, + '%ObjectPrototype%': Object.prototype, + '%ObjProto_toString%': Object.prototype.toString, + '%ObjProto_valueOf%': Object.prototype.valueOf, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, + '%PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, + '%Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, + '%Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, + '%Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%RangeErrorPrototype%': RangeError.prototype, + '%ReferenceError%': ReferenceError, + '%ReferenceErrorPrototype%': ReferenceError.prototype, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%RegExpPrototype%': RegExp.prototype, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, + '%StringPrototype%': String.prototype, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, + '%SyntaxError%': SyntaxError, + '%SyntaxErrorPrototype%': SyntaxError.prototype, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, + '%TypeError%': $TypeError, + '%TypeErrorPrototype%': $TypeError.prototype, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, + '%URIError%': URIError, + '%URIErrorPrototype%': URIError.prototype, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + '%WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype +}; + +var bind = require('function-bind'); +var $replace = bind.call(Function.call, String.prototype.replace); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match); + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + if (!(name in INTRINSICS)) { + throw new SyntaxError('intrinsic ' + name + ' does not exist!'); + } + + // istanbul ignore if // hopefully this is impossible to test :-) + if (typeof INTRINSICS[name] === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return INTRINSICS[name]; +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new TypeError('"allowMissing" argument must be a boolean'); + } + + var parts = stringToPath(name); + + var value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing); + for (var i = 1; i < parts.length; i += 1) { + if (value != null) { + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, parts[i]); + if (!allowMissing && !(parts[i] in value)) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + value = desc ? (desc.get || desc.value) : value[parts[i]]; + } else { + value = value[parts[i]]; + } + } + } + return value; +}; + +},{"function-bind":41,"has-symbols":42}],35:[function(require,module,exports){ +'use strict'; + +var bind = require('function-bind'); + +var GetIntrinsic = require('../GetIntrinsic'); + +var $Function = GetIntrinsic('%Function%'); +var $apply = $Function.apply; +var $call = $Function.call; + +module.exports = function callBind() { + return bind.apply($call, arguments); +}; + +module.exports.apply = function applyBind() { + return bind.apply($apply, arguments); +}; + +},{"../GetIntrinsic":34,"function-bind":41}],36:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var callBind = require('./callBind'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.')) { + return callBind(intrinsic); + } + return intrinsic; +}; + +},{"../GetIntrinsic":34,"./callBind":35}],37:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%'); +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + +},{"../GetIntrinsic":34}],38:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function eventListener() { + if (errorListener !== undefined) { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + var errorListener; + + // Adding an error listener is not optional because + // if an error is thrown on an event emitter we cannot + // guarantee that the actual event we are waiting will + // be fired. The result could be a silent way to create + // memory or file descriptor leaks, which is something + // we should avoid. + if (name !== 'error') { + errorListener = function errorListener(err) { + emitter.removeListener(name, eventListener); + reject(err); + }; + + emitter.once('error', errorListener); + } + + emitter.once(name, eventListener); + }); +} + +},{}],39:[function(require,module,exports){ + +var hasOwn = Object.prototype.hasOwnProperty; +var toString = Object.prototype.toString; + +module.exports = function forEach (obj, fn, ctx) { + if (toString.call(fn) !== '[object Function]') { + throw new TypeError('iterator must be a function'); + } + var l = obj.length; + if (l === +l) { + for (var i = 0; i < l; i++) { + fn.call(ctx, obj[i], i, obj); + } + } else { + for (var k in obj) { + if (hasOwn.call(obj, k)) { + fn.call(ctx, obj[k], k, obj); + } + } + } +}; + + +},{}],40:[function(require,module,exports){ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +},{}],41:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; + +},{"./implementation":40}],42:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +var origSymbol = global.Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./shams":43}],43:[function(require,module,exports){ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + +},{}],44:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],45:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + +},{}],46:[function(require,module,exports){ +'use strict'; + +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; +var toStr = Object.prototype.toString; + +var isStandardArguments = function isArguments(value) { + if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { + return false; + } + return toStr.call(value) === '[object Arguments]'; +}; + +var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value) !== '[object Array]' && + toStr.call(value.callee) === '[object Function]'; +}; + +var supportsStandardArguments = (function () { + return isStandardArguments(arguments); +}()); + +isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests + +module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; + +},{}],47:[function(require,module,exports){ +'use strict'; + +var toStr = Object.prototype.toString; +var fnToStr = Function.prototype.toString; +var isFnRegex = /^\s*(?:function)?\*/; +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; +var getProto = Object.getPrototypeOf; +var getGeneratorFunc = function () { // eslint-disable-line consistent-return + if (!hasToStringTag) { + return false; + } + try { + return Function('return function*() {}')(); + } catch (e) { + } +}; +var generatorFunc = getGeneratorFunc(); +var GeneratorFunction = generatorFunc ? getProto(generatorFunc) : {}; + +module.exports = function isGeneratorFunction(fn) { + if (typeof fn !== 'function') { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === '[object GeneratorFunction]'; + } + return getProto(fn) === GeneratorFunction; +}; + +},{}],48:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +var forEach = require('foreach'); +var availableTypedArrays = require('available-typed-arrays'); +var callBound = require('es-abstract/helpers/callBound'); + +var $toString = callBound('Object.prototype.toString'); +var hasSymbols = require('has-symbols')(); +var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; + +var typedArrays = availableTypedArrays(); + +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; +var $slice = callBound('String.prototype.slice'); +var toStrTags = {}; +var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new global[typedArray](); + if (!(Symbol.toStringTag in arr)) { + throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); + } + var proto = getPrototypeOf(arr); + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + descriptor = gOPD(superProto, Symbol.toStringTag); + } + toStrTags[typedArray] = descriptor.get; + }); +} + +var tryTypedArrays = function tryAllTypedArrays(value) { + var anyTrue = false; + forEach(toStrTags, function (getter, typedArray) { + if (!anyTrue) { + try { + anyTrue = getter.call(value) === typedArray; + } catch (e) { /**/ } + } + }); + return anyTrue; +}; + +module.exports = function isTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + var tag = $slice($toString(value), 8, -1); + return $indexOf(typedArrays, tag) > -1; + } + if (!gOPD) { return false; } + return tryTypedArrays(value); +}; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"available-typed-arrays":27,"es-abstract/helpers/callBound":36,"es-abstract/helpers/getOwnPropertyDescriptor":37,"foreach":39,"has-symbols":42}],49:[function(require,module,exports){ +'use strict'; + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); + +},{}],50:[function(require,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],51:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + +},{}],52:[function(require,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],53:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +},{"../utils/common":49,"./adler32":50,"./crc32":52,"./messages":57,"./trees":58}],54:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +},{}],55:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +},{"../utils/common":49,"./adler32":50,"./crc32":52,"./inffast":54,"./inftrees":56}],56:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +},{"../utils/common":49}],57:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],58:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + +},{"../utils/common":49}],59:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],60:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],61:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/lib/_stream_readable.js'); +Stream.Writable = require('readable-stream/lib/_stream_writable.js'); +Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); +Stream.Transform = require('readable-stream/lib/_stream_transform.js'); +Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); +Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') +Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":38,"inherits":45,"readable-stream/lib/_stream_duplex.js":63,"readable-stream/lib/_stream_passthrough.js":64,"readable-stream/lib/_stream_readable.js":65,"readable-stream/lib/_stream_transform.js":66,"readable-stream/lib/_stream_writable.js":67,"readable-stream/lib/internal/streams/end-of-stream.js":71,"readable-stream/lib/internal/streams/pipeline.js":73}],62:[function(require,module,exports){ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; + +},{}],63:[function(require,module,exports){ +(function (process){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. +'use strict'; +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; +}; +/**/ + + +module.exports = Duplex; + +var Readable = require('./_stream_readable'); + +var Writable = require('./_stream_writable'); + +require('inherits')(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer + +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + process.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); +}).call(this)}).call(this,require('_process')) +},{"./_stream_readable":65,"./_stream_writable":67,"_process":60,"inherits":45}],64:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +require('inherits')(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":66,"inherits":45}],65:[function(require,module,exports){ +(function (process,global){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +'use strict'; + +module.exports = Readable; +/**/ + +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; +/**/ + +var EE = require('events').EventEmitter; + +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ + + +var Stream = require('./internal/streams/stream'); +/**/ + + +var Buffer = require('buffer').Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + + +var debugUtil = require('util'); + +var debug; + +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + + +var BufferList = require('./internal/streams/buffer_list'); + +var destroyImpl = require('./internal/streams/destroy'); + +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; + +require('inherits')(Readable, Stream); + +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; + +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. + + +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() + + +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. + + +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB + + +var MAX_HWM = 0x40000000; + +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. + + +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; +} // you can override either this method, or the async _read(n) below. + + +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; +}; + +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} // Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. + + +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} + +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. + + +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. + + +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; // set up data events if they are asked for +// Ensure readable listeners eventually get something + + +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + + return res; +}; + +Readable.prototype.addListener = Readable.prototype.on; + +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. + + +Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. + + +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + + return createReadableStreamAsyncIterator(this); + }; +} + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); // exposed for testing purposes only. + +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. + +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} + +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + + return from(Readable, iterable, opts); + }; +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; +} +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../errors":62,"./_stream_duplex":63,"./internal/streams/async_iterator":68,"./internal/streams/buffer_list":69,"./internal/streams/destroy":70,"./internal/streams/from":72,"./internal/streams/state":74,"./internal/streams/stream":75,"_process":60,"buffer":33,"events":38,"inherits":45,"string_decoder/":76,"util":30}],66:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. +'use strict'; + +module.exports = Transform; + +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + +var Duplex = require('./_stream_duplex'); + +require('inherits')(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. + + +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. + + +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} +},{"../errors":62,"./_stream_duplex":63,"inherits":45}],67:[function(require,module,exports){ +(function (process,global){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. +'use strict'; + +module.exports = Writable; +/* */ + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream + + +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ + + +var Duplex; +/**/ + +Writable.WritableState = WritableState; +/**/ + +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ + +var Stream = require('./internal/streams/stream'); +/**/ + + +var Buffer = require('buffer').Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +var destroyImpl = require('./internal/streams/destroy'); + +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + +var errorOrDestroy = destroyImpl.errorOrDestroy; + +require('inherits')(Writable, Stream); + +function nop() {} + +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. + + +var realHasInstance; + +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. + + +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; + +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. + + +function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + + return true; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; + +Writable.prototype.cork = function () { + this._writableState.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. + +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. + + +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it + + +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} + +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; + +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../errors":62,"./_stream_duplex":63,"./internal/streams/destroy":70,"./internal/streams/state":74,"./internal/streams/stream":75,"_process":60,"buffer":33,"inherits":45,"util-deprecate":78}],68:[function(require,module,exports){ +(function (process){(function (){ +'use strict'; + +var _Object$setPrototypeO; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var finished = require('./end-of-stream'); + +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); + +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} + +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} + +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} + +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} + +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); + +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; + +module.exports = createReadableStreamAsyncIterator; +}).call(this)}).call(this,require('_process')) +},{"./end-of-stream":71,"_process":60}],69:[function(require,module,exports){ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = require('buffer'), + Buffer = _require.Buffer; + +var _require2 = require('util'), + inspect = _require2.inspect; + +var custom = inspect && inspect.custom || 'inspect'; + +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} + +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; +}(); +},{"buffer":33,"util":30}],70:[function(require,module,exports){ +(function (process){(function (){ +'use strict'; // undocumented cb() API, needed for core, not for public API + +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + + return this; +} + +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} + +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; +}).call(this)}).call(this,require('_process')) +},{"_process":60}],71:[function(require,module,exports){ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; +} + +function noop() {} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} + +module.exports = eos; +},{"../../../errors":62}],72:[function(require,module,exports){ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; + +},{}],73:[function(require,module,exports){ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; + +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} + +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} + +module.exports = pipeline; +},{"../../../errors":62,"./end-of-stream":71}],74:[function(require,module,exports){ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; + +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; +} + +module.exports = { + getHighWaterMark: getHighWaterMark +}; +},{"../../../errors":62}],75:[function(require,module,exports){ +module.exports = require('events').EventEmitter; + +},{"events":38}],76:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"safe-buffer":77}],77:[function(require,module,exports){ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + +},{"buffer":33}],78:[function(require,module,exports){ +(function (global){(function (){ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],79:[function(require,module,exports){ +arguments[4][25][0].apply(exports,arguments) +},{"dup":25}],80:[function(require,module,exports){ +// Currently in sync with Node.js lib/internal/util/types.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + +'use strict'; + +var isArgumentsObject = require('is-arguments'); +var isGeneratorFunction = require('is-generator-function'); +var whichTypedArray = require('which-typed-array'); +var isTypedArray = require('is-typed-array'); + +function uncurryThis(f) { + return f.call.bind(f); +} + +var BigIntSupported = typeof BigInt !== 'undefined'; +var SymbolSupported = typeof Symbol !== 'undefined'; + +var ObjectToString = uncurryThis(Object.prototype.toString); + +var numberValue = uncurryThis(Number.prototype.valueOf); +var stringValue = uncurryThis(String.prototype.valueOf); +var booleanValue = uncurryThis(Boolean.prototype.valueOf); + +if (BigIntSupported) { + var bigIntValue = uncurryThis(BigInt.prototype.valueOf); +} + +if (SymbolSupported) { + var symbolValue = uncurryThis(Symbol.prototype.valueOf); +} + +function checkBoxedPrimitive(value, prototypeValueOf) { + if (typeof value !== 'object') { + return false; + } + try { + prototypeValueOf(value); + return true; + } catch(e) { + return false; + } +} + +exports.isArgumentsObject = isArgumentsObject; +exports.isGeneratorFunction = isGeneratorFunction; +exports.isTypedArray = isTypedArray; + +// Taken from here and modified for better browser support +// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js +function isPromise(input) { + return ( + ( + typeof Promise !== 'undefined' && + input instanceof Promise + ) || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) + ); +} +exports.isPromise = isPromise; + +function isArrayBufferView(value) { + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + + return ( + isTypedArray(value) || + isDataView(value) + ); +} +exports.isArrayBufferView = isArrayBufferView; + + +function isUint8Array(value) { + return whichTypedArray(value) === 'Uint8Array'; +} +exports.isUint8Array = isUint8Array; + +function isUint8ClampedArray(value) { + return whichTypedArray(value) === 'Uint8ClampedArray'; +} +exports.isUint8ClampedArray = isUint8ClampedArray; + +function isUint16Array(value) { + return whichTypedArray(value) === 'Uint16Array'; +} +exports.isUint16Array = isUint16Array; + +function isUint32Array(value) { + return whichTypedArray(value) === 'Uint32Array'; +} +exports.isUint32Array = isUint32Array; + +function isInt8Array(value) { + return whichTypedArray(value) === 'Int8Array'; +} +exports.isInt8Array = isInt8Array; + +function isInt16Array(value) { + return whichTypedArray(value) === 'Int16Array'; +} +exports.isInt16Array = isInt16Array; + +function isInt32Array(value) { + return whichTypedArray(value) === 'Int32Array'; +} +exports.isInt32Array = isInt32Array; + +function isFloat32Array(value) { + return whichTypedArray(value) === 'Float32Array'; +} +exports.isFloat32Array = isFloat32Array; + +function isFloat64Array(value) { + return whichTypedArray(value) === 'Float64Array'; +} +exports.isFloat64Array = isFloat64Array; + +function isBigInt64Array(value) { + return whichTypedArray(value) === 'BigInt64Array'; +} +exports.isBigInt64Array = isBigInt64Array; + +function isBigUint64Array(value) { + return whichTypedArray(value) === 'BigUint64Array'; +} +exports.isBigUint64Array = isBigUint64Array; + +function isMapToString(value) { + return ObjectToString(value) === '[object Map]'; +} +isMapToString.working = ( + typeof Map !== 'undefined' && + isMapToString(new Map()) +); + +function isMap(value) { + if (typeof Map === 'undefined') { + return false; + } + + return isMapToString.working + ? isMapToString(value) + : value instanceof Map; +} +exports.isMap = isMap; + +function isSetToString(value) { + return ObjectToString(value) === '[object Set]'; +} +isSetToString.working = ( + typeof Set !== 'undefined' && + isSetToString(new Set()) +); +function isSet(value) { + if (typeof Set === 'undefined') { + return false; + } + + return isSetToString.working + ? isSetToString(value) + : value instanceof Set; +} +exports.isSet = isSet; + +function isWeakMapToString(value) { + return ObjectToString(value) === '[object WeakMap]'; +} +isWeakMapToString.working = ( + typeof WeakMap !== 'undefined' && + isWeakMapToString(new WeakMap()) +); +function isWeakMap(value) { + if (typeof WeakMap === 'undefined') { + return false; + } + + return isWeakMapToString.working + ? isWeakMapToString(value) + : value instanceof WeakMap; +} +exports.isWeakMap = isWeakMap; + +function isWeakSetToString(value) { + return ObjectToString(value) === '[object WeakSet]'; +} +isWeakSetToString.working = ( + typeof WeakSet !== 'undefined' && + isWeakSetToString(new WeakSet()) +); +function isWeakSet(value) { + return isWeakSetToString(value); +} +exports.isWeakSet = isWeakSet; + +function isArrayBufferToString(value) { + return ObjectToString(value) === '[object ArrayBuffer]'; +} +isArrayBufferToString.working = ( + typeof ArrayBuffer !== 'undefined' && + isArrayBufferToString(new ArrayBuffer()) +); +function isArrayBuffer(value) { + if (typeof ArrayBuffer === 'undefined') { + return false; + } + + return isArrayBufferToString.working + ? isArrayBufferToString(value) + : value instanceof ArrayBuffer; +} +exports.isArrayBuffer = isArrayBuffer; + +function isDataViewToString(value) { + return ObjectToString(value) === '[object DataView]'; +} +isDataViewToString.working = ( + typeof ArrayBuffer !== 'undefined' && + typeof DataView !== 'undefined' && + isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) +); +function isDataView(value) { + if (typeof DataView === 'undefined') { + return false; + } + + return isDataViewToString.working + ? isDataViewToString(value) + : value instanceof DataView; +} +exports.isDataView = isDataView; + +function isSharedArrayBufferToString(value) { + return ObjectToString(value) === '[object SharedArrayBuffer]'; +} +isSharedArrayBufferToString.working = ( + typeof SharedArrayBuffer !== 'undefined' && + isSharedArrayBufferToString(new SharedArrayBuffer()) +); +function isSharedArrayBuffer(value) { + if (typeof SharedArrayBuffer === 'undefined') { + return false; + } + + return isSharedArrayBufferToString.working + ? isSharedArrayBufferToString(value) + : value instanceof SharedArrayBuffer; +} +exports.isSharedArrayBuffer = isSharedArrayBuffer; + +function isAsyncFunction(value) { + return ObjectToString(value) === '[object AsyncFunction]'; +} +exports.isAsyncFunction = isAsyncFunction; + +function isMapIterator(value) { + return ObjectToString(value) === '[object Map Iterator]'; +} +exports.isMapIterator = isMapIterator; + +function isSetIterator(value) { + return ObjectToString(value) === '[object Set Iterator]'; +} +exports.isSetIterator = isSetIterator; + +function isGeneratorObject(value) { + return ObjectToString(value) === '[object Generator]'; +} +exports.isGeneratorObject = isGeneratorObject; + +function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === '[object WebAssembly.Module]'; +} +exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + +function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); +} +exports.isNumberObject = isNumberObject; + +function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); +} +exports.isStringObject = isStringObject; + +function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); +} +exports.isBooleanObject = isBooleanObject; + +function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); +} +exports.isBigIntObject = isBigIntObject; + +function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); +} +exports.isSymbolObject = isSymbolObject; + +function isBoxedPrimitive(value) { + return ( + isNumberObject(value) || + isStringObject(value) || + isBooleanObject(value) || + isBigIntObject(value) || + isSymbolObject(value) + ); +} +exports.isBoxedPrimitive = isBoxedPrimitive; + +function isAnyArrayBuffer(value) { + return typeof Uint8Array !== 'undefined' && ( + isArrayBuffer(value) || + isSharedArrayBuffer(value) + ); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; + +['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { + Object.defineProperty(exports, method, { + enumerable: false, + value: function() { + throw new Error(method + ' is not supported in userland'); + } + }); +}); + +},{"is-arguments":46,"is-generator-function":47,"is-typed-array":48,"which-typed-array":82}],81:[function(require,module,exports){ +(function (process){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + if (typeof process !== 'undefined' && process.noDeprecation === true) { + return fn; + } + + // Allow for deprecating things in the process of starting up. + if (typeof process === 'undefined') { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnvRegex = /^$/; + +if (process.env.NODE_DEBUG) { + var debugEnv = process.env.NODE_DEBUG; + debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^') + .toUpperCase(); + debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); +} +exports.debuglog = function(set) { + set = set.toUpperCase(); + if (!debugs[set]) { + if (debugEnvRegex.test(set)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +exports.types = require('./support/types'); + +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +exports.types.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; +exports.types.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; +exports.types.isNativeError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + +exports.promisify = function promisify(original) { + if (typeof original !== 'function') + throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); +} + +exports.promisify.custom = kCustomPromisifiedSymbol + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); +} + +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); + } + var self = this; + var cb = function() { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args) + .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, + function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, + getOwnPropertyDescriptors(original)); + return callbackified; +} +exports.callbackify = callbackify; + +}).call(this)}).call(this,require('_process')) +},{"./support/isBuffer":79,"./support/types":80,"_process":60,"inherits":45}],82:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +var forEach = require('foreach'); +var availableTypedArrays = require('available-typed-arrays'); +var callBound = require('es-abstract/helpers/callBound'); + +var $toString = callBound('Object.prototype.toString'); +var hasSymbols = require('has-symbols')(); +var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; + +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var toStrTags = {}; +var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + if (typeof global[typedArray] === 'function') { + var arr = new global[typedArray](); + if (!(Symbol.toStringTag in arr)) { + throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); + } + var proto = getPrototypeOf(arr); + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + descriptor = gOPD(superProto, Symbol.toStringTag); + } + toStrTags[typedArray] = descriptor.get; + } + }); +} + +var tryTypedArrays = function tryAllTypedArrays(value) { + var foundName = false; + forEach(toStrTags, function (getter, typedArray) { + if (!foundName) { + try { + var name = getter.call(value); + if (name === typedArray) { + foundName = name; + } + } catch (e) {} + } + }); + return foundName; +}; + +var isTypedArray = require('is-typed-array'); + +module.exports = function whichTypedArray(value) { + if (!isTypedArray(value)) { return false; } + if (!hasToStringTag) { return $slice($toString(value), 8, -1); } + return tryTypedArrays(value); +}; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"available-typed-arrays":27,"es-abstract/helpers/callBound":36,"es-abstract/helpers/getOwnPropertyDescriptor":37,"foreach":39,"has-symbols":42,"is-typed-array":48}]},{},[20])(20) +}); \ No newline at end of file diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/bitmapper.js b/node_modules/@jimp/png/node_modules/pngjs/lib/bitmapper.js new file mode 100644 index 00000000..18378a02 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/bitmapper.js @@ -0,0 +1,267 @@ +"use strict"; + +let interlaceUtils = require("./interlace"); + +let pixelBppMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, data, pxPos, rawPos) { + if (rawPos === data.length) { + throw new Error("Ran out of data"); + } + + let pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = 0xff; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function (pxData, data, pxPos, rawPos) { + if (rawPos + 1 >= data.length) { + throw new Error("Ran out of data"); + } + + let pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = data[rawPos + 1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, data, pxPos, rawPos) { + if (rawPos + 2 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = 0xff; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, data, pxPos, rawPos) { + if (rawPos + 3 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = data[rawPos + 3]; + }, +]; + +let pixelBppCustomMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = maxBit; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function (pxData, pixelData, pxPos) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = pixelData[1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = maxBit; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, pixelData, pxPos) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = pixelData[3]; + }, +]; + +function bitRetriever(data, depth) { + let leftOver = []; + let i = 0; + + function split() { + if (i === data.length) { + throw new Error("Ran out of data"); + } + let byte = data[i]; + i++; + let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1; + switch (depth) { + default: + throw new Error("unrecognised depth"); + case 16: + byte2 = data[i]; + i++; + leftOver.push((byte << 8) + byte2); + break; + case 4: + byte2 = byte & 0x0f; + byte1 = byte >> 4; + leftOver.push(byte1, byte2); + break; + case 2: + byte4 = byte & 3; + byte3 = (byte >> 2) & 3; + byte2 = (byte >> 4) & 3; + byte1 = (byte >> 6) & 3; + leftOver.push(byte1, byte2, byte3, byte4); + break; + case 1: + byte8 = byte & 1; + byte7 = (byte >> 1) & 1; + byte6 = (byte >> 2) & 1; + byte5 = (byte >> 3) & 1; + byte4 = (byte >> 4) & 1; + byte3 = (byte >> 5) & 1; + byte2 = (byte >> 6) & 1; + byte1 = (byte >> 7) & 1; + leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8); + break; + } + } + + return { + get: function (count) { + while (leftOver.length < count) { + split(); + } + let returner = leftOver.slice(0, count); + leftOver = leftOver.slice(count); + return returner; + }, + resetAfterLine: function () { + leftOver.length = 0; + }, + end: function () { + if (i !== data.length) { + throw new Error("extra data found"); + } + }, + }; +} + +function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pxPos = getPxPos(x, y, imagePass); + pixelBppMapper[bpp](pxData, data, pxPos, rawPos); + rawPos += bpp; //eslint-disable-line no-param-reassign + } + } + return rawPos; +} + +function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pixelData = bits.get(bpp); + let pxPos = getPxPos(x, y, imagePass); + pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); + } + bits.resetAfterLine(); + } +} + +exports.dataToBitMap = function (data, bitmapInfo) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let depth = bitmapInfo.depth; + let bpp = bitmapInfo.bpp; + let interlace = bitmapInfo.interlace; + let bits; + + if (depth !== 8) { + bits = bitRetriever(data, depth); + } + let pxData; + if (depth <= 8) { + pxData = Buffer.alloc(width * height * 4); + } else { + pxData = new Uint16Array(width * height * 4); + } + let maxBit = Math.pow(2, depth) - 1; + let rawPos = 0; + let images; + let getPxPos; + + if (interlace) { + images = interlaceUtils.getImagePasses(width, height); + getPxPos = interlaceUtils.getInterlaceIterator(width, height); + } else { + let nonInterlacedPxPos = 0; + getPxPos = function () { + let returner = nonInterlacedPxPos; + nonInterlacedPxPos += 4; + return returner; + }; + images = [{ width: width, height: height }]; + } + + for (let imageIndex = 0; imageIndex < images.length; imageIndex++) { + if (depth === 8) { + rawPos = mapImage8Bit( + images[imageIndex], + pxData, + getPxPos, + bpp, + data, + rawPos + ); + } else { + mapImageCustomBit( + images[imageIndex], + pxData, + getPxPos, + bpp, + bits, + maxBit + ); + } + } + if (depth === 8) { + if (rawPos !== data.length) { + throw new Error("extra data found"); + } + } else { + bits.end(); + } + + return pxData; +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/bitpacker.js b/node_modules/@jimp/png/node_modules/pngjs/lib/bitpacker.js new file mode 100644 index 00000000..d7a4e656 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/bitpacker.js @@ -0,0 +1,158 @@ +"use strict"; + +let constants = require("./constants"); + +module.exports = function (dataIn, width, height, options) { + let outHasAlpha = + [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf( + options.colorType + ) !== -1; + if (options.colorType === options.inputColorType) { + let bigEndian = (function () { + let buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] !== 256; + })(); + // If no need to convert to grayscale and alpha is present/absent in both, take a fast route + if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) { + return dataIn; + } + } + + // map to a UInt16 array if data is 16bit, fix endianness below + let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); + + let maxValue = 255; + let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType]; + if (inBpp === 4 && !options.inputHasAlpha) { + inBpp = 3; + } + let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType]; + if (options.bitDepth === 16) { + maxValue = 65535; + outBpp *= 2; + } + let outData = Buffer.alloc(width * height * outBpp); + + let inIndex = 0; + let outIndex = 0; + + let bgColor = options.bgColor || {}; + if (bgColor.red === undefined) { + bgColor.red = maxValue; + } + if (bgColor.green === undefined) { + bgColor.green = maxValue; + } + if (bgColor.blue === undefined) { + bgColor.blue = maxValue; + } + + function getRGBA() { + let red; + let green; + let blue; + let alpha = maxValue; + switch (options.inputColorType) { + case constants.COLORTYPE_COLOR_ALPHA: + alpha = data[inIndex + 3]; + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_COLOR: + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_ALPHA: + alpha = data[inIndex + 1]; + red = data[inIndex]; + green = red; + blue = red; + break; + case constants.COLORTYPE_GRAYSCALE: + red = data[inIndex]; + green = red; + blue = red; + break; + default: + throw new Error( + "input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + + if (options.inputHasAlpha) { + if (!outHasAlpha) { + alpha /= maxValue; + red = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), + maxValue + ); + green = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), + maxValue + ); + blue = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), + maxValue + ); + } + } + return { red: red, green: green, blue: blue, alpha: alpha }; + } + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let rgba = getRGBA(data, inIndex); + + switch (options.colorType) { + case constants.COLORTYPE_COLOR_ALPHA: + case constants.COLORTYPE_COLOR: + if (options.bitDepth === 8) { + outData[outIndex] = rgba.red; + outData[outIndex + 1] = rgba.green; + outData[outIndex + 2] = rgba.blue; + if (outHasAlpha) { + outData[outIndex + 3] = rgba.alpha; + } + } else { + outData.writeUInt16BE(rgba.red, outIndex); + outData.writeUInt16BE(rgba.green, outIndex + 2); + outData.writeUInt16BE(rgba.blue, outIndex + 4); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 6); + } + } + break; + case constants.COLORTYPE_ALPHA: + case constants.COLORTYPE_GRAYSCALE: { + // Convert to grayscale and alpha + let grayscale = (rgba.red + rgba.green + rgba.blue) / 3; + if (options.bitDepth === 8) { + outData[outIndex] = grayscale; + if (outHasAlpha) { + outData[outIndex + 1] = rgba.alpha; + } + } else { + outData.writeUInt16BE(grayscale, outIndex); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 2); + } + } + break; + } + default: + throw new Error("unrecognised color Type " + options.colorType); + } + + inIndex += inBpp; + outIndex += outBpp; + } + } + + return outData; +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/chunkstream.js b/node_modules/@jimp/png/node_modules/pngjs/lib/chunkstream.js new file mode 100644 index 00000000..95b46d48 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/chunkstream.js @@ -0,0 +1,189 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); + +let ChunkStream = (module.exports = function () { + Stream.call(this); + + this._buffers = []; + this._buffered = 0; + + this._reads = []; + this._paused = false; + + this._encoding = "utf8"; + this.writable = true; +}); +util.inherits(ChunkStream, Stream); + +ChunkStream.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); + + process.nextTick( + function () { + this._process(); + + // its paused and there is not enought data then ask for more + if (this._paused && this._reads && this._reads.length > 0) { + this._paused = false; + + this.emit("drain"); + } + }.bind(this) + ); +}; + +ChunkStream.prototype.write = function (data, encoding) { + if (!this.writable) { + this.emit("error", new Error("Stream not writable")); + return false; + } + + let dataBuffer; + if (Buffer.isBuffer(data)) { + dataBuffer = data; + } else { + dataBuffer = Buffer.from(data, encoding || this._encoding); + } + + this._buffers.push(dataBuffer); + this._buffered += dataBuffer.length; + + this._process(); + + // ok if there are no more read requests + if (this._reads && this._reads.length === 0) { + this._paused = true; + } + + return this.writable && !this._paused; +}; + +ChunkStream.prototype.end = function (data, encoding) { + if (data) { + this.write(data, encoding); + } + + this.writable = false; + + // already destroyed + if (!this._buffers) { + return; + } + + // enqueue or handle end + if (this._buffers.length === 0) { + this._end(); + } else { + this._buffers.push(null); + this._process(); + } +}; + +ChunkStream.prototype.destroySoon = ChunkStream.prototype.end; + +ChunkStream.prototype._end = function () { + if (this._reads.length > 0) { + this.emit("error", new Error("Unexpected end of input")); + } + + this.destroy(); +}; + +ChunkStream.prototype.destroy = function () { + if (!this._buffers) { + return; + } + + this.writable = false; + this._reads = null; + this._buffers = null; + + this.emit("close"); +}; + +ChunkStream.prototype._processReadAllowingLess = function (read) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + // first we need to peek into first buffer + let smallerBuf = this._buffers[0]; + + // ok there is more data than we need + if (smallerBuf.length > read.length) { + this._buffered -= read.length; + this._buffers[0] = smallerBuf.slice(read.length); + + read.func.call(this, smallerBuf.slice(0, read.length)); + } else { + // ok this is less than maximum length so use it all + this._buffered -= smallerBuf.length; + this._buffers.shift(); // == smallerBuf + + read.func.call(this, smallerBuf); + } +}; + +ChunkStream.prototype._processRead = function (read) { + this._reads.shift(); // == read + + let pos = 0; + let count = 0; + let data = Buffer.alloc(read.length); + + // create buffer for all data + while (pos < read.length) { + let buf = this._buffers[count++]; + let len = Math.min(buf.length, read.length - pos); + + buf.copy(data, pos, 0, len); + pos += len; + + // last buffer wasn't used all so just slice it and leave + if (len !== buf.length) { + this._buffers[--count] = buf.slice(len); + } + } + + // remove all used buffers + if (count > 0) { + this._buffers.splice(0, count); + } + + this._buffered -= read.length; + + read.func.call(this, data); +}; + +ChunkStream.prototype._process = function () { + try { + // as long as there is any data and read requests + while (this._buffered > 0 && this._reads && this._reads.length > 0) { + let read = this._reads[0]; + + // read any data (but no more than length) + if (read.allowLess) { + this._processReadAllowingLess(read); + } else if (this._buffered >= read.length) { + // ok we can meet some expectations + + this._processRead(read); + } else { + // not enought data to satisfy first request in queue + // so we need to wait for more + break; + } + } + + if (this._buffers && !this.writable) { + this._end(); + } + } catch (ex) { + this.emit("error", ex); + } +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/constants.js b/node_modules/@jimp/png/node_modules/pngjs/lib/constants.js new file mode 100644 index 00000000..21fdad68 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/constants.js @@ -0,0 +1,32 @@ +"use strict"; + +module.exports = { + PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], + + TYPE_IHDR: 0x49484452, + TYPE_IEND: 0x49454e44, + TYPE_IDAT: 0x49444154, + TYPE_PLTE: 0x504c5445, + TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase + TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase + + // color-type bits + COLORTYPE_GRAYSCALE: 0, + COLORTYPE_PALETTE: 1, + COLORTYPE_COLOR: 2, + COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha + + // color-type combinations + COLORTYPE_PALETTE_COLOR: 3, + COLORTYPE_COLOR_ALPHA: 6, + + COLORTYPE_TO_BPP_MAP: { + 0: 1, + 2: 3, + 3: 1, + 4: 2, + 6: 4, + }, + + GAMMA_DIVISION: 100000, +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/crc.js b/node_modules/@jimp/png/node_modules/pngjs/lib/crc.js new file mode 100644 index 00000000..950ec8ae --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/crc.js @@ -0,0 +1,40 @@ +"use strict"; + +let crcTable = []; + +(function () { + for (let i = 0; i < 256; i++) { + let currentCrc = i; + for (let j = 0; j < 8; j++) { + if (currentCrc & 1) { + currentCrc = 0xedb88320 ^ (currentCrc >>> 1); + } else { + currentCrc = currentCrc >>> 1; + } + } + crcTable[i] = currentCrc; + } +})(); + +let CrcCalculator = (module.exports = function () { + this._crc = -1; +}); + +CrcCalculator.prototype.write = function (data) { + for (let i = 0; i < data.length; i++) { + this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8); + } + return true; +}; + +CrcCalculator.prototype.crc32 = function () { + return this._crc ^ -1; +}; + +CrcCalculator.crc32 = function (buf) { + let crc = -1; + for (let i = 0; i < buf.length; i++) { + crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return crc ^ -1; +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/filter-pack.js b/node_modules/@jimp/png/node_modules/pngjs/lib/filter-pack.js new file mode 100644 index 00000000..32c85c40 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/filter-pack.js @@ -0,0 +1,171 @@ +"use strict"; + +let paethPredictor = require("./paeth-predictor"); + +function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + rawData[rawPos + x] = pxData[pxPos + x]; + } +} + +function filterSumNone(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + + for (let i = pxPos; i < length; i++) { + sum += Math.abs(pxData[i]); + } + return sum; +} + +function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + rawData[rawPos + x] = val; + } +} + +function filterSumSub(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + sum += Math.abs(val); + } + + return sum; +} + +function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - up; + + rawData[rawPos + x] = val; + } +} + +function filterSumUp(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + for (let x = pxPos; x < length; x++) { + let up = pxPos > 0 ? pxData[x - byteWidth] : 0; + let val = pxData[x] - up; + + sum += Math.abs(val); + } + + return sum; +} + +function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + rawData[rawPos + x] = val; + } +} + +function filterSumAvg(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + sum += Math.abs(val); + } + + return sum; +} + +function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + rawData[rawPos + x] = val; + } +} + +function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + sum += Math.abs(val); + } + + return sum; +} + +let filters = { + 0: filterNone, + 1: filterSub, + 2: filterUp, + 3: filterAvg, + 4: filterPaeth, +}; + +let filterSums = { + 0: filterSumNone, + 1: filterSumSub, + 2: filterSumUp, + 3: filterSumAvg, + 4: filterSumPaeth, +}; + +module.exports = function (pxData, width, height, options, bpp) { + let filterTypes; + if (!("filterType" in options) || options.filterType === -1) { + filterTypes = [0, 1, 2, 3, 4]; + } else if (typeof options.filterType === "number") { + filterTypes = [options.filterType]; + } else { + throw new Error("unrecognised filter types"); + } + + if (options.bitDepth === 16) { + bpp *= 2; + } + let byteWidth = width * bpp; + let rawPos = 0; + let pxPos = 0; + let rawData = Buffer.alloc((byteWidth + 1) * height); + + let sel = filterTypes[0]; + + for (let y = 0; y < height; y++) { + if (filterTypes.length > 1) { + // find best filter for this line (with lowest sum of values) + let min = Infinity; + + for (let i = 0; i < filterTypes.length; i++) { + let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp); + if (sum < min) { + sel = filterTypes[i]; + min = sum; + } + } + } + + rawData[rawPos] = sel; + rawPos++; + filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); + rawPos += byteWidth; + pxPos += byteWidth; + } + return rawData; +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse-async.js b/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse-async.js new file mode 100644 index 00000000..832b86cd --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse-async.js @@ -0,0 +1,24 @@ +"use strict"; + +let util = require("util"); +let ChunkStream = require("./chunkstream"); +let Filter = require("./filter-parse"); + +let FilterAsync = (module.exports = function (bitmapInfo) { + ChunkStream.call(this); + + let buffers = []; + let that = this; + this._filter = new Filter(bitmapInfo, { + read: this.read.bind(this), + write: function (buffer) { + buffers.push(buffer); + }, + complete: function () { + that.emit("complete", Buffer.concat(buffers)); + }, + }); + + this._filter.start(); +}); +util.inherits(FilterAsync, ChunkStream); diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse-sync.js b/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse-sync.js new file mode 100644 index 00000000..6924d161 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse-sync.js @@ -0,0 +1,21 @@ +"use strict"; + +let SyncReader = require("./sync-reader"); +let Filter = require("./filter-parse"); + +exports.process = function (inBuffer, bitmapInfo) { + let outBuffers = []; + let reader = new SyncReader(inBuffer); + let filter = new Filter(bitmapInfo, { + read: reader.read.bind(reader), + write: function (bufferPart) { + outBuffers.push(bufferPart); + }, + complete: function () {}, + }); + + filter.start(); + reader.process(); + + return Buffer.concat(outBuffers); +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse.js b/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse.js new file mode 100644 index 00000000..3a32e5ee --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/filter-parse.js @@ -0,0 +1,177 @@ +"use strict"; + +let interlaceUtils = require("./interlace"); +let paethPredictor = require("./paeth-predictor"); + +function getByteWidth(width, bpp, depth) { + let byteWidth = width * bpp; + if (depth !== 8) { + byteWidth = Math.ceil(byteWidth / (8 / depth)); + } + return byteWidth; +} + +let Filter = (module.exports = function (bitmapInfo, dependencies) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let interlace = bitmapInfo.interlace; + let bpp = bitmapInfo.bpp; + let depth = bitmapInfo.depth; + + this.read = dependencies.read; + this.write = dependencies.write; + this.complete = dependencies.complete; + + this._imageIndex = 0; + this._images = []; + if (interlace) { + let passes = interlaceUtils.getImagePasses(width, height); + for (let i = 0; i < passes.length; i++) { + this._images.push({ + byteWidth: getByteWidth(passes[i].width, bpp, depth), + height: passes[i].height, + lineIndex: 0, + }); + } + } else { + this._images.push({ + byteWidth: getByteWidth(width, bpp, depth), + height: height, + lineIndex: 0, + }); + } + + // when filtering the line we look at the pixel to the left + // the spec also says it is done on a byte level regardless of the number of pixels + // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back + // a pixel rather than just a different byte part. However if we are sub byte, we ignore. + if (depth === 8) { + this._xComparison = bpp; + } else if (depth === 16) { + this._xComparison = bpp * 2; + } else { + this._xComparison = 1; + } +}); + +Filter.prototype.start = function () { + this.read( + this._images[this._imageIndex].byteWidth + 1, + this._reverseFilterLine.bind(this) + ); +}; + +Filter.prototype._unFilterType1 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + unfilteredLine[x] = rawByte + f1Left; + } +}; + +Filter.prototype._unFilterType2 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f2Up = lastLine ? lastLine[x] : 0; + unfilteredLine[x] = rawByte + f2Up; + } +}; + +Filter.prototype._unFilterType3 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f3Up = lastLine ? lastLine[x] : 0; + let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f3Add = Math.floor((f3Left + f3Up) / 2); + unfilteredLine[x] = rawByte + f3Add; + } +}; + +Filter.prototype._unFilterType4 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f4Up = lastLine ? lastLine[x] : 0; + let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; + let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); + unfilteredLine[x] = rawByte + f4Add; + } +}; + +Filter.prototype._reverseFilterLine = function (rawData) { + let filter = rawData[0]; + let unfilteredLine; + let currentImage = this._images[this._imageIndex]; + let byteWidth = currentImage.byteWidth; + + if (filter === 0) { + unfilteredLine = rawData.slice(1, byteWidth + 1); + } else { + unfilteredLine = Buffer.alloc(byteWidth); + + switch (filter) { + case 1: + this._unFilterType1(rawData, unfilteredLine, byteWidth); + break; + case 2: + this._unFilterType2(rawData, unfilteredLine, byteWidth); + break; + case 3: + this._unFilterType3(rawData, unfilteredLine, byteWidth); + break; + case 4: + this._unFilterType4(rawData, unfilteredLine, byteWidth); + break; + default: + throw new Error("Unrecognised filter type - " + filter); + } + } + + this.write(unfilteredLine); + + currentImage.lineIndex++; + if (currentImage.lineIndex >= currentImage.height) { + this._lastLine = null; + this._imageIndex++; + currentImage = this._images[this._imageIndex]; + } else { + this._lastLine = unfilteredLine; + } + + if (currentImage) { + // read, using the byte width that may be from the new current image + this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this)); + } else { + this._lastLine = null; + this.complete(); + } +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/format-normaliser.js b/node_modules/@jimp/png/node_modules/pngjs/lib/format-normaliser.js new file mode 100644 index 00000000..209b66bb --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/format-normaliser.js @@ -0,0 +1,93 @@ +"use strict"; + +function dePalette(indata, outdata, width, height, palette) { + let pxPos = 0; + // use values from palette + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let color = palette[indata[pxPos]]; + + if (!color) { + throw new Error("index " + indata[pxPos] + " not in palette"); + } + + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = color[i]; + } + pxPos += 4; + } + } +} + +function replaceTransparentColor(indata, outdata, width, height, transColor) { + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let makeTrans = false; + + if (transColor.length === 1) { + if (transColor[0] === indata[pxPos]) { + makeTrans = true; + } + } else if ( + transColor[0] === indata[pxPos] && + transColor[1] === indata[pxPos + 1] && + transColor[2] === indata[pxPos + 2] + ) { + makeTrans = true; + } + if (makeTrans) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = 0; + } + } + pxPos += 4; + } + } +} + +function scaleDepth(indata, outdata, width, height, depth) { + let maxOutSample = 255; + let maxInSample = Math.pow(2, depth) - 1; + let pxPos = 0; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = Math.floor( + (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5 + ); + } + pxPos += 4; + } + } +} + +module.exports = function (indata, imageData, skipRescale = false) { + let depth = imageData.depth; + let width = imageData.width; + let height = imageData.height; + let colorType = imageData.colorType; + let transColor = imageData.transColor; + let palette = imageData.palette; + + let outdata = indata; // only different for 16 bits + + if (colorType === 3) { + // paletted + dePalette(indata, outdata, width, height, palette); + } else { + if (transColor) { + replaceTransparentColor(indata, outdata, width, height, transColor); + } + // if it needs scaling + if (depth !== 8 && !skipRescale) { + // if we need to change the buffer size + if (depth === 16) { + outdata = Buffer.alloc(width * height * 4); + } + scaleDepth(indata, outdata, width, height, depth); + } + } + return outdata; +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/interlace.js b/node_modules/@jimp/png/node_modules/pngjs/lib/interlace.js new file mode 100644 index 00000000..a035cb15 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/interlace.js @@ -0,0 +1,95 @@ +"use strict"; + +// Adam 7 +// 0 1 2 3 4 5 6 7 +// 0 x 6 4 6 x 6 4 6 +// 1 7 7 7 7 7 7 7 7 +// 2 5 6 5 6 5 6 5 6 +// 3 7 7 7 7 7 7 7 7 +// 4 3 6 4 6 3 6 4 6 +// 5 7 7 7 7 7 7 7 7 +// 6 5 6 5 6 5 6 5 6 +// 7 7 7 7 7 7 7 7 7 + +let imagePasses = [ + { + // pass 1 - 1px + x: [0], + y: [0], + }, + { + // pass 2 - 1px + x: [4], + y: [0], + }, + { + // pass 3 - 2px + x: [0, 4], + y: [4], + }, + { + // pass 4 - 4px + x: [2, 6], + y: [0, 4], + }, + { + // pass 5 - 8px + x: [0, 2, 4, 6], + y: [2, 6], + }, + { + // pass 6 - 16px + x: [1, 3, 5, 7], + y: [0, 2, 4, 6], + }, + { + // pass 7 - 32px + x: [0, 1, 2, 3, 4, 5, 6, 7], + y: [1, 3, 5, 7], + }, +]; + +exports.getImagePasses = function (width, height) { + let images = []; + let xLeftOver = width % 8; + let yLeftOver = height % 8; + let xRepeats = (width - xLeftOver) / 8; + let yRepeats = (height - yLeftOver) / 8; + for (let i = 0; i < imagePasses.length; i++) { + let pass = imagePasses[i]; + let passWidth = xRepeats * pass.x.length; + let passHeight = yRepeats * pass.y.length; + for (let j = 0; j < pass.x.length; j++) { + if (pass.x[j] < xLeftOver) { + passWidth++; + } else { + break; + } + } + for (let j = 0; j < pass.y.length; j++) { + if (pass.y[j] < yLeftOver) { + passHeight++; + } else { + break; + } + } + if (passWidth > 0 && passHeight > 0) { + images.push({ width: passWidth, height: passHeight, index: i }); + } + } + return images; +}; + +exports.getInterlaceIterator = function (width) { + return function (x, y, pass) { + let outerXLeftOver = x % imagePasses[pass].x.length; + let outerX = + ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 + + imagePasses[pass].x[outerXLeftOver]; + let outerYLeftOver = y % imagePasses[pass].y.length; + let outerY = + ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 + + imagePasses[pass].y[outerYLeftOver]; + return outerX * 4 + outerY * width * 4; + }; +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/packer-async.js b/node_modules/@jimp/png/node_modules/pngjs/lib/packer-async.js new file mode 100644 index 00000000..f3df73aa --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/packer-async.js @@ -0,0 +1,50 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let constants = require("./constants"); +let Packer = require("./packer"); + +let PackerAsync = (module.exports = function (opt) { + Stream.call(this); + + let options = opt || {}; + + this._packer = new Packer(options); + this._deflate = this._packer.createDeflate(); + + this.readable = true; +}); +util.inherits(PackerAsync, Stream); + +PackerAsync.prototype.pack = function (data, width, height, gamma) { + // Signature + this.emit("data", Buffer.from(constants.PNG_SIGNATURE)); + this.emit("data", this._packer.packIHDR(width, height)); + + if (gamma) { + this.emit("data", this._packer.packGAMA(gamma)); + } + + let filteredData = this._packer.filterData(data, width, height); + + // compress it + this._deflate.on("error", this.emit.bind(this, "error")); + + this._deflate.on( + "data", + function (compressedData) { + this.emit("data", this._packer.packIDAT(compressedData)); + }.bind(this) + ); + + this._deflate.on( + "end", + function () { + this.emit("data", this._packer.packIEND()); + this.emit("end"); + }.bind(this) + ); + + this._deflate.end(filteredData); +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/packer-sync.js b/node_modules/@jimp/png/node_modules/pngjs/lib/packer-sync.js new file mode 100644 index 00000000..f5ab0b3d --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/packer-sync.js @@ -0,0 +1,56 @@ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let constants = require("./constants"); +let Packer = require("./packer"); + +module.exports = function (metaData, opt) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let options = opt || {}; + + let packer = new Packer(options); + + let chunks = []; + + // Signature + chunks.push(Buffer.from(constants.PNG_SIGNATURE)); + + // Header + chunks.push(packer.packIHDR(metaData.width, metaData.height)); + + if (metaData.gamma) { + chunks.push(packer.packGAMA(metaData.gamma)); + } + + let filteredData = packer.filterData( + metaData.data, + metaData.width, + metaData.height + ); + + // compress it + let compressedData = zlib.deflateSync( + filteredData, + packer.getDeflateOptions() + ); + filteredData = null; + + if (!compressedData || !compressedData.length) { + throw new Error("bad png - invalid compressed data response"); + } + chunks.push(packer.packIDAT(compressedData)); + + // End + chunks.push(packer.packIEND()); + + return Buffer.concat(chunks); +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/packer.js b/node_modules/@jimp/png/node_modules/pngjs/lib/packer.js new file mode 100644 index 00000000..4aba12c8 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/packer.js @@ -0,0 +1,129 @@ +"use strict"; + +let constants = require("./constants"); +let CrcStream = require("./crc"); +let bitPacker = require("./bitpacker"); +let filter = require("./filter-pack"); +let zlib = require("zlib"); + +let Packer = (module.exports = function (options) { + this._options = options; + + options.deflateChunkSize = options.deflateChunkSize || 32 * 1024; + options.deflateLevel = + options.deflateLevel != null ? options.deflateLevel : 9; + options.deflateStrategy = + options.deflateStrategy != null ? options.deflateStrategy : 3; + options.inputHasAlpha = + options.inputHasAlpha != null ? options.inputHasAlpha : true; + options.deflateFactory = options.deflateFactory || zlib.createDeflate; + options.bitDepth = options.bitDepth || 8; + // This is outputColorType + options.colorType = + typeof options.colorType === "number" + ? options.colorType + : constants.COLORTYPE_COLOR_ALPHA; + options.inputColorType = + typeof options.inputColorType === "number" + ? options.inputColorType + : constants.COLORTYPE_COLOR_ALPHA; + + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.colorType) === -1 + ) { + throw new Error( + "option color type:" + options.colorType + " is not supported at present" + ); + } + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.inputColorType) === -1 + ) { + throw new Error( + "option input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + if (options.bitDepth !== 8 && options.bitDepth !== 16) { + throw new Error( + "option bit depth:" + options.bitDepth + " is not supported at present" + ); + } +}); + +Packer.prototype.getDeflateOptions = function () { + return { + chunkSize: this._options.deflateChunkSize, + level: this._options.deflateLevel, + strategy: this._options.deflateStrategy, + }; +}; + +Packer.prototype.createDeflate = function () { + return this._options.deflateFactory(this.getDeflateOptions()); +}; + +Packer.prototype.filterData = function (data, width, height) { + // convert to correct format for filtering (e.g. right bpp and bit depth) + let packedData = bitPacker(data, width, height, this._options); + + // filter pixel data + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType]; + let filteredData = filter(packedData, width, height, this._options, bpp); + return filteredData; +}; + +Packer.prototype._packChunk = function (type, data) { + let len = data ? data.length : 0; + let buf = Buffer.alloc(len + 12); + + buf.writeUInt32BE(len, 0); + buf.writeUInt32BE(type, 4); + + if (data) { + data.copy(buf, 8); + } + + buf.writeInt32BE( + CrcStream.crc32(buf.slice(4, buf.length - 4)), + buf.length - 4 + ); + return buf; +}; + +Packer.prototype.packGAMA = function (gamma) { + let buf = Buffer.alloc(4); + buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0); + return this._packChunk(constants.TYPE_gAMA, buf); +}; + +Packer.prototype.packIHDR = function (width, height) { + let buf = Buffer.alloc(13); + buf.writeUInt32BE(width, 0); + buf.writeUInt32BE(height, 4); + buf[8] = this._options.bitDepth; // Bit depth + buf[9] = this._options.colorType; // colorType + buf[10] = 0; // compression + buf[11] = 0; // filter + buf[12] = 0; // interlace + + return this._packChunk(constants.TYPE_IHDR, buf); +}; + +Packer.prototype.packIDAT = function (data) { + return this._packChunk(constants.TYPE_IDAT, data); +}; + +Packer.prototype.packIEND = function () { + return this._packChunk(constants.TYPE_IEND, null); +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/paeth-predictor.js b/node_modules/@jimp/png/node_modules/pngjs/lib/paeth-predictor.js new file mode 100644 index 00000000..9634497d --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/paeth-predictor.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function paethPredictor(left, above, upLeft) { + let paeth = left + above - upLeft; + let pLeft = Math.abs(paeth - left); + let pAbove = Math.abs(paeth - above); + let pUpLeft = Math.abs(paeth - upLeft); + + if (pLeft <= pAbove && pLeft <= pUpLeft) { + return left; + } + if (pAbove <= pUpLeft) { + return above; + } + return upLeft; +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/parser-async.js b/node_modules/@jimp/png/node_modules/pngjs/lib/parser-async.js new file mode 100644 index 00000000..1aacde34 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/parser-async.js @@ -0,0 +1,169 @@ +"use strict"; + +let util = require("util"); +let zlib = require("zlib"); +let ChunkStream = require("./chunkstream"); +let FilterAsync = require("./filter-parse-async"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +let ParserAsync = (module.exports = function (options) { + ChunkStream.call(this); + + this._parser = new Parser(options, { + read: this.read.bind(this), + error: this._handleError.bind(this), + metadata: this._handleMetaData.bind(this), + gamma: this.emit.bind(this, "gamma"), + palette: this._handlePalette.bind(this), + transColor: this._handleTransColor.bind(this), + finished: this._finished.bind(this), + inflateData: this._inflateData.bind(this), + simpleTransparency: this._simpleTransparency.bind(this), + headersFinished: this._headersFinished.bind(this), + }); + this._options = options; + this.writable = true; + + this._parser.start(); +}); +util.inherits(ParserAsync, ChunkStream); + +ParserAsync.prototype._handleError = function (err) { + this.emit("error", err); + + this.writable = false; + + this.destroy(); + + if (this._inflate && this._inflate.destroy) { + this._inflate.destroy(); + } + + if (this._filter) { + this._filter.destroy(); + // For backward compatibility with Node 7 and below. + // Suppress errors due to _inflate calling write() even after + // it's destroy()'ed. + this._filter.on("error", function () {}); + } + + this.errord = true; +}; + +ParserAsync.prototype._inflateData = function (data) { + if (!this._inflate) { + if (this._bitmapInfo.interlace) { + this._inflate = zlib.createInflate(); + + this._inflate.on("error", this.emit.bind(this, "error")); + this._filter.on("complete", this._complete.bind(this)); + + this._inflate.pipe(this._filter); + } else { + let rowSize = + ((this._bitmapInfo.width * + this._bitmapInfo.bpp * + this._bitmapInfo.depth + + 7) >> + 3) + + 1; + let imageSize = rowSize * this._bitmapInfo.height; + let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); + + this._inflate = zlib.createInflate({ chunkSize: chunkSize }); + let leftToInflate = imageSize; + + let emitError = this.emit.bind(this, "error"); + this._inflate.on("error", function (err) { + if (!leftToInflate) { + return; + } + + emitError(err); + }); + this._filter.on("complete", this._complete.bind(this)); + + let filterWrite = this._filter.write.bind(this._filter); + this._inflate.on("data", function (chunk) { + if (!leftToInflate) { + return; + } + + if (chunk.length > leftToInflate) { + chunk = chunk.slice(0, leftToInflate); + } + + leftToInflate -= chunk.length; + + filterWrite(chunk); + }); + + this._inflate.on("end", this._filter.end.bind(this._filter)); + } + } + this._inflate.write(data); +}; + +ParserAsync.prototype._handleMetaData = function (metaData) { + this._metaData = metaData; + this._bitmapInfo = Object.create(metaData); + + this._filter = new FilterAsync(this._bitmapInfo); +}; + +ParserAsync.prototype._handleTransColor = function (transColor) { + this._bitmapInfo.transColor = transColor; +}; + +ParserAsync.prototype._handlePalette = function (palette) { + this._bitmapInfo.palette = palette; +}; + +ParserAsync.prototype._simpleTransparency = function () { + this._metaData.alpha = true; +}; + +ParserAsync.prototype._headersFinished = function () { + // Up until this point, we don't know if we have a tRNS chunk (alpha) + // so we can't emit metadata any earlier + this.emit("metadata", this._metaData); +}; + +ParserAsync.prototype._finished = function () { + if (this.errord) { + return; + } + + if (!this._inflate) { + this.emit("error", "No Inflate block"); + } else { + // no more data to inflate + this._inflate.end(); + } +}; + +ParserAsync.prototype._complete = function (filteredData) { + if (this.errord) { + return; + } + + let normalisedBitmapData; + + try { + let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); + + normalisedBitmapData = formatNormaliser( + bitmapData, + this._bitmapInfo, + this._options.skipRescale + ); + bitmapData = null; + } catch (ex) { + this._handleError(ex); + return; + } + + this.emit("parsed", normalisedBitmapData); +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/parser-sync.js b/node_modules/@jimp/png/node_modules/pngjs/lib/parser-sync.js new file mode 100644 index 00000000..76cb134b --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/parser-sync.js @@ -0,0 +1,112 @@ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +let inflateSync = require("./sync-inflate"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let SyncReader = require("./sync-reader"); +let FilterSync = require("./filter-parse-sync"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +module.exports = function (buffer, options) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let err; + function handleError(_err_) { + err = _err_; + } + + let metaData; + function handleMetaData(_metaData_) { + metaData = _metaData_; + } + + function handleTransColor(transColor) { + metaData.transColor = transColor; + } + + function handlePalette(palette) { + metaData.palette = palette; + } + + function handleSimpleTransparency() { + metaData.alpha = true; + } + + let gamma; + function handleGamma(_gamma_) { + gamma = _gamma_; + } + + let inflateDataList = []; + function handleInflateData(inflatedData) { + inflateDataList.push(inflatedData); + } + + let reader = new SyncReader(buffer); + + let parser = new Parser(options, { + read: reader.read.bind(reader), + error: handleError, + metadata: handleMetaData, + gamma: handleGamma, + palette: handlePalette, + transColor: handleTransColor, + inflateData: handleInflateData, + simpleTransparency: handleSimpleTransparency, + }); + + parser.start(); + reader.process(); + + if (err) { + throw err; + } + + //join together the inflate datas + let inflateData = Buffer.concat(inflateDataList); + inflateDataList.length = 0; + + let inflatedData; + if (metaData.interlace) { + inflatedData = zlib.inflateSync(inflateData); + } else { + let rowSize = + ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1; + let imageSize = rowSize * metaData.height; + inflatedData = inflateSync(inflateData, { + chunkSize: imageSize, + maxLength: imageSize, + }); + } + inflateData = null; + + if (!inflatedData || !inflatedData.length) { + throw new Error("bad png - invalid inflate data response"); + } + + let unfilteredData = FilterSync.process(inflatedData, metaData); + inflateData = null; + + let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); + unfilteredData = null; + + let normalisedBitmapData = formatNormaliser( + bitmapData, + metaData, + options.skipRescale + ); + + metaData.data = normalisedBitmapData; + metaData.gamma = gamma || 0; + + return metaData; +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/parser.js b/node_modules/@jimp/png/node_modules/pngjs/lib/parser.js new file mode 100644 index 00000000..51a8f2a5 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/parser.js @@ -0,0 +1,290 @@ +"use strict"; + +let constants = require("./constants"); +let CrcCalculator = require("./crc"); + +let Parser = (module.exports = function (options, dependencies) { + this._options = options; + options.checkCRC = options.checkCRC !== false; + + this._hasIHDR = false; + this._hasIEND = false; + this._emittedHeadersFinished = false; + + // input flags/metadata + this._palette = []; + this._colorType = 0; + + this._chunks = {}; + this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this); + this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this); + this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this); + this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this); + this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this); + this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this); + + this.read = dependencies.read; + this.error = dependencies.error; + this.metadata = dependencies.metadata; + this.gamma = dependencies.gamma; + this.transColor = dependencies.transColor; + this.palette = dependencies.palette; + this.parsed = dependencies.parsed; + this.inflateData = dependencies.inflateData; + this.finished = dependencies.finished; + this.simpleTransparency = dependencies.simpleTransparency; + this.headersFinished = dependencies.headersFinished || function () {}; +}); + +Parser.prototype.start = function () { + this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this)); +}; + +Parser.prototype._parseSignature = function (data) { + let signature = constants.PNG_SIGNATURE; + + for (let i = 0; i < signature.length; i++) { + if (data[i] !== signature[i]) { + this.error(new Error("Invalid file signature")); + return; + } + } + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._parseChunkBegin = function (data) { + // chunk content length + let length = data.readUInt32BE(0); + + // chunk type + let type = data.readUInt32BE(4); + let name = ""; + for (let i = 4; i < 8; i++) { + name += String.fromCharCode(data[i]); + } + + //console.log('chunk ', name, length); + + // chunk flags + let ancillary = Boolean(data[4] & 0x20); // or critical + // priv = Boolean(data[5] & 0x20), // or public + // safeToCopy = Boolean(data[7] & 0x20); // or unsafe + + if (!this._hasIHDR && type !== constants.TYPE_IHDR) { + this.error(new Error("Expected IHDR on beggining")); + return; + } + + this._crc = new CrcCalculator(); + this._crc.write(Buffer.from(name)); + + if (this._chunks[type]) { + return this._chunks[type](length); + } + + if (!ancillary) { + this.error(new Error("Unsupported critical chunk type " + name)); + return; + } + + this.read(length + 4, this._skipChunk.bind(this)); +}; + +Parser.prototype._skipChunk = function (/*data*/) { + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._handleChunkEnd = function () { + this.read(4, this._parseChunkEnd.bind(this)); +}; + +Parser.prototype._parseChunkEnd = function (data) { + let fileCrc = data.readInt32BE(0); + let calcCrc = this._crc.crc32(); + + // check CRC + if (this._options.checkCRC && calcCrc !== fileCrc) { + this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc)); + return; + } + + if (!this._hasIEND) { + this.read(8, this._parseChunkBegin.bind(this)); + } +}; + +Parser.prototype._handleIHDR = function (length) { + this.read(length, this._parseIHDR.bind(this)); +}; +Parser.prototype._parseIHDR = function (data) { + this._crc.write(data); + + let width = data.readUInt32BE(0); + let height = data.readUInt32BE(4); + let depth = data[8]; + let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha + let compr = data[10]; + let filter = data[11]; + let interlace = data[12]; + + // console.log(' width', width, 'height', height, + // 'depth', depth, 'colorType', colorType, + // 'compr', compr, 'filter', filter, 'interlace', interlace + // ); + + if ( + depth !== 8 && + depth !== 4 && + depth !== 2 && + depth !== 1 && + depth !== 16 + ) { + this.error(new Error("Unsupported bit depth " + depth)); + return; + } + if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) { + this.error(new Error("Unsupported color type")); + return; + } + if (compr !== 0) { + this.error(new Error("Unsupported compression method")); + return; + } + if (filter !== 0) { + this.error(new Error("Unsupported filter method")); + return; + } + if (interlace !== 0 && interlace !== 1) { + this.error(new Error("Unsupported interlace method")); + return; + } + + this._colorType = colorType; + + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; + + this._hasIHDR = true; + + this.metadata({ + width: width, + height: height, + depth: depth, + interlace: Boolean(interlace), + palette: Boolean(colorType & constants.COLORTYPE_PALETTE), + color: Boolean(colorType & constants.COLORTYPE_COLOR), + alpha: Boolean(colorType & constants.COLORTYPE_ALPHA), + bpp: bpp, + colorType: colorType, + }); + + this._handleChunkEnd(); +}; + +Parser.prototype._handlePLTE = function (length) { + this.read(length, this._parsePLTE.bind(this)); +}; +Parser.prototype._parsePLTE = function (data) { + this._crc.write(data); + + let entries = Math.floor(data.length / 3); + // console.log('Palette:', entries); + + for (let i = 0; i < entries; i++) { + this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]); + } + + this.palette(this._palette); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleTRNS = function (length) { + this.simpleTransparency(); + this.read(length, this._parseTRNS.bind(this)); +}; +Parser.prototype._parseTRNS = function (data) { + this._crc.write(data); + + // palette + if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) { + if (this._palette.length === 0) { + this.error(new Error("Transparency chunk must be after palette")); + return; + } + if (data.length > this._palette.length) { + this.error(new Error("More transparent colors than palette size")); + return; + } + for (let i = 0; i < data.length; i++) { + this._palette[i][3] = data[i]; + } + this.palette(this._palette); + } + + // for colorType 0 (grayscale) and 2 (rgb) + // there might be one gray/color defined as transparent + if (this._colorType === constants.COLORTYPE_GRAYSCALE) { + // grey, 2 bytes + this.transColor([data.readUInt16BE(0)]); + } + if (this._colorType === constants.COLORTYPE_COLOR) { + this.transColor([ + data.readUInt16BE(0), + data.readUInt16BE(2), + data.readUInt16BE(4), + ]); + } + + this._handleChunkEnd(); +}; + +Parser.prototype._handleGAMA = function (length) { + this.read(length, this._parseGAMA.bind(this)); +}; +Parser.prototype._parseGAMA = function (data) { + this._crc.write(data); + this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleIDAT = function (length) { + if (!this._emittedHeadersFinished) { + this._emittedHeadersFinished = true; + this.headersFinished(); + } + this.read(-length, this._parseIDAT.bind(this, length)); +}; +Parser.prototype._parseIDAT = function (length, data) { + this._crc.write(data); + + if ( + this._colorType === constants.COLORTYPE_PALETTE_COLOR && + this._palette.length === 0 + ) { + throw new Error("Expected palette not found"); + } + + this.inflateData(data); + let leftOverLength = length - data.length; + + if (leftOverLength > 0) { + this._handleIDAT(leftOverLength); + } else { + this._handleChunkEnd(); + } +}; + +Parser.prototype._handleIEND = function (length) { + this.read(length, this._parseIEND.bind(this)); +}; +Parser.prototype._parseIEND = function (data) { + this._crc.write(data); + + this._hasIEND = true; + this._handleChunkEnd(); + + if (this.finished) { + this.finished(); + } +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/png-sync.js b/node_modules/@jimp/png/node_modules/pngjs/lib/png-sync.js new file mode 100644 index 00000000..68cac9bc --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/png-sync.js @@ -0,0 +1,12 @@ +"use strict"; + +let parse = require("./parser-sync"); +let pack = require("./packer-sync"); + +exports.read = function (buffer, options) { + return parse(buffer, options || {}); +}; + +exports.write = function (png, options) { + return pack(png, options); +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/png.js b/node_modules/@jimp/png/node_modules/pngjs/lib/png.js new file mode 100644 index 00000000..0b8af3f7 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/png.js @@ -0,0 +1,194 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let Parser = require("./parser-async"); +let Packer = require("./packer-async"); +let PNGSync = require("./png-sync"); + +let PNG = (exports.PNG = function (options) { + Stream.call(this); + + options = options || {}; // eslint-disable-line no-param-reassign + + // coerce pixel dimensions to integers (also coerces undefined -> 0): + this.width = options.width | 0; + this.height = options.height | 0; + + this.data = + this.width > 0 && this.height > 0 + ? Buffer.alloc(4 * this.width * this.height) + : null; + + if (options.fill && this.data) { + this.data.fill(0); + } + + this.gamma = 0; + this.readable = this.writable = true; + + this._parser = new Parser(options); + + this._parser.on("error", this.emit.bind(this, "error")); + this._parser.on("close", this._handleClose.bind(this)); + this._parser.on("metadata", this._metadata.bind(this)); + this._parser.on("gamma", this._gamma.bind(this)); + this._parser.on( + "parsed", + function (data) { + this.data = data; + this.emit("parsed", data); + }.bind(this) + ); + + this._packer = new Packer(options); + this._packer.on("data", this.emit.bind(this, "data")); + this._packer.on("end", this.emit.bind(this, "end")); + this._parser.on("close", this._handleClose.bind(this)); + this._packer.on("error", this.emit.bind(this, "error")); +}); +util.inherits(PNG, Stream); + +PNG.sync = PNGSync; + +PNG.prototype.pack = function () { + if (!this.data || !this.data.length) { + this.emit("error", "No data provided"); + return this; + } + + process.nextTick( + function () { + this._packer.pack(this.data, this.width, this.height, this.gamma); + }.bind(this) + ); + + return this; +}; + +PNG.prototype.parse = function (data, callback) { + if (callback) { + let onParsed, onError; + + onParsed = function (parsedData) { + this.removeListener("error", onError); + + this.data = parsedData; + callback(null, this); + }.bind(this); + + onError = function (err) { + this.removeListener("parsed", onParsed); + + callback(err, null); + }.bind(this); + + this.once("parsed", onParsed); + this.once("error", onError); + } + + this.end(data); + return this; +}; + +PNG.prototype.write = function (data) { + this._parser.write(data); + return true; +}; + +PNG.prototype.end = function (data) { + this._parser.end(data); +}; + +PNG.prototype._metadata = function (metadata) { + this.width = metadata.width; + this.height = metadata.height; + + this.emit("metadata", metadata); +}; + +PNG.prototype._gamma = function (gamma) { + this.gamma = gamma; +}; + +PNG.prototype._handleClose = function () { + if (!this._parser.writable && !this._packer.readable) { + this.emit("close"); + } +}; + +PNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) { + // eslint-disable-line max-params + // coerce pixel dimensions to integers (also coerces undefined -> 0): + /* eslint-disable no-param-reassign */ + srcX |= 0; + srcY |= 0; + width |= 0; + height |= 0; + deltaX |= 0; + deltaY |= 0; + /* eslint-enable no-param-reassign */ + + if ( + srcX > src.width || + srcY > src.height || + srcX + width > src.width || + srcY + height > src.height + ) { + throw new Error("bitblt reading outside image"); + } + + if ( + deltaX > dst.width || + deltaY > dst.height || + deltaX + width > dst.width || + deltaY + height > dst.height + ) { + throw new Error("bitblt writing outside image"); + } + + for (let y = 0; y < height; y++) { + src.data.copy( + dst.data, + ((deltaY + y) * dst.width + deltaX) << 2, + ((srcY + y) * src.width + srcX) << 2, + ((srcY + y) * src.width + srcX + width) << 2 + ); + } +}; + +PNG.prototype.bitblt = function ( + dst, + srcX, + srcY, + width, + height, + deltaX, + deltaY +) { + // eslint-disable-line max-params + + PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); + return this; +}; + +PNG.adjustGamma = function (src) { + if (src.gamma) { + for (let y = 0; y < src.height; y++) { + for (let x = 0; x < src.width; x++) { + let idx = (src.width * y + x) << 2; + + for (let i = 0; i < 3; i++) { + let sample = src.data[idx + i] / 255; + sample = Math.pow(sample, 1 / 2.2 / src.gamma); + src.data[idx + i] = Math.round(sample * 255); + } + } + } + src.gamma = 0; + } +}; + +PNG.prototype.adjustGamma = function () { + PNG.adjustGamma(this); +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/sync-inflate.js b/node_modules/@jimp/png/node_modules/pngjs/lib/sync-inflate.js new file mode 100644 index 00000000..4da0d5f0 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/sync-inflate.js @@ -0,0 +1,168 @@ +"use strict"; + +let assert = require("assert").ok; +let zlib = require("zlib"); +let util = require("util"); + +let kMaxLength = require("buffer").kMaxLength; + +function Inflate(opts) { + if (!(this instanceof Inflate)) { + return new Inflate(opts); + } + + if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { + opts.chunkSize = zlib.Z_MIN_CHUNK; + } + + zlib.Inflate.call(this, opts); + + // Node 8 --> 9 compatibility check + this._offset = this._offset === undefined ? this._outOffset : this._offset; + this._buffer = this._buffer || this._outBuffer; + + if (opts && opts.maxLength != null) { + this._maxLength = opts.maxLength; + } +} + +function createInflate(opts) { + return new Inflate(opts); +} + +function _close(engine, callback) { + if (callback) { + process.nextTick(callback); + } + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) { + return; + } + + engine._handle.close(); + engine._handle = null; +} + +Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) { + if (typeof asyncCb === "function") { + return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); + } + + let self = this; + + let availInBefore = chunk && chunk.length; + let availOutBefore = this._chunkSize - this._offset; + let leftToInflate = this._maxLength; + let inOff = 0; + + let buffers = []; + let nread = 0; + + let error; + this.on("error", function (err) { + error = err; + }); + + function handleChunk(availInAfter, availOutAfter) { + if (self._hadError) { + return; + } + + let have = availOutBefore - availOutAfter; + assert(have >= 0, "have should not go down"); + + if (have > 0) { + let out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + + if (out.length > leftToInflate) { + out = out.slice(0, leftToInflate); + } + + buffers.push(out); + nread += out.length; + leftToInflate -= out.length; + + if (leftToInflate === 0) { + return false; + } + } + + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + return true; + } + + return false; + } + + assert(this._handle, "zlib binding closed"); + let res; + do { + res = this._handle.writeSync( + flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore + ); // out_len + // Node 8 --> 9 compatibility check + res = res || this._writeState; + } while (!this._hadError && handleChunk(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError( + "Cannot create final Buffer. It would be larger than 0x" + + kMaxLength.toString(16) + + " bytes" + ); + } + + let buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; +}; + +util.inherits(Inflate, zlib.Inflate); + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === "string") { + buffer = Buffer.from(buffer); + } + if (!(buffer instanceof Buffer)) { + throw new TypeError("Not a string or buffer"); + } + + let flushFlag = engine._finishFlushFlag; + if (flushFlag == null) { + flushFlag = zlib.Z_FINISH; + } + + return engine._processChunk(buffer, flushFlag); +} + +function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +} + +module.exports = exports = inflateSync; +exports.Inflate = Inflate; +exports.createInflate = createInflate; +exports.inflateSync = inflateSync; diff --git a/node_modules/@jimp/png/node_modules/pngjs/lib/sync-reader.js b/node_modules/@jimp/png/node_modules/pngjs/lib/sync-reader.js new file mode 100644 index 00000000..213d1a75 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/lib/sync-reader.js @@ -0,0 +1,45 @@ +"use strict"; + +let SyncReader = (module.exports = function (buffer) { + this._buffer = buffer; + this._reads = []; +}); + +SyncReader.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); +}; + +SyncReader.prototype.process = function () { + // as long as there is any data and read requests + while (this._reads.length > 0 && this._buffer.length) { + let read = this._reads[0]; + + if ( + this._buffer.length && + (this._buffer.length >= read.length || read.allowLess) + ) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + let buf = this._buffer; + + this._buffer = buf.slice(read.length); + + read.func.call(this, buf.slice(0, read.length)); + } else { + break; + } + } + + if (this._reads.length > 0) { + throw new Error("There are some read requests waitng on finished stream"); + } + + if (this._buffer.length > 0) { + throw new Error("unrecognised content at end of stream"); + } +}; diff --git a/node_modules/@jimp/png/node_modules/pngjs/package.json b/node_modules/@jimp/png/node_modules/pngjs/package.json new file mode 100644 index 00000000..c75142e2 --- /dev/null +++ b/node_modules/@jimp/png/node_modules/pngjs/package.json @@ -0,0 +1,77 @@ +{ + "name": "pngjs", + "version": "6.0.0", + "description": "PNG encoder/decoder in pure JS, supporting any bit size & interlace, async & sync with full test suite.", + "contributors": [ + "Alexandre Paré", + "Gaurav Mali", + "Gusts Kaksis", + "Kuba Niegowski", + "Luke Page", + "Pietajan De Potter", + "Steven Sojka", + "liangzeng", + "Michael Vogt", + "Xin-Xin Wang", + "toriningen", + "Eugene Kulabuhov" + ], + "homepage": "https://github.com/lukeapage/pngjs", + "keywords": [ + "PNG", + "decoder", + "encoder", + "js-png", + "node-png", + "parser", + "png", + "png-js", + "png-parse", + "pngjs" + ], + "engines": { + "node": ">=12.13.0" + }, + "main": "./lib/png.js", + "directories": { + "lib": "lib", + "example": "examples", + "test": "test" + }, + "files": [ + "browser.js", + "lib/" + ], + "scripts": { + "build": "yarn prepublish", + "prepublish": "yarn browserify", + "browserify": "browserify lib/png.js --standalone png > browser.js", + "coverage": "nyc --reporter=lcov --reporter=text-summary tape test/*-spec.js nolarge", + "test": "yarn lint && yarn prettier:check && tape test/*-spec.js | tap-dot && node test/run-compare", + "lint": "eslint .", + "prettier:write": "prettier --write .", + "prettier:check": "prettier --check ." + }, + "repository": { + "type": "git", + "url": "git://github.com/lukeapage/pngjs.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/lukeapage/pngjs/issues" + }, + "devDependencies": { + "browserify": "17.0.0", + "buffer-equal": "1.0.0", + "codecov": "3.7.1", + "connect": "3.7.0", + "eslint": "7.8.1", + "eslint-config-prettier": "6.14.0", + "nyc": "15.1.0", + "prettier": "2.1.1", + "puppeteer": "5.4.0", + "serve-static": "1.14.1", + "tap-dot": "2.0.0", + "tape": "5.0.1" + } +} diff --git a/node_modules/@jimp/png/package.json b/node_modules/@jimp/png/package.json new file mode 100644 index 00000000..a5b0e2db --- /dev/null +++ b/node_modules/@jimp/png/package.json @@ -0,0 +1,39 @@ +{ + "name": "@jimp/png", + "version": "0.22.12", + "description": "Default Jimp png encoder/decoder.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/utils": "^0.22.12", + "pngjs": "^6.0.0" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12", + "@types/pngjs": "^6.0.1" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/png/src/index.js b/node_modules/@jimp/png/src/index.js new file mode 100644 index 00000000..2c81c063 --- /dev/null +++ b/node_modules/@jimp/png/src/index.js @@ -0,0 +1,157 @@ +import { PNG } from "pngjs"; +import { throwError, isNodePattern } from "@jimp/utils"; + +const MIME_TYPE = "image/png"; + +// PNG filter types +const PNG_FILTER_AUTO = -1; +const PNG_FILTER_NONE = 0; +const PNG_FILTER_SUB = 1; +const PNG_FILTER_UP = 2; +const PNG_FILTER_AVERAGE = 3; +const PNG_FILTER_PATH = 4; + +export default () => ({ + mime: { [MIME_TYPE]: ["png"] }, + + constants: { + MIME_PNG: MIME_TYPE, + PNG_FILTER_AUTO, + PNG_FILTER_NONE, + PNG_FILTER_SUB, + PNG_FILTER_UP, + PNG_FILTER_AVERAGE, + PNG_FILTER_PATH, + }, + + hasAlpha: { [MIME_TYPE]: true }, + decoders: { [MIME_TYPE]: PNG.sync.read }, + encoders: { + [MIME_TYPE](data) { + const png = new PNG({ + width: data.bitmap.width, + height: data.bitmap.height, + }); + + png.data = data.bitmap.data; + + return PNG.sync.write(png, { + deflateLevel: data._deflateLevel, + deflateStrategy: data._deflateStrategy, + filterType: data._filterType, + colorType: + typeof data._colorType === "number" + ? data._colorType + : data._rgba + ? 6 + : 2, + inputHasAlpha: data._rgba, + }); + }, + }, + + class: { + _deflateLevel: 9, + _deflateStrategy: 3, + _filterType: PNG_FILTER_AUTO, + _colorType: null, + + /** + * Sets the deflate level used when saving as PNG format (default is 9) + * @param {number} l Deflate level to use 0-9. 0 is no compression. 9 (default) is maximum compression. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + deflateLevel(l, cb) { + if (typeof l !== "number") { + return throwError.call(this, "l must be a number", cb); + } + + if (l < 0 || l > 9) { + return throwError.call(this, "l must be a number 0 - 9", cb); + } + + this._deflateLevel = Math.round(l); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Sets the deflate strategy used when saving as PNG format (default is 3) + * @param {number} s Deflate strategy to use 0-3. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + deflateStrategy(s, cb) { + if (typeof s !== "number") { + return throwError.call(this, "s must be a number", cb); + } + + if (s < 0 || s > 3) { + return throwError.call(this, "s must be a number 0 - 3", cb); + } + + this._deflateStrategy = Math.round(s); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Sets the filter type used when saving as PNG format (default is automatic filters) + * @param {number} f The quality to use -1-4. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + filterType(f, cb) { + if (typeof f !== "number") { + return throwError.call(this, "n must be a number", cb); + } + + if (f < -1 || f > 4) { + return throwError.call( + this, + "n must be -1 (auto) or a number 0 - 4", + cb + ); + } + + this._filterType = Math.round(f); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + /** + * Sets the color type used when saving as PNG format + * @param {number} s color type to use 0, 2, 4, 6. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ colorType(s, cb) { + if (typeof s !== "number") { + return throwError.call(this, "s must be a number", cb); + } + + if (s !== 0 && s !== 2 && s !== 4 && s !== 6) { + return throwError.call(this, "s must be a number 0, 2, 4, 6.", cb); + } + + this._colorType = Math.round(s); + + if (isNodePattern(cb)) { + cb.call(this, null, this); + } + + return this; + }, + }, +}); diff --git a/node_modules/@jimp/png/test/images/dice.png b/node_modules/@jimp/png/test/images/dice.png new file mode 100644 index 00000000..b28653fb Binary files /dev/null and b/node_modules/@jimp/png/test/images/dice.png differ diff --git a/node_modules/@jimp/png/test/images/options.png b/node_modules/@jimp/png/test/images/options.png new file mode 100644 index 00000000..5358c02a Binary files /dev/null and b/node_modules/@jimp/png/test/images/options.png differ diff --git a/node_modules/@jimp/png/test/png.test.js b/node_modules/@jimp/png/test/png.test.js new file mode 100644 index 00000000..ff10457c --- /dev/null +++ b/node_modules/@jimp/png/test/png.test.js @@ -0,0 +1,61 @@ +import { Jimp, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import expect from "@storybook/expect"; + +import png from "../src"; + +const jimp = configure({ types: [png] }, Jimp); + +describe("PNG", () => { + const imagesDir = getTestDir(__dirname) + "/images"; + + it("load PNG", async () => { + const image = await jimp.read(imagesDir + "/dice.png"); + + expect(image.getPixelColor(10, 10)).toBe(0x00000000); + expect(image.getPixelColor(160, 80)).toBe(0x1c1cd4ff); + expect(image.getPixelColor(400, 250)).toBe(0x7e0c0cda); + }); + + it("export PNG", async () => { + const jgd = await jimp.read({ + width: 3, + height: 3, + data: [ + 0xff0000ff, 0xff0080ff, 0xff00ffff, 0xff0080ff, 0xff00ffff, 0x8000ffff, + 0xff00ffff, 0x8000ffff, 0x0000ffff, + ], + }); + const buffer = await jgd.getBufferAsync("image/png"); + + expect(buffer.toString()).toMatch(/^.PNG\r\n/); + }); + + it("should use png options", async () => { + const jgd = await jimp.read({ + width: 20, + height: 20, + data: [ + 0xff0000ff, 0xff0080ff, 0xff00ffff, 0xff0080ff, 0xff00ffff, 0x8000ffff, + 0xff00ffff, 0x8000ffff, 0x0000ffff, 0xff0000ff, 0xff0080ff, 0xff00ffff, + 0xff0080ff, 0xff00ffff, 0x8000ffff, 0xff00ffff, 0x8000ffff, 0x0000ffff, + 0xff0000ff, 0xff0080ff, 0xff00ffff, 0xff0080ff, 0xff00ffff, 0x8000ffff, + 0xff00ffff, 0x8000ffff, 0x0000ffff, 0xff0000ff, 0xff0080ff, 0xff00ffff, + 0xff0080ff, 0xff00ffff, 0x8000ffff, 0xff00ffff, 0x8000ffff, 0x0000ffff, + ], + }); + + const image = await jgd + .deflateStrategy(0) + .colorType(0) + .getBufferAsync(Jimp.MIME_PNG); + + const expected = await jimp.read(imagesDir + "/options.png"); + const expectedBuffer = await expected + .deflateStrategy(0) + .colorType(0) + .getBufferAsync(Jimp.MIME_PNG); + + expect(image).toEqual(expectedBuffer); + }); +}); diff --git a/node_modules/@jimp/tiff/CHANGELOG.md b/node_modules/@jimp/tiff/CHANGELOG.md new file mode 100644 index 00000000..dce8da69 --- /dev/null +++ b/node_modules/@jimp/tiff/CHANGELOG.md @@ -0,0 +1,97 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.22.0 (Mon Feb 06 2023) + +#### 🏠 Internal + +- switch from should to expect [#1163](https://github.com/jimp-dev/jimp/pull/1163) ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Change test matching strategy to include all test files [#1161](https://github.com/jimp-dev/jimp/pull/1161) ([@danielholmes](https://github.com/danielholmes)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Daniel Holmes ([@danielholmes](https://github.com/danielholmes)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.18.0 (Sun Feb 05 2023) + +#### 🚀 Enhancement + +- Update utif [#1143](https://github.com/jimp-dev/jimp/pull/1143) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/tiff/LICENSE b/node_modules/@jimp/tiff/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/tiff/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/tiff/README.md b/node_modules/@jimp/tiff/README.md new file mode 100644 index 00000000..3f3a92d7 --- /dev/null +++ b/node_modules/@jimp/tiff/README.md @@ -0,0 +1,6 @@ +
+ +

@jimp/tiff

+

Default Jimp tiff encoder/decoder.

+
diff --git a/node_modules/@jimp/tiff/es/index.js b/node_modules/@jimp/tiff/es/index.js new file mode 100644 index 00000000..03159084 --- /dev/null +++ b/node_modules/@jimp/tiff/es/index.js @@ -0,0 +1,32 @@ +import utif from "utif2"; +const MIME_TYPE = "image/tiff"; +export default (() => ({ + mime: { + [MIME_TYPE]: ["tiff", "tif"] + }, + constants: { + MIME_TIFF: MIME_TYPE + }, + decoders: { + [MIME_TYPE]: data => { + const ifds = utif.decode(data); + const page = ifds[0]; + ifds.forEach(ifd => { + utif.decodeImage(data, ifd); + }); + const rgba = utif.toRGBA8(page); + return { + data: Buffer.from(rgba), + width: page.t256[0], + height: page.t257[0] + }; + } + }, + encoders: { + [MIME_TYPE]: image => { + const tiff = utif.encodeImage(image.bitmap.data, image.bitmap.width, image.bitmap.height); + return Buffer.from(tiff); + } + } +})); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/tiff/es/index.js.map b/node_modules/@jimp/tiff/es/index.js.map new file mode 100644 index 00000000..21755188 --- /dev/null +++ b/node_modules/@jimp/tiff/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["utif","MIME_TYPE","mime","constants","MIME_TIFF","decoders","data","ifds","decode","page","forEach","ifd","decodeImage","rgba","toRGBA8","Buffer","from","width","t256","height","t257","encoders","image","tiff","encodeImage","bitmap"],"sources":["../src/index.js"],"sourcesContent":["import utif from \"utif2\";\n\nconst MIME_TYPE = \"image/tiff\";\n\nexport default () => ({\n mime: { [MIME_TYPE]: [\"tiff\", \"tif\"] },\n\n constants: {\n MIME_TIFF: MIME_TYPE,\n },\n\n decoders: {\n [MIME_TYPE]: (data) => {\n const ifds = utif.decode(data);\n const page = ifds[0];\n\n ifds.forEach((ifd) => {\n utif.decodeImage(data, ifd);\n });\n\n const rgba = utif.toRGBA8(page);\n\n return {\n data: Buffer.from(rgba),\n width: page.t256[0],\n height: page.t257[0],\n };\n },\n },\n\n encoders: {\n [MIME_TYPE]: (image) => {\n const tiff = utif.encodeImage(\n image.bitmap.data,\n image.bitmap.width,\n image.bitmap.height\n );\n\n return Buffer.from(tiff);\n },\n },\n});\n"],"mappings":"AAAA,OAAOA,IAAI,MAAM,OAAO;AAExB,MAAMC,SAAS,GAAG,YAAY;AAE9B,gBAAe,OAAO;EACpBC,IAAI,EAAE;IAAE,CAACD,SAAS,GAAG,CAAC,MAAM,EAAE,KAAK;EAAE,CAAC;EAEtCE,SAAS,EAAE;IACTC,SAAS,EAAEH;EACb,CAAC;EAEDI,QAAQ,EAAE;IACR,CAACJ,SAAS,GAAIK,IAAI,IAAK;MACrB,MAAMC,IAAI,GAAGP,IAAI,CAACQ,MAAM,CAACF,IAAI,CAAC;MAC9B,MAAMG,IAAI,GAAGF,IAAI,CAAC,CAAC,CAAC;MAEpBA,IAAI,CAACG,OAAO,CAAEC,GAAG,IAAK;QACpBX,IAAI,CAACY,WAAW,CAACN,IAAI,EAAEK,GAAG,CAAC;MAC7B,CAAC,CAAC;MAEF,MAAME,IAAI,GAAGb,IAAI,CAACc,OAAO,CAACL,IAAI,CAAC;MAE/B,OAAO;QACLH,IAAI,EAAES,MAAM,CAACC,IAAI,CAACH,IAAI,CAAC;QACvBI,KAAK,EAAER,IAAI,CAACS,IAAI,CAAC,CAAC,CAAC;QACnBC,MAAM,EAAEV,IAAI,CAACW,IAAI,CAAC,CAAC;MACrB,CAAC;IACH;EACF,CAAC;EAEDC,QAAQ,EAAE;IACR,CAACpB,SAAS,GAAIqB,KAAK,IAAK;MACtB,MAAMC,IAAI,GAAGvB,IAAI,CAACwB,WAAW,CAC3BF,KAAK,CAACG,MAAM,CAACnB,IAAI,EACjBgB,KAAK,CAACG,MAAM,CAACR,KAAK,EAClBK,KAAK,CAACG,MAAM,CAACN,MAAM,CACpB;MAED,OAAOJ,MAAM,CAACC,IAAI,CAACO,IAAI,CAAC;IAC1B;EACF;AACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/tiff/index.d.ts b/node_modules/@jimp/tiff/index.d.ts new file mode 100644 index 00000000..851d7383 --- /dev/null +++ b/node_modules/@jimp/tiff/index.d.ts @@ -0,0 +1,16 @@ +import { DecoderFn, EncoderFn } from "@jimp/core"; + +interface Tiff { + mime: { "image/tiff": string[] }; + decoders: { + "image/tiff": DecoderFn; + }; + encoders: { + "image/tiff": EncoderFn; + }; + constants: { + MIME_TIFF: "image/tiff"; + }; +} + +export default function (): Tiff; diff --git a/node_modules/@jimp/tiff/package.json b/node_modules/@jimp/tiff/package.json new file mode 100644 index 00000000..ef219133 --- /dev/null +++ b/node_modules/@jimp/tiff/package.json @@ -0,0 +1,37 @@ +{ + "name": "@jimp/tiff", + "version": "0.22.12", + "description": "Default Jimp tiff encoder/decoder.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "utif2": "^4.0.1" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/test-utils": "^0.22.12" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/tiff/src/index.js b/node_modules/@jimp/tiff/src/index.js new file mode 100644 index 00000000..7942ae72 --- /dev/null +++ b/node_modules/@jimp/tiff/src/index.js @@ -0,0 +1,42 @@ +import utif from "utif2"; + +const MIME_TYPE = "image/tiff"; + +export default () => ({ + mime: { [MIME_TYPE]: ["tiff", "tif"] }, + + constants: { + MIME_TIFF: MIME_TYPE, + }, + + decoders: { + [MIME_TYPE]: (data) => { + const ifds = utif.decode(data); + const page = ifds[0]; + + ifds.forEach((ifd) => { + utif.decodeImage(data, ifd); + }); + + const rgba = utif.toRGBA8(page); + + return { + data: Buffer.from(rgba), + width: page.t256[0], + height: page.t257[0], + }; + }, + }, + + encoders: { + [MIME_TYPE]: (image) => { + const tiff = utif.encodeImage( + image.bitmap.data, + image.bitmap.width, + image.bitmap.height + ); + + return Buffer.from(tiff); + }, + }, +}); diff --git a/node_modules/@jimp/tiff/test/images/rgb.tiff b/node_modules/@jimp/tiff/test/images/rgb.tiff new file mode 100644 index 00000000..b795bcdc Binary files /dev/null and b/node_modules/@jimp/tiff/test/images/rgb.tiff differ diff --git a/node_modules/@jimp/tiff/test/tiff.test.js b/node_modules/@jimp/tiff/test/tiff.test.js new file mode 100644 index 00000000..be1e98f0 --- /dev/null +++ b/node_modules/@jimp/tiff/test/tiff.test.js @@ -0,0 +1,35 @@ +import { Jimp, getTestDir } from "@jimp/test-utils"; +import configure from "@jimp/custom"; +import expect from "@storybook/expect"; + +import tiff from "../src"; + +const jimp = configure({ types: [tiff] }, Jimp); + +describe("TIFF", () => { + const imagesDir = getTestDir(__dirname) + "/images"; + + it("load TIFF", async () => { + const image = await jimp.read(imagesDir + "/rgb.tiff"); + + expect(image.getPixelColor(10, 10)).toBe(0xa4988bff); + expect(image.getPixelColor(220, 190)).toBe(0xe0d7ddff); + expect(image.getPixelColor(350, 130)).toBe(0x565433ff); + }); + + const simpleJGD = { + width: 3, + height: 3, + data: [ + 0xff0000ff, 0xff0080ff, 0xff00ffff, 0xff0080ff, 0xff00ffff, 0x8000ffff, + 0xff00ffff, 0x8000ffff, 0x0000ffff, + ], + }; + + it("export TIFF", async () => { + const image = await jimp.read(simpleJGD); + const buffer = await image.getBufferAsync("image/tiff"); + + expect(buffer.toString()).toMatch(/^MM\u0000*\u0000/); + }); +}); diff --git a/node_modules/@jimp/types/CHANGELOG.md b/node_modules/@jimp/types/CHANGELOG.md new file mode 100644 index 00000000..8d029143 --- /dev/null +++ b/node_modules/@jimp/types/CHANGELOG.md @@ -0,0 +1,71 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- `@jimp/cli`, `@jimp/core`, `@jimp/custom`, `jimp`, `@jimp/plugin-blit`, `@jimp/plugin-blur`, `@jimp/plugin-circle`, `@jimp/plugin-color`, `@jimp/plugin-contain`, `@jimp/plugin-cover`, `@jimp/plugin-crop`, `@jimp/plugin-displace`, `@jimp/plugin-dither`, `@jimp/plugin-fisheye`, `@jimp/plugin-flip`, `@jimp/plugin-gaussian`, `@jimp/plugin-invert`, `@jimp/plugin-mask`, `@jimp/plugin-normalize`, `@jimp/plugin-print`, `@jimp/plugin-resize`, `@jimp/plugin-rotate`, `@jimp/plugin-scale`, `@jimp/plugin-shadow`, `@jimp/plugin-threshold`, `@jimp/plugins`, `@jimp/test-utils`, `@jimp/bmp`, `@jimp/gif`, `@jimp/jpeg`, `@jimp/png`, `@jimp/tiff`, `@jimp/types`, `@jimp/utils` + - Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/types/LICENSE b/node_modules/@jimp/types/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/types/README.md b/node_modules/@jimp/types/README.md new file mode 100644 index 00000000..60dc4199 --- /dev/null +++ b/node_modules/@jimp/types/README.md @@ -0,0 +1,14 @@ +
+ +

@jimp/types

+

Default Jimp types.

+
+ +## Supported Image Types + +- [bmp](../type-bmp) +- [gif](../type-gif) +- [jpeg](../type-jpeg) +- [png](../type-png) +- [tiff](../type-tiff) diff --git a/node_modules/@jimp/types/es/index.js b/node_modules/@jimp/types/es/index.js new file mode 100644 index 00000000..0c66bcbf --- /dev/null +++ b/node_modules/@jimp/types/es/index.js @@ -0,0 +1,8 @@ +import { mergeDeep } from "timm"; +import jpeg from "@jimp/jpeg"; +import png from "@jimp/png"; +import bmp from "@jimp/bmp"; +import tiff from "@jimp/tiff"; +import gif from "@jimp/gif"; +export default (() => mergeDeep(jpeg(), png(), bmp(), tiff(), gif())); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/types/es/index.js.map b/node_modules/@jimp/types/es/index.js.map new file mode 100644 index 00000000..c6cbaed2 --- /dev/null +++ b/node_modules/@jimp/types/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["mergeDeep","jpeg","png","bmp","tiff","gif"],"sources":["../src/index.js"],"sourcesContent":["import { mergeDeep } from \"timm\";\n\nimport jpeg from \"@jimp/jpeg\";\nimport png from \"@jimp/png\";\nimport bmp from \"@jimp/bmp\";\nimport tiff from \"@jimp/tiff\";\nimport gif from \"@jimp/gif\";\n\nexport default () => mergeDeep(jpeg(), png(), bmp(), tiff(), gif());\n"],"mappings":"AAAA,SAASA,SAAS,QAAQ,MAAM;AAEhC,OAAOC,IAAI,MAAM,YAAY;AAC7B,OAAOC,GAAG,MAAM,WAAW;AAC3B,OAAOC,GAAG,MAAM,WAAW;AAC3B,OAAOC,IAAI,MAAM,YAAY;AAC7B,OAAOC,GAAG,MAAM,WAAW;AAE3B,gBAAe,MAAML,SAAS,CAACC,IAAI,EAAE,EAAEC,GAAG,EAAE,EAAEC,GAAG,EAAE,EAAEC,IAAI,EAAE,EAAEC,GAAG,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@jimp/types/index.d.ts b/node_modules/@jimp/types/index.d.ts new file mode 100644 index 00000000..98f0cceb --- /dev/null +++ b/node_modules/@jimp/types/index.d.ts @@ -0,0 +1,23 @@ +import jpeg from "@jimp/jpeg"; +import png from "@jimp/png"; +import bmp from "@jimp/bmp"; +import tiff from "@jimp/tiff"; +import gif from "@jimp/gif"; + +type JpegRet = ReturnType; +type PngRet = ReturnType; +type BmpRet = ReturnType; +type TiffRet = ReturnType; +type GifRet = ReturnType; + +/** + * This is made union and not intersection to avoid issues with + * `IllformedPlugin` and `WellFormedPlugin` when using typings with Jimp + * generic + * + * In reality, this should be an intersection but our type data isn't + * clever enough to figure out what's a class and what's not/etc + */ +type Types = JpegRet | PngRet | BmpRet | TiffRet | GifRet; + +export default function (): Types; diff --git a/node_modules/@jimp/types/package.json b/node_modules/@jimp/types/package.json new file mode 100644 index 00000000..7042428f --- /dev/null +++ b/node_modules/@jimp/types/package.json @@ -0,0 +1,38 @@ +{ + "name": "@jimp/types", + "version": "0.22.12", + "description": "Default Jimp encoder/decoders.", + "main": "dist/index.js", + "module": "es/index.js", + "repository": "jimp-dev/jimp", + "types": "index.d.ts", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@jimp/bmp": "^0.22.12", + "@jimp/gif": "^0.22.12", + "@jimp/jpeg": "^0.22.12", + "@jimp/png": "^0.22.12", + "@jimp/tiff": "^0.22.12", + "timm": "^1.6.1" + }, + "peerDependencies": { + "@jimp/custom": ">=0.3.5" + }, + "devDependencies": { + "@types/node": "^12.7.5" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/types/src/index.js b/node_modules/@jimp/types/src/index.js new file mode 100644 index 00000000..1f6eb528 --- /dev/null +++ b/node_modules/@jimp/types/src/index.js @@ -0,0 +1,9 @@ +import { mergeDeep } from "timm"; + +import jpeg from "@jimp/jpeg"; +import png from "@jimp/png"; +import bmp from "@jimp/bmp"; +import tiff from "@jimp/tiff"; +import gif from "@jimp/gif"; + +export default () => mergeDeep(jpeg(), png(), bmp(), tiff(), gif()); diff --git a/node_modules/@jimp/utils/CHANGELOG.md b/node_modules/@jimp/utils/CHANGELOG.md new file mode 100644 index 00000000..8aae0bbe --- /dev/null +++ b/node_modules/@jimp/utils/CHANGELOG.md @@ -0,0 +1,82 @@ +# v0.22.1 (Mon Feb 06 2023) + +#### 🏠 Internal + +- rename master to main [#1169](https://github.com/jimp-dev/jimp/pull/1169) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.21.0 (Sun Feb 05 2023) + +### Release Notes + +#### Babel Refactor ([#1149](https://github.com/jimp-dev/jimp/pull/1149)) + +Marking this as a "breaking release" because it might change what deps need to be installed. + +All modules should be exported as valid cjs and esm + +![CleanShot 2023-02-04 at 18 19 27](https://user-images.githubusercontent.com/1192452/216798157-664cc430-7846-432d-84cf-26e8d8ba9e10.png) + +--- + +#### 💥 Breaking Change + +- Babel Refactor [#1149](https://github.com/jimp-dev/jimp/pull/1149) ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.16.3 (Sat Feb 04 2023) + +#### ⚠️ Pushed to `main` + +- upgrade prettier ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 1 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) + +--- + +# v0.11.0 (Fri May 15 2020) + +#### 🚀 Enhancement + +- Removed Core-JS as a dependency. [#882](https://github.com/oliver-moran/jimp/pull/882) ([@EricRabil](https://github.com/EricRabil)) + +#### Authors: 1 + +- Eric Rabil ([@EricRabil](https://github.com/EricRabil)) + +--- + +# v0.10.1 (Sun Apr 05 2020) + +#### 🐛 Bug Fix + +- Update package.json [#870](https://github.com/oliver-moran/jimp/pull/870) ([@arcanis](https://github.com/arcanis)) + +#### Authors: 1 + +- Maël Nison ([@arcanis](https://github.com/arcanis)) + +--- + +# v0.9.3 (Tue Nov 26 2019) + +#### 🐛 Bug Fix + +- Fix regeneratorRuntime errors [#815](https://github.com/oliver-moran/jimp/pull/815) ([@crutchcorn](https://github.com/crutchcorn) [@hipstersmoothie](https://github.com/hipstersmoothie)) + +#### Authors: 2 + +- Andrew Lisowski ([@hipstersmoothie](https://github.com/hipstersmoothie)) +- Corbin Crutchley ([@crutchcorn](https://github.com/crutchcorn)) diff --git a/node_modules/@jimp/utils/LICENSE b/node_modules/@jimp/utils/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/@jimp/utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jimp/utils/README.md b/node_modules/@jimp/utils/README.md new file mode 100644 index 00000000..51a52c4d --- /dev/null +++ b/node_modules/@jimp/utils/README.md @@ -0,0 +1,70 @@ +
+ +

@jimp/utils

+

Utils for jimp extensions.

+
+ +## Available Methods + +### isNodePattern + +Determines if function was passed an node callback. + +```js +if (isNodePattern(cb)) { + cb.call(this, null, this); +} +``` + +### throwError + +Either throws the error or calls the callback with the error. + +```js +if (/* check for error */) { + return throwError.call(this, 'someError', cb); +} +``` + +### scan + +Scans through a region of the bitmap, calling a function for each pixel. + +```js +function removeRed(image) { + return scan( + image, + 0, + 0, + image.bitmap.width, + image.bitmap.height, + function (x, y, index) { + const red = this.bitmap.data[index + 0]; + const green = this.bitmap.data[index + 1]; + const blue = this.bitmap.data[index + 2]; + const alpha = this.bitmap.data[index + 3]; + + this.bitmap.data[index + 0] = 0; + this.bitmap.data[index + 1] = green; + this.bitmap.data[index + 2] = blue; + this.bitmap.data[index + 3] = alpha; + } + ); +} +``` + +### scanIterator + +It's possible to make an iterator scan with a `for ... of`, if you want to `break` the scan before it reaches the end, but note, that this iterator has a huge performance implication: + +```js +for (const { x, y, idx, image } of scanIterator( + image, + 0, + 0, + image.bitmap.width, + image.bitmap.height +)) { +} +``` diff --git a/node_modules/@jimp/utils/es/index.js b/node_modules/@jimp/utils/es/index.js new file mode 100644 index 00000000..00a127b1 --- /dev/null +++ b/node_modules/@jimp/utils/es/index.js @@ -0,0 +1,51 @@ +export function isNodePattern(cb) { + if (typeof cb === "undefined") { + return false; + } + if (typeof cb !== "function") { + throw new TypeError("Callback must be a function"); + } + return true; +} +export function throwError(error, cb) { + if (typeof error === "string") { + error = new Error(error); + } + if (typeof cb === "function") { + return cb.call(this, error); + } + throw error; +} +export function scan(image, x, y, w, h, f) { + // round input + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + for (let _y = y; _y < y + h; _y++) { + for (let _x = x; _x < x + w; _x++) { + const idx = image.bitmap.width * _y + _x << 2; + f.call(image, _x, _y, idx); + } + } + return image; +} +export function* scanIterator(image, x, y, w, h) { + // round input + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + for (let _y = y; _y < y + h; _y++) { + for (let _x = x; _x < x + w; _x++) { + const idx = image.bitmap.width * _y + _x << 2; + yield { + x: _x, + y: _y, + idx, + image + }; + } + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@jimp/utils/es/index.js.map b/node_modules/@jimp/utils/es/index.js.map new file mode 100644 index 00000000..dc3d73c3 --- /dev/null +++ b/node_modules/@jimp/utils/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["isNodePattern","cb","TypeError","throwError","error","Error","call","scan","image","x","y","w","h","f","Math","round","_y","_x","idx","bitmap","width","scanIterator"],"sources":["../src/index.js"],"sourcesContent":["export function isNodePattern(cb) {\n if (typeof cb === \"undefined\") {\n return false;\n }\n\n if (typeof cb !== \"function\") {\n throw new TypeError(\"Callback must be a function\");\n }\n\n return true;\n}\n\nexport function throwError(error, cb) {\n if (typeof error === \"string\") {\n error = new Error(error);\n }\n\n if (typeof cb === \"function\") {\n return cb.call(this, error);\n }\n\n throw error;\n}\n\nexport function scan(image, x, y, w, h, f) {\n // round input\n x = Math.round(x);\n y = Math.round(y);\n w = Math.round(w);\n h = Math.round(h);\n\n for (let _y = y; _y < y + h; _y++) {\n for (let _x = x; _x < x + w; _x++) {\n const idx = (image.bitmap.width * _y + _x) << 2;\n f.call(image, _x, _y, idx);\n }\n }\n\n return image;\n}\n\nexport function* scanIterator(image, x, y, w, h) {\n // round input\n x = Math.round(x);\n y = Math.round(y);\n w = Math.round(w);\n h = Math.round(h);\n\n for (let _y = y; _y < y + h; _y++) {\n for (let _x = x; _x < x + w; _x++) {\n const idx = (image.bitmap.width * _y + _x) << 2;\n yield { x: _x, y: _y, idx, image };\n }\n }\n}\n"],"mappings":"AAAA,OAAO,SAASA,aAAa,CAACC,EAAE,EAAE;EAChC,IAAI,OAAOA,EAAE,KAAK,WAAW,EAAE;IAC7B,OAAO,KAAK;EACd;EAEA,IAAI,OAAOA,EAAE,KAAK,UAAU,EAAE;IAC5B,MAAM,IAAIC,SAAS,CAAC,6BAA6B,CAAC;EACpD;EAEA,OAAO,IAAI;AACb;AAEA,OAAO,SAASC,UAAU,CAACC,KAAK,EAAEH,EAAE,EAAE;EACpC,IAAI,OAAOG,KAAK,KAAK,QAAQ,EAAE;IAC7BA,KAAK,GAAG,IAAIC,KAAK,CAACD,KAAK,CAAC;EAC1B;EAEA,IAAI,OAAOH,EAAE,KAAK,UAAU,EAAE;IAC5B,OAAOA,EAAE,CAACK,IAAI,CAAC,IAAI,EAAEF,KAAK,CAAC;EAC7B;EAEA,MAAMA,KAAK;AACb;AAEA,OAAO,SAASG,IAAI,CAACC,KAAK,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAE;EACzC;EACAJ,CAAC,GAAGK,IAAI,CAACC,KAAK,CAACN,CAAC,CAAC;EACjBC,CAAC,GAAGI,IAAI,CAACC,KAAK,CAACL,CAAC,CAAC;EACjB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;QAAEE,GAAG;QAAEV;MAAM,CAAC;IACpC;EACF;AACF"} \ No newline at end of file diff --git a/node_modules/@jimp/utils/index.d.ts b/node_modules/@jimp/utils/index.d.ts new file mode 100644 index 00000000..612e9fce --- /dev/null +++ b/node_modules/@jimp/utils/index.d.ts @@ -0,0 +1,19 @@ +import { Image, Omit } from "@jimp/core"; +import { ThrowStatement } from "typescript"; + +export function isNodePattern(cb: Function): true; +export function isNodePattern(cb: Omit): false; + +export function throwError( + error: string | Error, + cb?: (err: Error) => void +): ThrowStatement; + +export function scan( + image: Image, + x: number, + y: number, + w: number, + h: number, + f: (image: Image, _x: number, _y: number, idx: number) => void +): Image; diff --git a/node_modules/@jimp/utils/package.json b/node_modules/@jimp/utils/package.json new file mode 100644 index 00000000..018d2d7c --- /dev/null +++ b/node_modules/@jimp/utils/package.json @@ -0,0 +1,27 @@ +{ + "name": "@jimp/utils", + "version": "0.22.12", + "description": "Utils for jimp extensions.", + "main": "dist/index.js", + "module": "es/index.js", + "types": "index.d.ts", + "repository": "jimp-dev/jimp", + "scripts": { + "build": "npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node" + }, + "author": "", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "dependencies": { + "regenerator-runtime": "^0.13.3" + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/@jimp/utils/src/index.js b/node_modules/@jimp/utils/src/index.js new file mode 100644 index 00000000..723f2114 --- /dev/null +++ b/node_modules/@jimp/utils/src/index.js @@ -0,0 +1,55 @@ +export function isNodePattern(cb) { + if (typeof cb === "undefined") { + return false; + } + + if (typeof cb !== "function") { + throw new TypeError("Callback must be a function"); + } + + return true; +} + +export function throwError(error, cb) { + if (typeof error === "string") { + error = new Error(error); + } + + if (typeof cb === "function") { + return cb.call(this, error); + } + + throw error; +} + +export function scan(image, x, y, w, h, f) { + // round input + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + + for (let _y = y; _y < y + h; _y++) { + for (let _x = x; _x < x + w; _x++) { + const idx = (image.bitmap.width * _y + _x) << 2; + f.call(image, _x, _y, idx); + } + } + + return image; +} + +export function* scanIterator(image, x, y, w, h) { + // round input + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + + for (let _y = y; _y < y + h; _y++) { + for (let _x = x; _x < x + w; _x++) { + const idx = (image.bitmap.width * _y + _x) << 2; + yield { x: _x, y: _y, idx, image }; + } + } +} diff --git a/node_modules/@tokenizer/token/README.md b/node_modules/@tokenizer/token/README.md new file mode 100644 index 00000000..1c1ba324 --- /dev/null +++ b/node_modules/@tokenizer/token/README.md @@ -0,0 +1,19 @@ +[![npm version](https://badge.fury.io/js/%40tokenizer%2Ftoken.svg)](https://www.npmjs.com/package/@tokenizer/token) +[![npm downloads](http://img.shields.io/npm/dm/@tokenizer/token.svg)](https://npmcharts.com/compare/@tokenizer/token?interval=30) + +# @tokenizer/token + +TypeScript definition of an [strtok3](https://github.com/Borewit/strtok3) token. + +## Licence + +(The MIT License) + +Copyright (c) 2020 Borewit + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/@tokenizer/token/index.d.ts b/node_modules/@tokenizer/token/index.d.ts new file mode 100644 index 00000000..d6c8122e --- /dev/null +++ b/node_modules/@tokenizer/token/index.d.ts @@ -0,0 +1,30 @@ +/** + * Read-only token + * See https://github.com/Borewit/strtok3 for more information + */ +export interface IGetToken { + + /** + * Length of encoded token in bytes + */ + len: number; + + /** + * Decode value from buffer at offset + * @param array - Uint8Array to read the decoded value from + * @param offset - Decode offset + * @return decoded value + */ + get(array: Array, offset: number): Value; +} + +export interface IToken extends IGetToken { + /** + * Encode value to buffer + * @param array - Uint8Array to write the encoded value to + * @param offset - Buffer write offset + * @param value - Value to decode of type T + * @return offset plus number of bytes written + */ + put(array: Array, offset: number, value: Value): number +} diff --git a/node_modules/@tokenizer/token/package.json b/node_modules/@tokenizer/token/package.json new file mode 100644 index 00000000..ad87e5bb --- /dev/null +++ b/node_modules/@tokenizer/token/package.json @@ -0,0 +1,33 @@ +{ + "name": "@tokenizer/token", + "version": "0.3.0", + "description": "TypeScript definition for strtok3 token", + "main": "", + "types": "index.d.ts", + "files": [ + "index.d.ts" + ], + "keywords": [ + "token", + "interface", + "tokenizer", + "TypeScript" + ], + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/Borewit/tokenizer-token.git" + }, + "bugs": { + "url": "https://github.com/Borewit/tokenizer-token/issues" + }, + "typeScriptVersion": "3.0", + "dependencies": {}, + "devDependencies": { + "@types/node": "^13.1.0" + } +} diff --git a/node_modules/any-base/LICENSE b/node_modules/any-base/LICENSE new file mode 100644 index 00000000..a70ce0ce --- /dev/null +++ b/node_modules/any-base/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Kamil Harasimowicz and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/any-base/README.md b/node_modules/any-base/README.md new file mode 100644 index 00000000..98887d74 --- /dev/null +++ b/node_modules/any-base/README.md @@ -0,0 +1,55 @@ +# README # + +The library allows you to convert any large numbers in any number base to another number base. The base is determined by specifying the alphabet. So is full freedom + +[![NPM](https://nodei.co/npm/any-base.png?downloads=true&stars=true)](https://nodei.co/npm/any-base/) + +## Installation ## + +``` +npm install any-base --save +``` + +## API ## + +### AnyBase() ### + +``` +converterFunction = anyBase(sourceAlphabet, destinationAlphabet); +``` + +#### Parameters #### + +* {String} __sourceAlphabet__ digits from smallest to the largest +* {String} __destinationAlphabet__ digits from smallest to the largest + +#### Return Values #### + +Returns __function__ that converts the number of source base to the destination + +### Convert() ### + +``` +converterFunction(number) +``` + +#### Parameters #### + +* {String} __number__ number of source base + +#### Return Values #### + +Returns number of destonation base + +## Example ## + +```js +var anyBase = require('any-base'), +dec2hex = anyBase(anyBase.DEC, anyBase.HEX), +shortId = anyBase(anyBase.DEC, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-+!@#$^'), +longId = anyBase('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-+!@#$^', anyBase.DEC); + +dec2hex('123456'); // return: '1E240' +shortId('1234567890'); // return: 'PtmIa' +longId('PtmIa'); // return: '1234567890' +``` diff --git a/node_modules/any-base/index.js b/node_modules/any-base/index.js new file mode 100644 index 00000000..17c6694b --- /dev/null +++ b/node_modules/any-base/index.js @@ -0,0 +1,30 @@ +var Converter = require('./src/converter'); + +/** + * Function get source and destination alphabet and return convert function + * + * @param {string|Array} srcAlphabet + * @param {string|Array} dstAlphabet + * + * @returns {function(number|Array)} + */ +function anyBase(srcAlphabet, dstAlphabet) { + var converter = new Converter(srcAlphabet, dstAlphabet); + /** + * Convert function + * + * @param {string|Array} number + * + * @return {string|Array} number + */ + return function (number) { + return converter.convert(number); + } +}; + +anyBase.BIN = '01'; +anyBase.OCT = '01234567'; +anyBase.DEC = '0123456789'; +anyBase.HEX = '0123456789abcdef'; + +module.exports = anyBase; \ No newline at end of file diff --git a/node_modules/any-base/package.json b/node_modules/any-base/package.json new file mode 100644 index 00000000..1ca20b0a --- /dev/null +++ b/node_modules/any-base/package.json @@ -0,0 +1,40 @@ +{ + "name": "any-base", + "version": "1.1.0", + "description": "Converter from any base to other any base", + "main": "index.js", + "scripts": { + "start": "./node_modules/.bin/watchify . -s AnyBase -o dist/any-base.js -v -d", + "build": "./node_modules/.bin/browserify . -s AnyBase | ./node_modules/.bin/uglifyjs -cm > dist/any-base.min.js", + "test": "node tests/test.js" + }, + "keywords": [ + "number", + "convert", + "base", + "alphabet", + "short number", + "long numbers", + "dec", + "hex", + "bin", + "oct", + "any" + ], + "repository": { + "type": "git", + "url": "https://github.com/HarasimowiczKamil/any-base.git" + }, + "author": { + "name": "Kamil Harasimowicz", + "email": "mifczu@gmail.com" + }, + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "browserify": "^13.1.1", + "punycode": "^2.1.0", + "uglify-js": "^2.7.4", + "watchify": "^3.7.0" + } +} diff --git a/node_modules/any-base/src/converter.js b/node_modules/any-base/src/converter.js new file mode 100644 index 00000000..b2b07f3f --- /dev/null +++ b/node_modules/any-base/src/converter.js @@ -0,0 +1,80 @@ +'use strict'; + +/** + * Converter + * + * @param {string|Array} srcAlphabet + * @param {string|Array} dstAlphabet + * @constructor + */ +function Converter(srcAlphabet, dstAlphabet) { + if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) { + throw new Error('Bad alphabet'); + } + this.srcAlphabet = srcAlphabet; + this.dstAlphabet = dstAlphabet; +} + +/** + * Convert number from source alphabet to destination alphabet + * + * @param {string|Array} number - number represented as a string or array of points + * + * @returns {string|Array} + */ +Converter.prototype.convert = function(number) { + var i, divide, newlen, + numberMap = {}, + fromBase = this.srcAlphabet.length, + toBase = this.dstAlphabet.length, + length = number.length, + result = typeof number === 'string' ? '' : []; + + if (!this.isValid(number)) { + throw new Error('Number "' + number + '" contains of non-alphabetic digits (' + this.srcAlphabet + ')'); + } + + if (this.srcAlphabet === this.dstAlphabet) { + return number; + } + + for (i = 0; i < length; i++) { + numberMap[i] = this.srcAlphabet.indexOf(number[i]); + } + do { + divide = 0; + newlen = 0; + for (i = 0; i < length; i++) { + divide = divide * fromBase + numberMap[i]; + if (divide >= toBase) { + numberMap[newlen++] = parseInt(divide / toBase, 10); + divide = divide % toBase; + } else if (newlen > 0) { + numberMap[newlen++] = 0; + } + } + length = newlen; + result = this.dstAlphabet.slice(divide, divide + 1).concat(result); + } while (newlen !== 0); + + return result; +}; + +/** + * Valid number with source alphabet + * + * @param {number} number + * + * @returns {boolean} + */ +Converter.prototype.isValid = function(number) { + var i = 0; + for (; i < number.length; ++i) { + if (this.srcAlphabet.indexOf(number[i]) === -1) { + return false; + } + } + return true; +}; + +module.exports = Converter; \ No newline at end of file diff --git a/node_modules/bmp-js/.npmignore b/node_modules/bmp-js/.npmignore new file mode 100644 index 00000000..34977ee7 --- /dev/null +++ b/node_modules/bmp-js/.npmignore @@ -0,0 +1,2 @@ +node_modules +.idea \ No newline at end of file diff --git a/node_modules/bmp-js/LICENSE b/node_modules/bmp-js/LICENSE new file mode 100644 index 00000000..4b20aeff --- /dev/null +++ b/node_modules/bmp-js/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 @丝刀口 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/bmp-js/README.md b/node_modules/bmp-js/README.md new file mode 100644 index 00000000..d5fa52b7 --- /dev/null +++ b/node_modules/bmp-js/README.md @@ -0,0 +1,44 @@ +bmp-js +====== + +A pure javascript Bmp encoder and decoder for node.js + +Supports all bits decoding(1,4,8,16,24,32) and encoding with 24bit. + +##Install + + $ npm install bmp-js + + +How to use? +--- +###Decode BMP +```js +var bmp = require("bmp-js"); +var bmpBuffer = fs.readFileSync('bit24.bmp'); +var bmpData = bmp.decode(bmpBuffer); + +``` + +`bmpData` has all properties includes: + +1. fileSize,reserved,offset + +2. headerSize,width,height,planes,bitPP,compress,rawSize,hr,vr,colors,importantColors + +3. palette + +4. data-------byte array order by ABGR ABGR ABGR,4 bytes per pixel + + +###Encode RGB +```js +var bmp = require("bmp-js"); +//bmpData={data:Buffer,width:Number,height:Height} +var rawData = bmp.encode(bmpData);//default no compression,write rawData to .bmp file + +``` + +License +--- +U can use on free with [MIT License](https://github.com/shaozilee/bmp-js/blob/master/LICENSE) \ No newline at end of file diff --git a/node_modules/bmp-js/bmp-js.iml b/node_modules/bmp-js/bmp-js.iml new file mode 100644 index 00000000..8021953e --- /dev/null +++ b/node_modules/bmp-js/bmp-js.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/node_modules/bmp-js/index.js b/node_modules/bmp-js/index.js new file mode 100644 index 00000000..dbb578c3 --- /dev/null +++ b/node_modules/bmp-js/index.js @@ -0,0 +1,15 @@ +/** + * @author shaozilee + * + * support 1bit 4bit 8bit 24bit decode + * encode with 24bit + * + */ + +var encode = require('./lib/encoder'), + decode = require('./lib/decoder'); + +module.exports = { + encode: encode, + decode: decode +}; diff --git a/node_modules/bmp-js/lib/decoder.js b/node_modules/bmp-js/lib/decoder.js new file mode 100644 index 00000000..b66d1812 --- /dev/null +++ b/node_modules/bmp-js/lib/decoder.js @@ -0,0 +1,485 @@ +/** + * @author shaozilee + * + * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp + * + */ + +function BmpDecoder(buffer,is_with_alpha) { + this.pos = 0; + this.buffer = buffer; + this.is_with_alpha = !!is_with_alpha; + this.bottom_up = true; + this.flag = this.buffer.toString("utf-8", 0, this.pos += 2); + if (this.flag != "BM") throw new Error("Invalid BMP File"); + this.parseHeader(); + this.parseRGBA(); +} + +BmpDecoder.prototype.parseHeader = function() { + this.fileSize = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.reserved = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.offset = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.headerSize = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.width = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.height = this.buffer.readInt32LE(this.pos); + this.pos += 4; + this.planes = this.buffer.readUInt16LE(this.pos); + this.pos += 2; + this.bitPP = this.buffer.readUInt16LE(this.pos); + this.pos += 2; + this.compress = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.rawSize = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.hr = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.vr = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.colors = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.importantColors = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + + if(this.bitPP === 16 && this.is_with_alpha){ + this.bitPP = 15 + } + if (this.bitPP < 15) { + var len = this.colors === 0 ? 1 << this.bitPP : this.colors; + this.palette = new Array(len); + for (var i = 0; i < len; i++) { + var blue = this.buffer.readUInt8(this.pos++); + var green = this.buffer.readUInt8(this.pos++); + var red = this.buffer.readUInt8(this.pos++); + var quad = this.buffer.readUInt8(this.pos++); + this.palette[i] = { + red: red, + green: green, + blue: blue, + quad: quad + }; + } + } + if(this.height < 0) { + this.height *= -1; + this.bottom_up = false; + } + +} + +BmpDecoder.prototype.parseRGBA = function() { + var bitn = "bit" + this.bitPP; + var len = this.width * this.height * 4; + this.data = new Buffer(len); + this[bitn](); +}; + +BmpDecoder.prototype.bit1 = function() { + var xlen = Math.ceil(this.width / 8); + var mode = xlen%4; + var y = this.height >= 0 ? this.height - 1 : -this.height + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < xlen; x++) { + var b = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x*8*4; + for (var i = 0; i < 8; i++) { + if(x*8+i>(7-i))&0x1)]; + + this.data[location+i*4] = 0; + this.data[location+i*4 + 1] = rgb.blue; + this.data[location+i*4 + 2] = rgb.green; + this.data[location+i*4 + 3] = rgb.red; + + }else{ + break; + } + } + } + + if (mode != 0){ + this.pos+=(4 - mode); + } + } +}; + +BmpDecoder.prototype.bit4 = function() { + //RLE-4 + if(this.compress == 2){ + this.data.fill(0xff); + + var location = 0; + var lines = this.bottom_up?this.height-1:0; + var low_nibble = false;//for all count of pixel + + while(location>4); + } + + if ((i & 1) && (i+1 < b)){ + c = this.buffer.readUInt8(this.pos++); + } + + low_nibble = !low_nibble; + } + + if ((((b+1) >> 1) & 1 ) == 1){ + this.pos++ + } + } + + }else{//encoded mode + for (var i = 0; i < a; i++) { + if (low_nibble) { + setPixelData.call(this, (b & 0x0f)); + } else { + setPixelData.call(this, (b & 0xf0)>>4); + } + low_nibble = !low_nibble; + } + } + + } + + + + + function setPixelData(rgbIndex){ + var rgb = this.palette[rgbIndex]; + this.data[location] = 0; + this.data[location + 1] = rgb.blue; + this.data[location + 2] = rgb.green; + this.data[location + 3] = rgb.red; + location+=4; + } + }else{ + + var xlen = Math.ceil(this.width/2); + var mode = xlen%4; + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < xlen; x++) { + var b = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x*2*4; + + var before = b>>4; + var after = b&0x0F; + + var rgb = this.palette[before]; + this.data[location] = 0; + this.data[location + 1] = rgb.blue; + this.data[location + 2] = rgb.green; + this.data[location + 3] = rgb.red; + + + if(x*2+1>=this.width)break; + + rgb = this.palette[after]; + + this.data[location+4] = 0; + this.data[location+4 + 1] = rgb.blue; + this.data[location+4 + 2] = rgb.green; + this.data[location+4 + 3] = rgb.red; + + } + + if (mode != 0){ + this.pos+=(4 - mode); + } + } + + } + +}; + +BmpDecoder.prototype.bit8 = function() { + //RLE-8 + if(this.compress == 1){ + this.data.fill(0xff); + + var location = 0; + var lines = this.bottom_up?this.height-1:0; + + while(location= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < this.width; x++) { + var b = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x * 4; + if (b < this.palette.length) { + var rgb = this.palette[b]; + + this.data[location] = 0; + this.data[location + 1] = rgb.blue; + this.data[location + 2] = rgb.green; + this.data[location + 3] = rgb.red; + + } else { + this.data[location] = 0; + this.data[location + 1] = 0xFF; + this.data[location + 2] = 0xFF; + this.data[location + 3] = 0xFF; + } + } + if (mode != 0) { + this.pos += (4 - mode); + } + } + } +}; + +BmpDecoder.prototype.bit15 = function() { + var dif_w =this.width % 3; + var _11111 = parseInt("11111", 2),_1_5 = _11111; + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < this.width; x++) { + + var B = this.buffer.readUInt16LE(this.pos); + this.pos+=2; + var blue = (B & _1_5) / _1_5 * 255 | 0; + var green = (B >> 5 & _1_5 ) / _1_5 * 255 | 0; + var red = (B >> 10 & _1_5) / _1_5 * 255 | 0; + var alpha = (B>>15)?0xFF:0x00; + + var location = line * this.width * 4 + x * 4; + + this.data[location] = alpha; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + //skip extra bytes + this.pos += dif_w; + } +}; + +BmpDecoder.prototype.bit16 = function() { + var dif_w =(this.width % 2)*2; + //default xrgb555 + this.maskRed = 0x7C00; + this.maskGreen = 0x3E0; + this.maskBlue =0x1F; + this.mask0 = 0; + + if(this.compress == 3){ + this.maskRed = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.maskGreen = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.maskBlue = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.mask0 = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + } + + + var ns=[0,0,0]; + for (var i=0;i<16;i++){ + if ((this.maskRed>>i)&0x01) ns[0]++; + if ((this.maskGreen>>i)&0x01) ns[1]++; + if ((this.maskBlue>>i)&0x01) ns[2]++; + } + ns[1]+=ns[0]; ns[2]+=ns[1]; ns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8; + + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y; + for (var x = 0; x < this.width; x++) { + + var B = this.buffer.readUInt16LE(this.pos); + this.pos+=2; + + var blue = (B&this.maskBlue)<>ns[1]; + var red = (B&this.maskRed)>>ns[2]; + + var location = line * this.width * 4 + x * 4; + + this.data[location] = 0; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + //skip extra bytes + this.pos += dif_w; + } +}; + +BmpDecoder.prototype.bit24 = function() { + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < this.width; x++) { + //Little Endian rgb + var blue = this.buffer.readUInt8(this.pos++); + var green = this.buffer.readUInt8(this.pos++); + var red = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x * 4; + this.data[location] = 0; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + //skip extra bytes + this.pos += (this.width % 4); + } + +}; + +/** + * add 32bit decode func + * @author soubok + */ +BmpDecoder.prototype.bit32 = function() { + //BI_BITFIELDS + if(this.compress == 3){ + this.maskRed = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.maskGreen = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.maskBlue = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.mask0 = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y; + for (var x = 0; x < this.width; x++) { + //Little Endian rgba + var alpha = this.buffer.readUInt8(this.pos++); + var blue = this.buffer.readUInt8(this.pos++); + var green = this.buffer.readUInt8(this.pos++); + var red = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x * 4; + this.data[location] = alpha; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + } + + }else{ + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y; + for (var x = 0; x < this.width; x++) { + //Little Endian argb + var blue = this.buffer.readUInt8(this.pos++); + var green = this.buffer.readUInt8(this.pos++); + var red = this.buffer.readUInt8(this.pos++); + var alpha = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x * 4; + this.data[location] = alpha; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + } + + } + + + + +}; + +BmpDecoder.prototype.getData = function() { + return this.data; +}; + +module.exports = function(bmpData) { + var decoder = new BmpDecoder(bmpData); + return decoder; +}; diff --git a/node_modules/bmp-js/lib/encoder.js b/node_modules/bmp-js/lib/encoder.js new file mode 100644 index 00000000..ddb3ef6b --- /dev/null +++ b/node_modules/bmp-js/lib/encoder.js @@ -0,0 +1,81 @@ +/** + * @author shaozilee + * + * BMP format encoder,encode 24bit BMP + * Not support quality compression + * + */ + +function BmpEncoder(imgData){ + this.buffer = imgData.data; + this.width = imgData.width; + this.height = imgData.height; + this.extraBytes = this.width%4; + this.rgbSize = this.height*(3*this.width+this.extraBytes); + this.headerInfoSize = 40; + + this.data = []; + /******************header***********************/ + this.flag = "BM"; + this.reserved = 0; + this.offset = 54; + this.fileSize = this.rgbSize+this.offset; + this.planes = 1; + this.bitPP = 24; + this.compress = 0; + this.hr = 0; + this.vr = 0; + this.colors = 0; + this.importantColors = 0; +} + +BmpEncoder.prototype.encode = function() { + var tempBuffer = new Buffer(this.offset+this.rgbSize); + this.pos = 0; + tempBuffer.write(this.flag,this.pos,2);this.pos+=2; + tempBuffer.writeUInt32LE(this.fileSize,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.reserved,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.offset,this.pos);this.pos+=4; + + tempBuffer.writeUInt32LE(this.headerInfoSize,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.width,this.pos);this.pos+=4; + tempBuffer.writeInt32LE(-this.height,this.pos);this.pos+=4; + tempBuffer.writeUInt16LE(this.planes,this.pos);this.pos+=2; + tempBuffer.writeUInt16LE(this.bitPP,this.pos);this.pos+=2; + tempBuffer.writeUInt32LE(this.compress,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.rgbSize,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.hr,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.vr,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.colors,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.importantColors,this.pos);this.pos+=4; + + var i=0; + var rowBytes = 3*this.width+this.extraBytes; + + for (var y = 0; y 0){ + var fillOffset = this.pos+y*rowBytes+this.width*3; + tempBuffer.fill(0,fillOffset,fillOffset+this.extraBytes); + } + } + + return tempBuffer; +}; + +module.exports = function(imgData, quality) { + if (typeof quality === 'undefined') quality = 100; + var encoder = new BmpEncoder(imgData); + var data = encoder.encode(); + return { + data: data, + width: imgData.width, + height: imgData.height + }; +}; diff --git a/node_modules/bmp-js/package.json b/node_modules/bmp-js/package.json new file mode 100644 index 00000000..befbcb7e --- /dev/null +++ b/node_modules/bmp-js/package.json @@ -0,0 +1,32 @@ +{ + "name": "bmp-js", + "version": "0.1.0", + "description": "A pure javascript BMP encoder and decoder", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/shaozilee/bmp-js" + }, + "keywords": [ + "bmp", + "1bit", + "4bit", + "8bit", + "16bit", + "24bit", + "32bit", + "encoder", + "decoder", + "image", + "javascript", + "js" + ], + "author": { + "name": "shaozilee", + "email": "shaozilee@gmail.com" + }, + "license": "MIT", + "dependencies": {}, + "devDependencies": { + } +} diff --git a/node_modules/bmp-js/test/bit1.bmp b/node_modules/bmp-js/test/bit1.bmp new file mode 100644 index 00000000..c33b94d9 Binary files /dev/null and b/node_modules/bmp-js/test/bit1.bmp differ diff --git a/node_modules/bmp-js/test/bit16_565.bmp b/node_modules/bmp-js/test/bit16_565.bmp new file mode 100644 index 00000000..f111172f Binary files /dev/null and b/node_modules/bmp-js/test/bit16_565.bmp differ diff --git a/node_modules/bmp-js/test/bit16_565_out.bmp b/node_modules/bmp-js/test/bit16_565_out.bmp new file mode 100644 index 00000000..a618d6ff Binary files /dev/null and b/node_modules/bmp-js/test/bit16_565_out.bmp differ diff --git a/node_modules/bmp-js/test/bit16_a444.bmp b/node_modules/bmp-js/test/bit16_a444.bmp new file mode 100644 index 00000000..7eabc666 Binary files /dev/null and b/node_modules/bmp-js/test/bit16_a444.bmp differ diff --git a/node_modules/bmp-js/test/bit16_a444_out.bmp b/node_modules/bmp-js/test/bit16_a444_out.bmp new file mode 100644 index 00000000..413b8180 Binary files /dev/null and b/node_modules/bmp-js/test/bit16_a444_out.bmp differ diff --git a/node_modules/bmp-js/test/bit16_a555.bmp b/node_modules/bmp-js/test/bit16_a555.bmp new file mode 100644 index 00000000..8f28347b Binary files /dev/null and b/node_modules/bmp-js/test/bit16_a555.bmp differ diff --git a/node_modules/bmp-js/test/bit16_a555_out.bmp b/node_modules/bmp-js/test/bit16_a555_out.bmp new file mode 100644 index 00000000..64352869 Binary files /dev/null and b/node_modules/bmp-js/test/bit16_a555_out.bmp differ diff --git a/node_modules/bmp-js/test/bit16_x444.bmp b/node_modules/bmp-js/test/bit16_x444.bmp new file mode 100644 index 00000000..3afabae2 Binary files /dev/null and b/node_modules/bmp-js/test/bit16_x444.bmp differ diff --git a/node_modules/bmp-js/test/bit16_x444_out.bmp b/node_modules/bmp-js/test/bit16_x444_out.bmp new file mode 100644 index 00000000..413b8180 Binary files /dev/null and b/node_modules/bmp-js/test/bit16_x444_out.bmp differ diff --git a/node_modules/bmp-js/test/bit16_x555.bmp b/node_modules/bmp-js/test/bit16_x555.bmp new file mode 100644 index 00000000..077122ed Binary files /dev/null and b/node_modules/bmp-js/test/bit16_x555.bmp differ diff --git a/node_modules/bmp-js/test/bit16_x555_out.bmp b/node_modules/bmp-js/test/bit16_x555_out.bmp new file mode 100644 index 00000000..64352869 Binary files /dev/null and b/node_modules/bmp-js/test/bit16_x555_out.bmp differ diff --git a/node_modules/bmp-js/test/bit1_out.bmp b/node_modules/bmp-js/test/bit1_out.bmp new file mode 100644 index 00000000..830c3796 Binary files /dev/null and b/node_modules/bmp-js/test/bit1_out.bmp differ diff --git a/node_modules/bmp-js/test/bit24.bmp b/node_modules/bmp-js/test/bit24.bmp new file mode 100644 index 00000000..9dcaba91 Binary files /dev/null and b/node_modules/bmp-js/test/bit24.bmp differ diff --git a/node_modules/bmp-js/test/bit24_out.bmp b/node_modules/bmp-js/test/bit24_out.bmp new file mode 100644 index 00000000..3a9aa823 Binary files /dev/null and b/node_modules/bmp-js/test/bit24_out.bmp differ diff --git a/node_modules/bmp-js/test/bit32.bmp b/node_modules/bmp-js/test/bit32.bmp new file mode 100644 index 00000000..411a1769 Binary files /dev/null and b/node_modules/bmp-js/test/bit32.bmp differ diff --git a/node_modules/bmp-js/test/bit32_alpha.bmp b/node_modules/bmp-js/test/bit32_alpha.bmp new file mode 100644 index 00000000..57acdbe3 Binary files /dev/null and b/node_modules/bmp-js/test/bit32_alpha.bmp differ diff --git a/node_modules/bmp-js/test/bit32_alpha_out.bmp b/node_modules/bmp-js/test/bit32_alpha_out.bmp new file mode 100644 index 00000000..3a9aa823 Binary files /dev/null and b/node_modules/bmp-js/test/bit32_alpha_out.bmp differ diff --git a/node_modules/bmp-js/test/bit32_out.bmp b/node_modules/bmp-js/test/bit32_out.bmp new file mode 100644 index 00000000..3a9aa823 Binary files /dev/null and b/node_modules/bmp-js/test/bit32_out.bmp differ diff --git a/node_modules/bmp-js/test/bit4.bmp b/node_modules/bmp-js/test/bit4.bmp new file mode 100644 index 00000000..665349b2 Binary files /dev/null and b/node_modules/bmp-js/test/bit4.bmp differ diff --git a/node_modules/bmp-js/test/bit4_RLE.bmp b/node_modules/bmp-js/test/bit4_RLE.bmp new file mode 100644 index 00000000..faf74b55 Binary files /dev/null and b/node_modules/bmp-js/test/bit4_RLE.bmp differ diff --git a/node_modules/bmp-js/test/bit4_RLE_out.bmp b/node_modules/bmp-js/test/bit4_RLE_out.bmp new file mode 100644 index 00000000..839e830a Binary files /dev/null and b/node_modules/bmp-js/test/bit4_RLE_out.bmp differ diff --git a/node_modules/bmp-js/test/bit4_out.bmp b/node_modules/bmp-js/test/bit4_out.bmp new file mode 100644 index 00000000..51987206 Binary files /dev/null and b/node_modules/bmp-js/test/bit4_out.bmp differ diff --git a/node_modules/bmp-js/test/bit8.bmp b/node_modules/bmp-js/test/bit8.bmp new file mode 100644 index 00000000..9d7c7061 Binary files /dev/null and b/node_modules/bmp-js/test/bit8.bmp differ diff --git a/node_modules/bmp-js/test/bit8_RLE.bmp b/node_modules/bmp-js/test/bit8_RLE.bmp new file mode 100644 index 00000000..e959d984 Binary files /dev/null and b/node_modules/bmp-js/test/bit8_RLE.bmp differ diff --git a/node_modules/bmp-js/test/bit8_RLE_out.bmp b/node_modules/bmp-js/test/bit8_RLE_out.bmp new file mode 100644 index 00000000..0ce584bd Binary files /dev/null and b/node_modules/bmp-js/test/bit8_RLE_out.bmp differ diff --git a/node_modules/bmp-js/test/bit8_out.bmp b/node_modules/bmp-js/test/bit8_out.bmp new file mode 100644 index 00000000..6ffcb1d3 Binary files /dev/null and b/node_modules/bmp-js/test/bit8_out.bmp differ diff --git a/node_modules/bmp-js/test/test.js b/node_modules/bmp-js/test/test.js new file mode 100644 index 00000000..239a7777 --- /dev/null +++ b/node_modules/bmp-js/test/test.js @@ -0,0 +1,33 @@ +var fs = require("fs"); + +var coder = require("../index.js"); +var bmps = ["./bit1", "./bit4", "./bit4_RLE", "./bit8", "./bit8_RLE", "./bit16_565", "./bit16_a444", "./bit16_a555", "./bit16_x444", "./bit16_x555", "./bit24", "./bit32", "./bit32_alpha"]; + +console.log("test bmp decoding and encoding..."); + +for(var b=0; b=0.4.0" + }, + "license" : "MIT", + "author" : { + "name" : "James Halliday", + "email" : "mail@substack.net", + "url" : "http://substack.net" + } +} diff --git a/node_modules/buffer-equal/test/eq.js b/node_modules/buffer-equal/test/eq.js new file mode 100644 index 00000000..3d340062 --- /dev/null +++ b/node_modules/buffer-equal/test/eq.js @@ -0,0 +1,35 @@ +var bufferEqual = require('../'); +var test = require('tap').test; + +test('equal', function (t) { + var eq = bufferEqual( + new Buffer([253,254,255]), + new Buffer([253,254,255]) + ); + t.strictEqual(eq, true); + t.end(); +}); + +test('not equal', function (t) { + var eq = bufferEqual( + new Buffer('abc'), + new Buffer('abcd') + ); + t.strictEqual(eq, false); + t.end(); +}); + +test('not equal not buffer', function (t) { + var eq = bufferEqual( + new Buffer('abc'), + 'abc' + ); + t.strictEqual(eq, undefined); + t.end(); +}); + +test('equal not buffer', function (t) { + var eq = bufferEqual('abc', 'abc'); + t.strictEqual(eq, undefined); + t.end(); +}); diff --git a/node_modules/centra/LICENSE b/node_modules/centra/LICENSE new file mode 100644 index 00000000..ee01e012 --- /dev/null +++ b/node_modules/centra/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Ethan Davis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/centra/README.md b/node_modules/centra/README.md new file mode 100644 index 00000000..73845ca8 --- /dev/null +++ b/node_modules/centra/README.md @@ -0,0 +1,144 @@ +

+ +> The core lightweight HTTP client for Node + +[GitHub](https://github.com/ethanent/centra) | [NPM](https://npmjs.com/package/centra) + +## Install + +```shell +npm i centra +``` + +## Why centra? + +centra is the best request library for developers; it provides a number of extremely useful features while still being one of the most lightweight Node.js HTTP client libraries available. + +## Use centra! + +First, require the library. + +```js +const c = require('centra') +``` + +Then let's make a request in an async function! + +```js +;(async () => { + const res = await c('https://example.com').send() + + console.log(await res.text()) +})() +``` + +## More advanced usage + +### Send data in a JSON body + +```js +c('https://example.com/nonexistentJSONAPI', 'POST').body({ + 'name': 'Ethan' +}, 'json').send().then((res) => { + /*...*/ +}) +``` + +### Send data in a form body + +```js +c('https://example.com/nonexistentJSONAPI', 'POST').body({ + 'name': 'Ethan' +}, 'form').send().then((res) => { + /*...*/ +}) +``` + +### Set query string parameters + +One at a time: + +```js +c('https://example.com/user').query('id', 'u1817760').send().then((res) => { + /*...*/ +}) +``` + +Many at a time: + +```js +c('https://example.com/user').query({ + 'id', 'u1817760', + 'name': 'Ethan' +}).send().then((res) => { + /*...*/ +}) +``` + +### Set a request timeout + +```js +c('https://example.com').timeout(2000).send().then((res) => { + // Success! +}).catch((err) => { + // Has the request timed out? +}) +``` + +### Stream a request's response + +In this example, the [stream](https://nodejs.org/api/stream.html) is piped to a file: + +```js +// require the fs module beforehand + +c('https://example.com').stream().send().then((stream) => stream.pipe(fs.createWriteStream(path.join(__dirname, 'logo.png')))) +``` + +### Follow redirects + +```js +c('https://example.com/').followRedirects(5).send() +``` + +### Switch paths on the fly + +```js +c('https://example.com/test').path('/hello').send() + +// This will make a request to https://example.com/test/hello +``` + +### Specify request headers + +One at a time: + +```js +c('https://example.com').header('Content-Type', 'application/json').send() +``` + +Many at a time: + +```js +c('https://example.com').header({ + 'Content-Type': 'application/json', + 'X-Connecting-With': 'centra' +}).send() +``` + +### Modify core HTTP request options + +See [http.request](https://nodejs.org/dist/latest-v10.x/docs/api/http.html#http_http_request_url_options_callback)'s options for more information about core HTTP request options. +Let's change our localAddress as an example. + +```js +c('https://example.com').option('localAddress', '127.0.0.2').send() +``` + +### Accept compressed responses + +```js +c('https://example.com').compress().send() + +// This will cause centra to accept compressed content from the server. (gzip and deflate are currently supported) +``` diff --git a/node_modules/centra/createRequest.js b/node_modules/centra/createRequest.js new file mode 100644 index 00000000..364d816e --- /dev/null +++ b/node_modules/centra/createRequest.js @@ -0,0 +1,5 @@ +const CentraRequest = require('./model/CentraRequest.js') + +module.exports = (url, method) => { + return new CentraRequest(url, method) +} diff --git a/node_modules/centra/model/CentraRequest.js b/node_modules/centra/model/CentraRequest.js new file mode 100644 index 00000000..3b70a83f --- /dev/null +++ b/node_modules/centra/model/CentraRequest.js @@ -0,0 +1,220 @@ +const path = require('path') +const http = require('http') +const https = require('https') +const followRedirects = require('follow-redirects') +const qs = require('querystring') +const zlib = require('zlib') +const {URL} = require('url') + +const CentraResponse = require('./CentraResponse.js') + +const supportedCompressions = ['gzip', 'deflate', 'br'] + +const useRequest = (protocol, maxRedirects) => { + let httpr + let httpsr + if (maxRedirects <= 0) { + httpr = http.request + httpsr = https.request + } + else { + httpr = followRedirects.http.request + httpsr = followRedirects.https.request + } + + if (protocol === 'http:') { + return httpr + } + else if (protocol === 'https:') { + return httpsr + } + else throw new Error('Bad URL protocol: ' + protocol) +} + +module.exports = class CentraRequest { + constructor (url, method = 'GET') { + this.url = typeof url === 'string' ? new URL(url) : url + this.method = method + this.data = null + this.sendDataAs = null + this.reqHeaders = {} + this.streamEnabled = false + this.compressionEnabled = false + this.timeoutTime = null + this.coreOptions = {} + this.maxRedirects = 0 + + this.resOptions = { + 'maxBuffer': 50 * 1000000 // 50 MB + } + + return this + } + + followRedirects(n) { + this.maxRedirects = n + + return this + } + + query (a1, a2) { + if (typeof a1 === 'object') { + Object.keys(a1).forEach((queryKey) => { + this.url.searchParams.append(queryKey, a1[queryKey]) + }) + } + else this.url.searchParams.append(a1, a2) + + return this + } + + path (relativePath) { + this.url.pathname = path.join(this.url.pathname, relativePath) + + return this + } + + body (data, sendAs) { + this.sendDataAs = typeof data === 'object' && !sendAs && !Buffer.isBuffer(data) ? 'json' : (sendAs ? sendAs.toLowerCase() : 'buffer') + this.data = this.sendDataAs === 'form' ? qs.stringify(data) : (this.sendDataAs === 'json' ? JSON.stringify(data) : data) + + return this + } + + header (a1, a2) { + if (typeof a1 === 'object') { + Object.keys(a1).forEach((headerName) => { + this.reqHeaders[headerName.toLowerCase()] = a1[headerName] + }) + } + else this.reqHeaders[a1.toLowerCase()] = a2 + + return this + } + + timeout (timeout) { + this.timeoutTime = timeout + + return this + } + + option (name, value) { + this.coreOptions[name] = value + + return this + } + + stream () { + this.streamEnabled = true + + return this + } + + compress () { + this.compressionEnabled = true + + if (!this.reqHeaders['accept-encoding']) this.reqHeaders['accept-encoding'] = supportedCompressions.join(', ') + + return this + } + + send () { + return new Promise((resolve, reject) => { + if (this.data) { + if (!this.reqHeaders.hasOwnProperty('content-type')) { + if (this.sendDataAs === 'json') { + this.reqHeaders['content-type'] = 'application/json' + } + else if (this.sendDataAs === 'form') { + this.reqHeaders['content-type'] = 'application/x-www-form-urlencoded' + } + } + + if (!this.reqHeaders.hasOwnProperty('content-length')) { + this.reqHeaders['content-length'] = Buffer.byteLength(this.data) + } + } + + const options = Object.assign({ + 'protocol': this.url.protocol, + 'host': this.url.hostname.replace('[', '').replace(']', ''), + 'port': this.url.port, + 'path': this.url.pathname + (this.url.search === null ? '' : this.url.search), + 'method': this.method, + 'headers': this.reqHeaders, + 'maxRedirects': this.maxRedirects + }, this.coreOptions) + + let req + + const resHandler = (res) => { + let stream = res + + if (this.compressionEnabled) { + if (res.headers['content-encoding'] === 'gzip') { + stream = res.pipe(zlib.createGunzip()) + } + else if (res.headers['content-encoding'] === 'deflate') { + stream = res.pipe(zlib.createInflate()) + } + else if (res.headers['content-encoding'] === 'br') { + stream = res.pipe(zlib.createBrotliDecompress()) + } + } + + let centraRes + + if (this.streamEnabled) { + resolve(stream) + } + else { + centraRes = new CentraResponse(res, this.resOptions) + + stream.on('error', (err) => { + reject(err) + }) + + stream.on('aborted', () => { + reject(new Error('Server aborted request')) + }) + + stream.on('data', (chunk) => { + centraRes._addChunk(chunk) + + if (this.resOptions.maxBuffer !== null && centraRes.body.length > this.resOptions.maxBuffer) { + stream.destroy() + + reject('Received a response which was longer than acceptable when buffering. (' + this.body.length + ' bytes)') + } + }) + + stream.on('end', () => { + resolve(centraRes) + }) + } + } + + const request = useRequest(this.url.protocol, this.maxRedirects) + + req = request(options, resHandler) + + if (this.timeoutTime) { + req.setTimeout(this.timeoutTime, () => { + req.abort() + + if (!this.streamEnabled) { + reject(new Error('Timeout reached')) + } + }) + } + + req.on('error', (err) => { + reject(err) + }) + + if (this.data) req.write(this.data) + + req.end() + }) + } +} diff --git a/node_modules/centra/model/CentraResponse.js b/node_modules/centra/model/CentraResponse.js new file mode 100644 index 00000000..d1a17f51 --- /dev/null +++ b/node_modules/centra/model/CentraResponse.js @@ -0,0 +1,23 @@ +module.exports = class CentraResponse { + constructor (res, resOptions) { + this.coreRes = res + this.resOptions = resOptions + + this.body = Buffer.alloc(0) + + this.headers = res.headers + this.statusCode = res.statusCode + } + + _addChunk (chunk) { + this.body = Buffer.concat([this.body, chunk]) + } + + async json () { + return this.statusCode === 204 ? null : JSON.parse(this.body) + } + + async text () { + return this.body.toString() + } +} diff --git a/node_modules/centra/package.json b/node_modules/centra/package.json new file mode 100644 index 00000000..0d762716 --- /dev/null +++ b/node_modules/centra/package.json @@ -0,0 +1,40 @@ +{ + "name": "centra", + "version": "2.7.0", + "description": "The core lightweight HTTP client for Node", + "main": "createRequest.js", + "scripts": { + "test": "node test.js --test-force-exit", + "prepublishOnly": "npm test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ethanent/centra.git" + }, + "files": [ + "model/CentraRequest.js", + "model/CentraResponse.js", + "createRequest.js" + ], + "keywords": [ + "http", + "https", + "request", + "fetch", + "url", + "lightweight" + ], + "author": "Ethan Davis", + "license": "MIT", + "bugs": { + "url": "https://github.com/ethanent/centra/issues" + }, + "homepage": "https://github.com/ethanent/centra", + "devDependencies": { + "body-parser": "^1.20.2", + "express": "^4.19.2" + }, + "dependencies": { + "follow-redirects": "^1.15.6" + } +} diff --git a/node_modules/dom-walk/LICENCE b/node_modules/dom-walk/LICENCE new file mode 100644 index 00000000..a23e08a8 --- /dev/null +++ b/node_modules/dom-walk/LICENCE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/dom-walk/Makefile b/node_modules/dom-walk/Makefile new file mode 100644 index 00000000..132d3a3d --- /dev/null +++ b/node_modules/dom-walk/Makefile @@ -0,0 +1,2 @@ +run: + ./node_modules/.bin/browserify-server --cwd example \ No newline at end of file diff --git a/node_modules/dom-walk/README.md b/node_modules/dom-walk/README.md new file mode 100644 index 00000000..9e33dd15 --- /dev/null +++ b/node_modules/dom-walk/README.md @@ -0,0 +1,23 @@ +# dom-walk + +iteratively walk a DOM node + +## Example + +``` js +var walk = require("dom-walk") + +walk(document.body.childNodes, function (node) { + console.log("node", node) +}) +``` + +## Installation + +`npm install dom-walk` + +## Contributors + + - Raynos + +## MIT Licenced \ No newline at end of file diff --git a/node_modules/dom-walk/example/index.js b/node_modules/dom-walk/example/index.js new file mode 100644 index 00000000..2c8162dd --- /dev/null +++ b/node_modules/dom-walk/example/index.js @@ -0,0 +1,5 @@ +var walk = require("../index") + +walk(document, function (node) { + console.log("node", node) +}) diff --git a/node_modules/dom-walk/index.js b/node_modules/dom-walk/index.js new file mode 100644 index 00000000..9c2402d4 --- /dev/null +++ b/node_modules/dom-walk/index.js @@ -0,0 +1,24 @@ +var slice = Array.prototype.slice + +module.exports = iterativelyWalk + +function iterativelyWalk(nodes, cb) { + if (!('length' in nodes)) { + nodes = [nodes] + } + + nodes = slice.call(nodes) + + while(nodes.length) { + var node = nodes.shift(), + ret = cb(node) + + if (ret) { + return ret + } + + if (node.childNodes && node.childNodes.length) { + nodes = slice.call(node.childNodes).concat(nodes) + } + } +} diff --git a/node_modules/dom-walk/package.json b/node_modules/dom-walk/package.json new file mode 100644 index 00000000..c37c128c --- /dev/null +++ b/node_modules/dom-walk/package.json @@ -0,0 +1,32 @@ +{ + "name": "dom-walk", + "version": "0.1.2", + "description": "iteratively walk a DOM node", + "keywords": [], + "author": "Raynos ", + "repository": "git://github.com/Raynos/dom-walk.git", + "main": "index", + "homepage": "https://github.com/Raynos/dom-walk", + "contributors": [ + { + "name": "Jake Verbaten" + } + ], + "bugs": { + "url": "https://github.com/Raynos/dom-walk/issues", + "email": "raynos2@gmail.com" + }, + "dependencies": {}, + "devDependencies": { + "budo": "11.6.3" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://github.com/Raynos/dom-walk/raw/master/LICENSE" + } + ], + "scripts": { + "example": "budo example/index.js" + } +} diff --git a/node_modules/events/.airtap.yml b/node_modules/events/.airtap.yml new file mode 100644 index 00000000..c7a8a87d --- /dev/null +++ b/node_modules/events/.airtap.yml @@ -0,0 +1,15 @@ +sauce_connect: true +loopback: airtap.local +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: 9..latest + - name: iphone + version: latest + - name: ie + version: 9..latest + - name: microsoftedge + version: 13..latest diff --git a/node_modules/events/.github/FUNDING.yml b/node_modules/events/.github/FUNDING.yml new file mode 100644 index 00000000..8b8cb78b --- /dev/null +++ b/node_modules/events/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/events +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/events/.travis.yml b/node_modules/events/.travis.yml new file mode 100644 index 00000000..486dc3c4 --- /dev/null +++ b/node_modules/events/.travis.yml @@ -0,0 +1,18 @@ +dist: xenial +os: linux +language: node_js +node_js: + - 'stable' + - 'lts/*' + - '0.12' +script: + - npm test + - if [ "${TRAVIS_PULL_REQUEST}" = "false" ] && [ "${TRAVIS_NODE_VERSION}" = "stable" ]; then npm run test:browsers; fi +addons: + sauce_connect: true + hosts: + - airtap.local +env: + global: + - secure: XcBiD8yReflut9q7leKsigDZ0mI3qTKH+QrNVY8DaqlomJOZw8aOrVuX9Jz12l86ZJ41nbxmKnRNkFzcVr9mbP9YaeTb3DpeOBWmvaoSfud9Wnc16VfXtc1FCcwDhSVcSiM3UtnrmFU5cH+Dw1LPh5PbfylYOS/nJxUvG0FFLqI= + - secure: jNWtEbqhUdQ0xXDHvCYfUbKYeJCi6a7B4LsrcxYCyWWn4NIgncE5x2YbB+FSUUFVYfz0dsn5RKP1oHB99f0laUEo18HBNkrAS/rtyOdVzcpJjbQ6kgSILGjnJD/Ty1B57Rcz3iyev5Y7bLZ6Y1FbDnk/i9/l0faOGz8vTC3Vdkc= diff --git a/node_modules/events/History.md b/node_modules/events/History.md new file mode 100644 index 00000000..f48bf210 --- /dev/null +++ b/node_modules/events/History.md @@ -0,0 +1,118 @@ +# 3.3.0 + + - Support EventTarget emitters in `events.once` from Node.js 12.11.0. + + Now you can use the `events.once` function with objects that implement the EventTarget interface. This interface is used widely in + the DOM and other web APIs. + + ```js + var events = require('events'); + var assert = require('assert'); + + async function connect() { + var ws = new WebSocket('wss://example.com'); + await events.once(ws, 'open'); + assert(ws.readyState === WebSocket.OPEN); + } + + async function onClick() { + await events.once(document.body, 'click'); + alert('you clicked the page!'); + } + ``` + +# 3.2.0 + + - Add `events.once` from Node.js 11.13.0. + + To use this function, Promises must be supported in the environment. Use a polyfill like `es6-promise` if you support older browsers. + +# 3.1.0 (2020-01-08) + +`events` now matches the Node.js 11.12.0 API. + + - pass through return value in wrapped `emitter.once()` listeners + + Now, this works: + ```js + emitter.once('myevent', function () { return 1; }); + var listener = emitter.rawListeners('myevent')[0] + assert(listener() === 1); + ``` + Previously, `listener()` would return undefined regardless of the implementation. + + Ported from https://github.com/nodejs/node/commit/acc506c2d2771dab8d7bba6d3452bc5180dff7cf + + - Reduce code duplication in listener type check ([#67](https://github.com/Gozala/events/pull/67) by [@friederbluemle](https://github.com/friederbluemle)). + - Improve `emitter.once()` performance in some engines + +# 3.0.0 (2018-05-25) + +**This version drops support for IE8.** `events` no longer includes polyfills +for ES5 features. If you need to support older environments, use an ES5 shim +like [es5-shim](https://npmjs.com/package/es5-shim). Both the shim and sham +versions of es5-shim are necessary. + + - Update to events code from Node.js 10.x + - (semver major) Adds `off()` method + - Port more tests from Node.js + - Switch browser tests to airtap, making things more reliable + +# 2.1.0 (2018-05-25) + + - add Emitter#rawListeners from Node.js v9.4 + +# 2.0.0 (2018-02-02) + + - Update to events code from node.js 8.x + - Adds `prependListener()` and `prependOnceListener()` + - Adds `eventNames()` method + - (semver major) Unwrap `once()` listeners in `listeners()` + - copy tests from node.js + +Note that this version doubles the gzipped size, jumping from 1.1KB to 2.1KB, +due to new methods and runtime performance improvements. Be aware of that when +upgrading. + +# 1.1.1 (2016-06-22) + + - add more context to errors if they are not instanceof Error + +# 1.1.0 (2015-09-29) + + - add Emitter#listerCount (to match node v4 api) + +# 1.0.2 (2014-08-28) + + - remove un-reachable code + - update devDeps + +## 1.0.1 / 2014-05-11 + + - check for console.trace before using it + +## 1.0.0 / 2013-12-10 + + - Update to latest events code from node.js 0.10 + - copy tests from node.js + +## 0.4.0 / 2011-07-03 ## + + - Switching to graphquire@0.8.0 + +## 0.3.0 / 2011-07-03 ## + + - Switching to URL based module require. + +## 0.2.0 / 2011-06-10 ## + + - Simplified package structure. + - Graphquire for dependency management. + +## 0.1.1 / 2011-05-16 ## + + - Unhandled errors are logged via console.error + +## 0.1.0 / 2011-04-22 ## + + - Initial release diff --git a/node_modules/events/LICENSE b/node_modules/events/LICENSE new file mode 100644 index 00000000..52ed3b0a --- /dev/null +++ b/node_modules/events/LICENSE @@ -0,0 +1,22 @@ +MIT + +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/events/Readme.md b/node_modules/events/Readme.md new file mode 100644 index 00000000..80849c0b --- /dev/null +++ b/node_modules/events/Readme.md @@ -0,0 +1,50 @@ +# events [![Build Status](https://travis-ci.org/Gozala/events.png?branch=master)](https://travis-ci.org/Gozala/events) + +> Node's event emitter for all engines. + +This implements the Node.js [`events`][node.js docs] module for environments that do not have it, like browsers. + +> `events` currently matches the **Node.js 11.13.0** API. + +Note that the `events` module uses ES5 features. If you need to support very old browsers like IE8, use a shim like [`es5-shim`](https://www.npmjs.com/package/es5-shim). You need both the shim and the sham versions of `es5-shim`. + +This module is maintained, but only by very few people. If you'd like to help, let us know in the [Maintainer Needed](https://github.com/Gozala/events/issues/43) issue! + +## Install + +You usually do not have to install `events` yourself! If your code runs in Node.js, `events` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) also include the `events` module. + +But if none of those apply, with npm do: + +``` +npm install events +``` + +## Usage + +```javascript +var EventEmitter = require('events') + +var ee = new EventEmitter() +ee.on('message', function (text) { + console.log(text) +}) +ee.emit('message', 'hello world') +``` + +## API + +See the [Node.js EventEmitter docs][node.js docs]. `events` currently matches the Node.js 11.13.0 API. + +## Contributing + +PRs are very welcome! The main way to contribute to `events` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. +This module intends to provide exactly the same API as Node.js, so features that are not available in the core `events` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js. + +If there is a difference in behaviour between Node.js's `events` module and this module, please open an issue! + +## License + +[MIT](./LICENSE) + +[node.js docs]: https://nodejs.org/dist/v11.13.0/docs/api/events.html diff --git a/node_modules/events/events.js b/node_modules/events/events.js new file mode 100644 index 00000000..34b69a0b --- /dev/null +++ b/node_modules/events/events.js @@ -0,0 +1,497 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} diff --git a/node_modules/events/package.json b/node_modules/events/package.json new file mode 100644 index 00000000..b9580d88 --- /dev/null +++ b/node_modules/events/package.json @@ -0,0 +1,37 @@ +{ + "name": "events", + "version": "3.3.0", + "description": "Node's event emitter for all engines.", + "keywords": [ + "events", + "eventEmitter", + "eventDispatcher", + "listeners" + ], + "author": "Irakli Gozalishvili (http://jeditoolkit.com)", + "repository": { + "type": "git", + "url": "git://github.com/Gozala/events.git", + "web": "https://github.com/Gozala/events" + }, + "bugs": { + "url": "http://github.com/Gozala/events/issues/" + }, + "main": "./events.js", + "engines": { + "node": ">=0.8.x" + }, + "devDependencies": { + "airtap": "^1.0.0", + "functions-have-names": "^1.2.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "isarray": "^2.0.5", + "tape": "^5.0.0" + }, + "scripts": { + "test": "node tests/index.js", + "test:browsers": "airtap -- tests/index.js" + }, + "license": "MIT" +} diff --git a/node_modules/events/security.md b/node_modules/events/security.md new file mode 100644 index 00000000..a14ace6a --- /dev/null +++ b/node_modules/events/security.md @@ -0,0 +1,10 @@ +# Security Policy + +## Supported Versions +Only the latest major version is supported at any given time. + +## Reporting a Vulnerability + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/events/tests/add-listeners.js b/node_modules/events/tests/add-listeners.js new file mode 100644 index 00000000..9b578272 --- /dev/null +++ b/node_modules/events/tests/add-listeners.js @@ -0,0 +1,111 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var EventEmitter = require('../'); + +{ + var ee = new EventEmitter(); + var events_new_listener_emitted = []; + var listeners_new_listener_emitted = []; + + // Sanity check + assert.strictEqual(ee.addListener, ee.on); + + ee.on('newListener', function(event, listener) { + // Don't track newListener listeners. + if (event === 'newListener') + return; + + events_new_listener_emitted.push(event); + listeners_new_listener_emitted.push(listener); + }); + + var hello = common.mustCall(function(a, b) { + assert.strictEqual('a', a); + assert.strictEqual('b', b); + }); + + ee.once('newListener', function(name, listener) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(listener, hello); + + var listeners = this.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + }); + + ee.on('hello', hello); + ee.once('foo', assert.fail); + + assert.ok(Array.isArray(events_new_listener_emitted)); + assert.strictEqual(events_new_listener_emitted.length, 2); + assert.strictEqual(events_new_listener_emitted[0], 'hello'); + assert.strictEqual(events_new_listener_emitted[1], 'foo'); + + assert.ok(Array.isArray(listeners_new_listener_emitted)); + assert.strictEqual(listeners_new_listener_emitted.length, 2); + assert.strictEqual(listeners_new_listener_emitted[0], hello); + assert.strictEqual(listeners_new_listener_emitted[1], assert.fail); + + ee.emit('hello', 'a', 'b'); +} + +// just make sure that this doesn't throw: +{ + var f = new EventEmitter(); + + f.setMaxListeners(0); +} + +{ + var listen1 = function() {}; + var listen2 = function() {}; + var ee = new EventEmitter(); + + ee.once('newListener', function() { + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + ee.once('newListener', function() { + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + }); + ee.on('hello', listen2); + }); + ee.on('hello', listen1); + // The order of listeners on an event is not always the order in which the + // listeners were added. + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 2); + assert.strictEqual(listeners[0], listen2); + assert.strictEqual(listeners[1], listen1); +} + +// Verify that the listener must be a function +assert.throws(function() { + var ee = new EventEmitter(); + + ee.on('foo', null); +}, /^TypeError: The "listener" argument must be of type Function. Received type object$/); diff --git a/node_modules/events/tests/check-listener-leaks.js b/node_modules/events/tests/check-listener-leaks.js new file mode 100644 index 00000000..7fce48f3 --- /dev/null +++ b/node_modules/events/tests/check-listener-leaks.js @@ -0,0 +1,101 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var events = require('../'); + +// Redirect warning output to tape. +var consoleWarn = console.warn; +console.warn = common.test.comment; + +common.test.on('end', function () { + console.warn = consoleWarn; +}); + +// default +{ + var e = new events.EventEmitter(); + + for (var i = 0; i < 10; i++) { + e.on('default', common.mustNotCall()); + } + assert.ok(!e._events['default'].hasOwnProperty('warned')); + e.on('default', common.mustNotCall()); + assert.ok(e._events['default'].warned); + + // specific + e.setMaxListeners(5); + for (var i = 0; i < 5; i++) { + e.on('specific', common.mustNotCall()); + } + assert.ok(!e._events['specific'].hasOwnProperty('warned')); + e.on('specific', common.mustNotCall()); + assert.ok(e._events['specific'].warned); + + // only one + e.setMaxListeners(1); + e.on('only one', common.mustNotCall()); + assert.ok(!e._events['only one'].hasOwnProperty('warned')); + e.on('only one', common.mustNotCall()); + assert.ok(e._events['only one'].hasOwnProperty('warned')); + + // unlimited + e.setMaxListeners(0); + for (var i = 0; i < 1000; i++) { + e.on('unlimited', common.mustNotCall()); + } + assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); +} + +// process-wide +{ + events.EventEmitter.defaultMaxListeners = 42; + var e = new events.EventEmitter(); + + for (var i = 0; i < 42; ++i) { + e.on('fortytwo', common.mustNotCall()); + } + assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); + e.on('fortytwo', common.mustNotCall()); + assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); + delete e._events['fortytwo'].warned; + + events.EventEmitter.defaultMaxListeners = 44; + e.on('fortytwo', common.mustNotCall()); + assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); + e.on('fortytwo', common.mustNotCall()); + assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); +} + +// but _maxListeners still has precedence over defaultMaxListeners +{ + events.EventEmitter.defaultMaxListeners = 42; + var e = new events.EventEmitter(); + e.setMaxListeners(1); + e.on('uno', common.mustNotCall()); + assert.ok(!e._events['uno'].hasOwnProperty('warned')); + e.on('uno', common.mustNotCall()); + assert.ok(e._events['uno'].hasOwnProperty('warned')); + + // chainable + assert.strictEqual(e, e.setMaxListeners(1)); +} diff --git a/node_modules/events/tests/common.js b/node_modules/events/tests/common.js new file mode 100644 index 00000000..49569b05 --- /dev/null +++ b/node_modules/events/tests/common.js @@ -0,0 +1,104 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var test = require('tape'); +var assert = require('assert'); + +var noop = function() {}; + +var mustCallChecks = []; + +function runCallChecks(exitCode) { + if (exitCode !== 0) return; + + var failed = filter(mustCallChecks, function(context) { + if ('minimum' in context) { + context.messageSegment = 'at least ' + context.minimum; + return context.actual < context.minimum; + } else { + context.messageSegment = 'exactly ' + context.exact; + return context.actual !== context.exact; + } + }); + + for (var i = 0; i < failed.length; i++) { + var context = failed[i]; + console.log('Mismatched %s function calls. Expected %s, actual %d.', + context.name, + context.messageSegment, + context.actual); + // IE8 has no .stack + if (context.stack) console.log(context.stack.split('\n').slice(2).join('\n')); + } + + assert.strictEqual(failed.length, 0); +} + +exports.mustCall = function(fn, exact) { + return _mustCallInner(fn, exact, 'exact'); +}; + +function _mustCallInner(fn, criteria, field) { + if (typeof criteria == 'undefined') criteria = 1; + + if (typeof fn === 'number') { + criteria = fn; + fn = noop; + } else if (fn === undefined) { + fn = noop; + } + + if (typeof criteria !== 'number') + throw new TypeError('Invalid ' + field + ' value: ' + criteria); + + var context = { + actual: 0, + stack: (new Error()).stack, + name: fn.name || '' + }; + + context[field] = criteria; + + // add the exit listener only once to avoid listener leak warnings + if (mustCallChecks.length === 0) test.onFinish(function() { runCallChecks(0); }); + + mustCallChecks.push(context); + + return function() { + context.actual++; + return fn.apply(this, arguments); + }; +} + +exports.mustNotCall = function(msg) { + return function mustNotCall() { + assert.fail(msg || 'function should not have been called'); + }; +}; + +function filter(arr, fn) { + if (arr.filter) return arr.filter(fn); + var filtered = []; + for (var i = 0; i < arr.length; i++) { + if (fn(arr[i], i, arr)) filtered.push(arr[i]); + } + return filtered +} diff --git a/node_modules/events/tests/errors.js b/node_modules/events/tests/errors.js new file mode 100644 index 00000000..a23df437 --- /dev/null +++ b/node_modules/events/tests/errors.js @@ -0,0 +1,13 @@ +'use strict'; +var assert = require('assert'); +var EventEmitter = require('../'); + +var EE = new EventEmitter(); + +assert.throws(function () { + EE.emit('error', 'Accepts a string'); +}, 'Error: Unhandled error. (Accepts a string)'); + +assert.throws(function () { + EE.emit('error', { message: 'Error!' }); +}, 'Unhandled error. ([object Object])'); diff --git a/node_modules/events/tests/events-list.js b/node_modules/events/tests/events-list.js new file mode 100644 index 00000000..08aa6217 --- /dev/null +++ b/node_modules/events/tests/events-list.js @@ -0,0 +1,28 @@ +'use strict'; + +var EventEmitter = require('../'); +var assert = require('assert'); + +var EE = new EventEmitter(); +var m = function() {}; +EE.on('foo', function() {}); +assert.equal(1, EE.eventNames().length); +assert.equal('foo', EE.eventNames()[0]); +EE.on('bar', m); +assert.equal(2, EE.eventNames().length); +assert.equal('foo', EE.eventNames()[0]); +assert.equal('bar', EE.eventNames()[1]); +EE.removeListener('bar', m); +assert.equal(1, EE.eventNames().length); +assert.equal('foo', EE.eventNames()[0]); + +if (typeof Symbol !== 'undefined') { + var s = Symbol('s'); + EE.on(s, m); + assert.equal(2, EE.eventNames().length); + assert.equal('foo', EE.eventNames()[0]); + assert.equal(s, EE.eventNames()[1]); + EE.removeListener(s, m); + assert.equal(1, EE.eventNames().length); + assert.equal('foo', EE.eventNames()[0]); +} diff --git a/node_modules/events/tests/events-once.js b/node_modules/events/tests/events-once.js new file mode 100644 index 00000000..dae86496 --- /dev/null +++ b/node_modules/events/tests/events-once.js @@ -0,0 +1,234 @@ +'use strict'; + +var common = require('./common'); +var EventEmitter = require('../').EventEmitter; +var once = require('../').once; +var has = require('has'); +var assert = require('assert'); + +function Event(type) { + this.type = type; +} + +function EventTargetMock() { + this.events = {}; + + this.addEventListener = common.mustCall(this.addEventListener); + this.removeEventListener = common.mustCall(this.removeEventListener); +} + +EventTargetMock.prototype.addEventListener = function addEventListener(name, listener, options) { + if (!(name in this.events)) { + this.events[name] = { listeners: [], options: options || {} } + } + this.events[name].listeners.push(listener); +}; + +EventTargetMock.prototype.removeEventListener = function removeEventListener(name, callback) { + if (!(name in this.events)) { + return; + } + var event = this.events[name]; + var stack = event.listeners; + + for (var i = 0, l = stack.length; i < l; i++) { + if (stack[i] === callback) { + stack.splice(i, 1); + if (stack.length === 0) { + delete this.events[name]; + } + return; + } + } +}; + +EventTargetMock.prototype.dispatchEvent = function dispatchEvent(arg) { + if (!(arg.type in this.events)) { + return true; + } + + var event = this.events[arg.type]; + var stack = event.listeners.slice(); + + for (var i = 0, l = stack.length; i < l; i++) { + stack[i].call(null, arg); + if (event.options.once) { + this.removeEventListener(arg.type, stack[i]); + } + } + return !arg.defaultPrevented; +}; + +function onceAnEvent() { + var ee = new EventEmitter(); + + process.nextTick(function () { + ee.emit('myevent', 42); + }); + + return once(ee, 'myevent').then(function (args) { + var value = args[0] + assert.strictEqual(value, 42); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + }); +} + +function onceAnEventWithTwoArgs() { + var ee = new EventEmitter(); + + process.nextTick(function () { + ee.emit('myevent', 42, 24); + }); + + return once(ee, 'myevent').then(function (value) { + assert.strictEqual(value.length, 2); + assert.strictEqual(value[0], 42); + assert.strictEqual(value[1], 24); + }); +} + +function catchesErrors() { + var ee = new EventEmitter(); + + var expected = new Error('kaboom'); + var err; + process.nextTick(function () { + ee.emit('error', expected); + }); + + return once(ee, 'myevent').then(function () { + throw new Error('should reject') + }, function (err) { + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + }); +} + +function stopListeningAfterCatchingError() { + var ee = new EventEmitter(); + + var expected = new Error('kaboom'); + var err; + process.nextTick(function () { + ee.emit('error', expected); + ee.emit('myevent', 42, 24); + }); + + // process.on('multipleResolves', common.mustNotCall()); + + return once(ee, 'myevent').then(common.mustNotCall, function (err) { + // process.removeAllListeners('multipleResolves'); + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + }); +} + +function onceError() { + var ee = new EventEmitter(); + + var expected = new Error('kaboom'); + process.nextTick(function () { + ee.emit('error', expected); + }); + + var promise = once(ee, 'error'); + assert.strictEqual(ee.listenerCount('error'), 1); + return promise.then(function (args) { + var err = args[0] + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + }); +} + +function onceWithEventTarget() { + var et = new EventTargetMock(); + var event = new Event('myevent'); + process.nextTick(function () { + et.dispatchEvent(event); + }); + return once(et, 'myevent').then(function (args) { + var value = args[0]; + assert.strictEqual(value, event); + assert.strictEqual(has(et.events, 'myevent'), false); + }); +} + +function onceWithEventTargetError() { + var et = new EventTargetMock(); + var error = new Event('error'); + process.nextTick(function () { + et.dispatchEvent(error); + }); + return once(et, 'error').then(function (args) { + var err = args[0]; + assert.strictEqual(err, error); + assert.strictEqual(has(et.events, 'error'), false); + }); +} + +function prioritizesEventEmitter() { + var ee = new EventEmitter(); + ee.addEventListener = assert.fail; + ee.removeAllListeners = assert.fail; + process.nextTick(function () { + ee.emit('foo'); + }); + return once(ee, 'foo'); +} + +var allTests = [ + onceAnEvent(), + onceAnEventWithTwoArgs(), + catchesErrors(), + stopListeningAfterCatchingError(), + onceError(), + onceWithEventTarget(), + onceWithEventTargetError(), + prioritizesEventEmitter() +]; + +var hasBrowserEventTarget = false; +try { + hasBrowserEventTarget = typeof (new window.EventTarget().addEventListener) === 'function' && + new window.Event('xyz').type === 'xyz'; +} catch (err) {} + +if (hasBrowserEventTarget) { + var onceWithBrowserEventTarget = function onceWithBrowserEventTarget() { + var et = new window.EventTarget(); + var event = new window.Event('myevent'); + process.nextTick(function () { + et.dispatchEvent(event); + }); + return once(et, 'myevent').then(function (args) { + var value = args[0]; + assert.strictEqual(value, event); + assert.strictEqual(has(et.events, 'myevent'), false); + }); + } + + var onceWithBrowserEventTargetError = function onceWithBrowserEventTargetError() { + var et = new window.EventTarget(); + var error = new window.Event('error'); + process.nextTick(function () { + et.dispatchEvent(error); + }); + return once(et, 'error').then(function (args) { + var err = args[0]; + assert.strictEqual(err, error); + assert.strictEqual(has(et.events, 'error'), false); + }); + } + + common.test.comment('Testing with browser built-in EventTarget'); + allTests.push([ + onceWithBrowserEventTarget(), + onceWithBrowserEventTargetError() + ]); +} + +module.exports = Promise.all(allTests); diff --git a/node_modules/events/tests/index.js b/node_modules/events/tests/index.js new file mode 100644 index 00000000..2d739e67 --- /dev/null +++ b/node_modules/events/tests/index.js @@ -0,0 +1,64 @@ +var test = require('tape'); +var functionsHaveNames = require('functions-have-names'); +var hasSymbols = require('has-symbols'); + +require('./legacy-compat'); +var common = require('./common'); + +// we do this to easily wrap each file in a mocha test +// and also have browserify be able to statically analyze this file +var orig_require = require; +var require = function(file) { + test(file, function(t) { + // Store the tape object so tests can access it. + t.on('end', function () { delete common.test; }); + common.test = t; + + try { + var exp = orig_require(file); + if (exp && exp.then) { + exp.then(function () { t.end(); }, t.fail); + return; + } + } catch (err) { + t.fail(err); + } + t.end(); + }); +}; + +require('./add-listeners.js'); +require('./check-listener-leaks.js'); +require('./errors.js'); +require('./events-list.js'); +if (typeof Promise === 'function') { + require('./events-once.js'); +} else { + // Promise support is not available. + test('./events-once.js', { skip: true }, function () {}); +} +require('./listener-count.js'); +require('./listeners-side-effects.js'); +require('./listeners.js'); +require('./max-listeners.js'); +if (functionsHaveNames()) { + require('./method-names.js'); +} else { + // Function.name is not supported in IE + test('./method-names.js', { skip: true }, function () {}); +} +require('./modify-in-emit.js'); +require('./num-args.js'); +require('./once.js'); +require('./prepend.js'); +require('./set-max-listeners-side-effects.js'); +require('./special-event-names.js'); +require('./subclass.js'); +if (hasSymbols()) { + require('./symbols.js'); +} else { + // Symbol is not available. + test('./symbols.js', { skip: true }, function () {}); +} +require('./remove-all-listeners.js'); +require('./remove-listeners.js'); diff --git a/node_modules/events/tests/legacy-compat.js b/node_modules/events/tests/legacy-compat.js new file mode 100644 index 00000000..a402be6e --- /dev/null +++ b/node_modules/events/tests/legacy-compat.js @@ -0,0 +1,16 @@ +// sigh... life is hard +if (!global.console) { + console = {} +} + +var fns = ['log', 'error', 'trace']; +for (var i=0 ; ifoo should not be emitted'); +} + +e.once('foo', remove); +e.removeListener('foo', remove); +e.emit('foo'); + +e.once('e', common.mustCall(function() { + e.emit('e'); +})); + +e.once('e', common.mustCall()); + +e.emit('e'); + +// Verify that the listener must be a function +assert.throws(function() { + var ee = new EventEmitter(); + + ee.once('foo', null); +}, /^TypeError: The "listener" argument must be of type Function. Received type object$/); + +{ + // once() has different code paths based on the number of arguments being + // emitted. Verify that all of the cases are covered. + var maxArgs = 4; + + for (var i = 0; i <= maxArgs; ++i) { + var ee = new EventEmitter(); + var args = ['foo']; + + for (var j = 0; j < i; ++j) + args.push(j); + + ee.once('foo', common.mustCall(function() { + var params = Array.prototype.slice.call(arguments); + var restArgs = args.slice(1); + assert.ok(Array.isArray(params)); + assert.strictEqual(params.length, restArgs.length); + for (var index = 0; index < params.length; index++) { + var param = params[index]; + assert.strictEqual(param, restArgs[index]); + } + })); + + EventEmitter.prototype.emit.apply(ee, args); + } +} diff --git a/node_modules/events/tests/prepend.js b/node_modules/events/tests/prepend.js new file mode 100644 index 00000000..79afde0b --- /dev/null +++ b/node_modules/events/tests/prepend.js @@ -0,0 +1,31 @@ +'use strict'; + +var common = require('./common'); +var EventEmitter = require('../'); +var assert = require('assert'); + +var myEE = new EventEmitter(); +var m = 0; +// This one comes last. +myEE.on('foo', common.mustCall(function () { + assert.strictEqual(m, 2); +})); + +// This one comes second. +myEE.prependListener('foo', common.mustCall(function () { + assert.strictEqual(m++, 1); +})); + +// This one comes first. +myEE.prependOnceListener('foo', + common.mustCall(function () { + assert.strictEqual(m++, 0); + })); + +myEE.emit('foo'); + +// Verify that the listener must be a function +assert.throws(function () { + var ee = new EventEmitter(); + ee.prependOnceListener('foo', null); +}, 'TypeError: The "listener" argument must be of type Function. Received type object'); diff --git a/node_modules/events/tests/remove-all-listeners.js b/node_modules/events/tests/remove-all-listeners.js new file mode 100644 index 00000000..622941cf --- /dev/null +++ b/node_modules/events/tests/remove-all-listeners.js @@ -0,0 +1,133 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var events = require('../'); +var test = require('tape'); + +function expect(expected) { + var actual = []; + test.onFinish(function() { + var sortedActual = actual.sort(); + var sortedExpected = expected.sort(); + assert.strictEqual(sortedActual.length, sortedExpected.length); + for (var index = 0; index < sortedActual.length; index++) { + var value = sortedActual[index]; + assert.strictEqual(value, sortedExpected[index]); + } + }); + function listener(name) { + actual.push(name); + } + return common.mustCall(listener, expected.length); +} + +{ + var ee = new events.EventEmitter(); + var noop = common.mustNotCall(); + ee.on('foo', noop); + ee.on('bar', noop); + ee.on('baz', noop); + ee.on('baz', noop); + var fooListeners = ee.listeners('foo'); + var barListeners = ee.listeners('bar'); + var bazListeners = ee.listeners('baz'); + ee.on('removeListener', expect(['bar', 'baz', 'baz'])); + ee.removeAllListeners('bar'); + ee.removeAllListeners('baz'); + + var listeners = ee.listeners('foo'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], noop); + + listeners = ee.listeners('bar'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + listeners = ee.listeners('baz'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + // After calling removeAllListeners(), + // the old listeners array should stay unchanged. + assert.strictEqual(fooListeners.length, 1); + assert.strictEqual(fooListeners[0], noop); + assert.strictEqual(barListeners.length, 1); + assert.strictEqual(barListeners[0], noop); + assert.strictEqual(bazListeners.length, 2); + assert.strictEqual(bazListeners[0], noop); + assert.strictEqual(bazListeners[1], noop); + // After calling removeAllListeners(), + // new listeners arrays is different from the old. + assert.notStrictEqual(ee.listeners('bar'), barListeners); + assert.notStrictEqual(ee.listeners('baz'), bazListeners); +} + +{ + var ee = new events.EventEmitter(); + ee.on('foo', common.mustNotCall()); + ee.on('bar', common.mustNotCall()); + // Expect LIFO order + ee.on('removeListener', expect(['foo', 'bar', 'removeListener'])); + ee.on('removeListener', expect(['foo', 'bar'])); + ee.removeAllListeners(); + + var listeners = ee.listeners('foo'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + listeners = ee.listeners('bar'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); +} + +{ + var ee = new events.EventEmitter(); + ee.on('removeListener', common.mustNotCall()); + // Check for regression where removeAllListeners() throws when + // there exists a 'removeListener' listener, but there exists + // no listeners for the provided event type. + assert.doesNotThrow(function () { ee.removeAllListeners(ee, 'foo') }); +} + +{ + var ee = new events.EventEmitter(); + var expectLength = 2; + ee.on('removeListener', function() { + assert.strictEqual(expectLength--, this.listeners('baz').length); + }); + ee.on('baz', common.mustNotCall()); + ee.on('baz', common.mustNotCall()); + ee.on('baz', common.mustNotCall()); + assert.strictEqual(ee.listeners('baz').length, expectLength + 1); + ee.removeAllListeners('baz'); + assert.strictEqual(ee.listeners('baz').length, 0); +} + +{ + var ee = new events.EventEmitter(); + assert.strictEqual(ee, ee.removeAllListeners()); +} + +{ + var ee = new events.EventEmitter(); + ee._events = undefined; + assert.strictEqual(ee, ee.removeAllListeners()); +} diff --git a/node_modules/events/tests/remove-listeners.js b/node_modules/events/tests/remove-listeners.js new file mode 100644 index 00000000..18e4d165 --- /dev/null +++ b/node_modules/events/tests/remove-listeners.js @@ -0,0 +1,212 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var EventEmitter = require('../'); + +var listener1 = function listener1() {}; +var listener2 = function listener2() {}; + +{ + var ee = new EventEmitter(); + ee.on('hello', listener1); + ee.on('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener1); + })); + ee.removeListener('hello', listener1); + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); +} + +{ + var ee = new EventEmitter(); + ee.on('hello', listener1); + ee.on('removeListener', common.mustNotCall()); + ee.removeListener('hello', listener2); + + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], listener1); +} + +{ + var ee = new EventEmitter(); + ee.on('hello', listener1); + ee.on('hello', listener2); + + var listeners; + ee.once('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener1); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], listener2); + })); + ee.removeListener('hello', listener1); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], listener2); + ee.once('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener2); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + })); + ee.removeListener('hello', listener2); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); +} + +{ + var ee = new EventEmitter(); + + function remove1() { + assert.fail('remove1 should not have been called'); + } + + function remove2() { + assert.fail('remove2 should not have been called'); + } + + ee.on('removeListener', common.mustCall(function(name, cb) { + if (cb !== remove1) return; + this.removeListener('quux', remove2); + this.emit('quux'); + }, 2)); + ee.on('quux', remove1); + ee.on('quux', remove2); + ee.removeListener('quux', remove1); +} + +{ + var ee = new EventEmitter(); + ee.on('hello', listener1); + ee.on('hello', listener2); + + var listeners; + ee.once('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener1); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], listener2); + ee.once('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener2); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + })); + ee.removeListener('hello', listener2); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + })); + ee.removeListener('hello', listener1); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); +} + +{ + var ee = new EventEmitter(); + var listener3 = common.mustCall(function() { + ee.removeListener('hello', listener4); + }, 2); + var listener4 = common.mustCall(); + + ee.on('hello', listener3); + ee.on('hello', listener4); + + // listener4 will still be called although it is removed by listener 3. + ee.emit('hello'); + // This is so because the interal listener array at time of emit + // was [listener3,listener4] + + // Interal listener array [listener3] + ee.emit('hello'); +} + +{ + var ee = new EventEmitter(); + + ee.once('hello', listener1); + ee.on('removeListener', common.mustCall(function(eventName, listener) { + assert.strictEqual(eventName, 'hello'); + assert.strictEqual(listener, listener1); + })); + ee.emit('hello'); +} + +{ + var ee = new EventEmitter(); + + assert.strictEqual(ee, ee.removeListener('foo', function() {})); +} + +// Verify that the removed listener must be a function +assert.throws(function() { + var ee = new EventEmitter(); + + ee.removeListener('foo', null); +}, /^TypeError: The "listener" argument must be of type Function\. Received type object$/); + +{ + var ee = new EventEmitter(); + var listener = function() {}; + ee._events = undefined; + var e = ee.removeListener('foo', listener); + assert.strictEqual(e, ee); +} + +{ + var ee = new EventEmitter(); + + ee.on('foo', listener1); + ee.on('foo', listener2); + var listeners = ee.listeners('foo'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 2); + assert.strictEqual(listeners[0], listener1); + assert.strictEqual(listeners[1], listener2); + + ee.removeListener('foo', listener1); + assert.strictEqual(ee._events.foo, listener2); + + ee.on('foo', listener1); + listeners = ee.listeners('foo'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 2); + assert.strictEqual(listeners[0], listener2); + assert.strictEqual(listeners[1], listener1); + + ee.removeListener('foo', listener1); + assert.strictEqual(ee._events.foo, listener2); +} diff --git a/node_modules/events/tests/set-max-listeners-side-effects.js b/node_modules/events/tests/set-max-listeners-side-effects.js new file mode 100644 index 00000000..13dbb671 --- /dev/null +++ b/node_modules/events/tests/set-max-listeners-side-effects.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +require('./common'); +var assert = require('assert'); +var events = require('../'); + +var e = new events.EventEmitter(); + +if (Object.create) assert.ok(!(e._events instanceof Object)); +assert.strictEqual(Object.keys(e._events).length, 0); +e.setMaxListeners(5); +assert.strictEqual(Object.keys(e._events).length, 0); diff --git a/node_modules/events/tests/special-event-names.js b/node_modules/events/tests/special-event-names.js new file mode 100644 index 00000000..a2f0b744 --- /dev/null +++ b/node_modules/events/tests/special-event-names.js @@ -0,0 +1,45 @@ +'use strict'; + +var common = require('./common'); +var EventEmitter = require('../'); +var assert = require('assert'); + +var ee = new EventEmitter(); +var handler = function() {}; + +assert.strictEqual(ee.eventNames().length, 0); + +assert.strictEqual(ee._events.hasOwnProperty, undefined); +assert.strictEqual(ee._events.toString, undefined); + +ee.on('__defineGetter__', handler); +ee.on('toString', handler); +ee.on('__proto__', handler); + +assert.strictEqual(ee.eventNames()[0], '__defineGetter__'); +assert.strictEqual(ee.eventNames()[1], 'toString'); + +assert.strictEqual(ee.listeners('__defineGetter__').length, 1); +assert.strictEqual(ee.listeners('__defineGetter__')[0], handler); +assert.strictEqual(ee.listeners('toString').length, 1); +assert.strictEqual(ee.listeners('toString')[0], handler); + +// Only run __proto__ tests if that property can actually be set +if ({ __proto__: 'ok' }.__proto__ === 'ok') { + assert.strictEqual(ee.eventNames().length, 3); + assert.strictEqual(ee.eventNames()[2], '__proto__'); + assert.strictEqual(ee.listeners('__proto__').length, 1); + assert.strictEqual(ee.listeners('__proto__')[0], handler); + + ee.on('__proto__', common.mustCall(function(val) { + assert.strictEqual(val, 1); + })); + ee.emit('__proto__', 1); + + process.on('__proto__', common.mustCall(function(val) { + assert.strictEqual(val, 1); + })); + process.emit('__proto__', 1); +} else { + console.log('# skipped __proto__') +} diff --git a/node_modules/events/tests/subclass.js b/node_modules/events/tests/subclass.js new file mode 100644 index 00000000..bd033fff --- /dev/null +++ b/node_modules/events/tests/subclass.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var test = require('tape'); +var assert = require('assert'); +var EventEmitter = require('../').EventEmitter; +var util = require('util'); + +util.inherits(MyEE, EventEmitter); + +function MyEE(cb) { + this.once(1, cb); + this.emit(1); + this.removeAllListeners(); + EventEmitter.call(this); +} + +var myee = new MyEE(common.mustCall()); + + +util.inherits(ErrorEE, EventEmitter); +function ErrorEE() { + this.emit('error', new Error('blerg')); +} + +assert.throws(function() { + new ErrorEE(); +}, /blerg/); + +test.onFinish(function() { + assert.ok(!(myee._events instanceof Object)); + assert.strictEqual(Object.keys(myee._events).length, 0); +}); + + +function MyEE2() { + EventEmitter.call(this); +} + +MyEE2.prototype = new EventEmitter(); + +var ee1 = new MyEE2(); +var ee2 = new MyEE2(); + +ee1.on('x', function() {}); + +assert.strictEqual(ee2.listenerCount('x'), 0); diff --git a/node_modules/events/tests/symbols.js b/node_modules/events/tests/symbols.js new file mode 100644 index 00000000..0721f0ec --- /dev/null +++ b/node_modules/events/tests/symbols.js @@ -0,0 +1,25 @@ +'use strict'; + +var common = require('./common'); +var EventEmitter = require('../'); +var assert = require('assert'); + +var ee = new EventEmitter(); +var foo = Symbol('foo'); +var listener = common.mustCall(); + +ee.on(foo, listener); +assert.strictEqual(ee.listeners(foo).length, 1); +assert.strictEqual(ee.listeners(foo)[0], listener); + +ee.emit(foo); + +ee.removeAllListeners(); +assert.strictEqual(ee.listeners(foo).length, 0); + +ee.on(foo, listener); +assert.strictEqual(ee.listeners(foo).length, 1); +assert.strictEqual(ee.listeners(foo)[0], listener); + +ee.removeListener(foo, listener); +assert.strictEqual(ee.listeners(foo).length, 0); diff --git a/node_modules/exif-parser/.npmignore b/node_modules/exif-parser/.npmignore new file mode 100644 index 00000000..76add878 --- /dev/null +++ b/node_modules/exif-parser/.npmignore @@ -0,0 +1,2 @@ +node_modules +dist \ No newline at end of file diff --git a/node_modules/exif-parser/CHANGELOG.md b/node_modules/exif-parser/CHANGELOG.md new file mode 100644 index 00000000..2cfc4033 --- /dev/null +++ b/node_modules/exif-parser/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +## 0.1.11 - July 9th 2017 + + - On nodejs, decode strings using UTF-8 instead of ASCII. Ideally we'd do this in the browser (UTF-16 currently) as well but that is a bit more work. + +## 0.1.10 - July 9th 2017 + +- Ignore unknown tag formats instead of failing. There seem to be images with format 0 that otherwise contain valid data. +- Fix bug in date parsing to not rely on the current date. This broke when the current date was the 31st of the month. +- In case a tag appears more than once, take the first, not the last. For example some pictures taken on an iPhone suffer from duplicate Orientation tags, where the first one is the wrong one. +- treat ModifyDate tag as a date value + +## 0.1.9 - April 9th 2015 + +- parse ISO 8601 dates with timezone offset diff --git a/node_modules/exif-parser/LICENSE.md b/node_modules/exif-parser/LICENSE.md new file mode 100644 index 00000000..e8f2aab9 --- /dev/null +++ b/node_modules/exif-parser/LICENSE.md @@ -0,0 +1,23 @@ +The MIT License +=============== + +Copyright (c) 2010 Bruno Windels , Daniel Leinich . + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/exif-parser/Makefile b/node_modules/exif-parser/Makefile new file mode 100644 index 00000000..06e4f760 --- /dev/null +++ b/node_modules/exif-parser/Makefile @@ -0,0 +1,16 @@ +VERSION=$(shell node --eval "console.log(require('./package.json').version)") +BUNDLE=dist/exif-parser-$(VERSION).js +MIN_BUNDLE=dist/exif-parser-$(VERSION)-min.js +BROWSERIFY=node_modules/.bin/browserify +UGLIFY=node_modules/.bin/uglifyjs + +build-browser-bundle: setup + @echo "building $(BUNDLE) ..." + @mkdir -p dist/ + @$(BROWSERIFY) --bare browser-global.js -o $(BUNDLE) + @echo "building $(MIN_BUNDLE) ..." + @$(UGLIFY) $(BUNDLE) -o $(MIN_BUNDLE) --compress +setup: + @npm install --no-optional --loglevel error --development +clean: + @rm -rf dist/ \ No newline at end of file diff --git a/node_modules/exif-parser/README.md b/node_modules/exif-parser/README.md new file mode 100644 index 00000000..3b2404d0 --- /dev/null +++ b/node_modules/exif-parser/README.md @@ -0,0 +1,83 @@ +exif-parser +======== +exif-parser is a parser for image metadata in the exif format, the most popular metadata format for jpeg and tiff images. It is written in pure javascript and has no external dependencies. It can also get the size of jpeg images and the size of the jpeg thumbnail embedded in the exif data. It can also extract the embedded thumbnail image. + +### Installing + + npm install exif-parser + +You can also build a browser bundle to include it with a ` +``` + +## How to use + +Please refer to [API Documentation and Usage](http://ibezkrovnyi.github.io/image-quantization/) + +## Breaking changes + +#### 2.1.1 + + + PaletteQuantizer#quantize => PaletteQuantizer#quantizeSync + + ImageQuantizer#quantize => ImageQuantizer#quantizeSync + +#### 2.0.1 - 2.0.4 (2018-02-22) + + + EuclideanRgbQuantWOAlpha => EuclideanBT709NoAlpha + + EuclideanRgbQuantWithAlpha => EuclideanBT709 + + ManhattanSRGB => ManhattanBT709 + + IImageDitherer => AbstractImageQuantizer + + IPaletteQuantizer => AbstractPaletteQuantizer + + PointContainer.fromNodeCanvas => PointContainer.fromHTMLCanvasElement + + PointContainer.fromArray => PointContainer.fromUint8Array + + PointContainer.fromBuffer (Node.js, new) + + CMETRIC => CMetric + + PNGQUANT => PNGQuant + + SSIM Class => ssim function + +## TODO + +1. ~~notification about progress~~ +2. ~~riemersma dithering~~ +3. ordered dithering <-- is there anyone who needs it? +4. readme update, more examples +5. demo update (latest image-q npm version should be used in demo) + +## Changelog + +##### 4.0.0 + + Test cases for different types of imports and requres added + +##### 4.0.0-alpha + + Try to solve exported bundle types problem. 'umd' bundle removed. + +##### 3.0.8 + + Test case for issue #95 added + +##### 3.0.7 + + Fixes #96: Fix minimumColorDistanceToDither (PR #97 by @pixelplanetdev) + +##### 3.0.6 + + Fixes #95: "Always empty result in certain webpack / babel configs" (PR #98) + +##### 3.0.4 + + Fixes issue "Module not found: Can't resolve 'core-js/fn/set-immediate' in ..." + +##### 3.0.0 + + pnpm monorepo, esbuild for faster builds, typescript upgraded + +##### 2.1.1 + + + Basic (Simple) API implemented + + see breaking changes + +##### 2.0.5 (2018-02-23) + + + @types/node moved to 'dependencies' + +##### 2.0.4 (2018-02-23) + + + documentation added + + some refactorings/renames, see breaking changes + +##### 2.0.3 (2018-02-22) + + + circular dependency removed + +##### 2.0.2 (2018-02-22) + + + readme updated + +##### 2.0.1 (2018-02-22) + + + progress tracking api (using es6 generators) added + + strinct lint rules (+code cleanup/renames) + + rollup (3 different versions - umd, cjs, esm + source maps + d.ts) + + latest TypeScript + + jest + + snapshot tests + + coverage (+coveralls) + + greenkeeper + +##### 1.1.1 (2016-08-28) + + + CIEDE2000 - incorrect calculation fixed + + CIEDE2000 - alpha channel now has only 25% impact on color distance instead of 66% + + CIE94 - added 2 types (textiles and graphics art) according to spec + + CIE94 - alpha support added + + rgb2xyz, lab2xyz, xyz2rgb, xyz2lab - gamma correction + + lab2xyz, xyz2lab - refY should be 100 (1.00000) instead of 10 (0.10000) + + manhattan with new (Nommyde) coefficients added + + mocha tests added + + webpack integration + + image-q is now UMD module + + travis-ci integration + + typescript 2.0 + + indentation with 4 spaces + +##### 0.1.4 (2015-06-24) + + + Refactoring + + Riemersma dithering added (Hilbert Curve) + + Readme.md updated + + build.cmd updated + +##### 0.1.3 (2015-06-16) + + + NeuQuant is fixed (again) according to original Anthony Dekker source code (all values should be integer) + + Error Diffusion Dithering is now calculates error like XNVIEW + + Refactoring + +##### 0.1.2 (2015-06-16) + + + Documentation generation fixed + + File name case problem fixed + +##### 0.1.1 (2015-06-16) + + + Auto-generated documentation added + + Refactoring + +##### 0.1.0 (2015-06-16) + + + Code cleanup, removed unnecessary files + +##### 0.0.5 (2015-06-16) + + + PNGQuant color distance added, need to check its quality + + CIEDE2000 and CIE94 fixed for use in NeuQuant + + NeuQuant is fixed according to original Anthony Dekker source code (all values should be integer) + + Code refactoring and cleanup + * We have some slowdown because of red/green/blue/alpha normalization according to white point per each calculateRaw/calculateNormalized call + +##### 0.0.4 (2015-06-15) + + + CIEDE2000 color distance equation optimized (original CIEDE2000 equation is available as class `CIEDE2000_Original`) + +##### 0.0.3b (2015-06-11) + + + CMetric color distance fixed + +##### 0.0.3a (2015-06-11) + + + Cleanup + + Draft of CMetric color distance added + +##### 0.0.2 (2015-06-10) + + + rgb2xyz & xyz2lab fixed. CIEDE2000 works much better now. + + CIE94 distance formula added. More investigation is needed. + +##### 0.0.1 + + + Initial + +## Credits + +Thanks to Leon Sorokin for information share and his original RGBQuant! + +## References + +- Palette Quantization Algorithms + + 1. [RGBQuant (Leon Sorokin)](https://github.com/leeoniya/RgbQuant.js) `JavaScript` + 2. [NeuQuant (Johan Nordberg)](https://github.com/jnordberg/gif.js/blob/master/src/TypedNeuQuant.js) `TypeScript` + 3. [NeuQuant (Tim Oxley)](https://github.com/timoxley/neuquant) `JavaScript` + 4. [NeuQuant (Devon Govett)](https://github.com/devongovett/neuquant) `JavaScript` + 5. [NeuQuant32 (Stuart Coyle)](https://github.com/stuart/pngnq/blob/master/src/neuquant32.c) `C` + 6. [Xiaolin Wu (Xiaolin Wu)](http://www.ece.mcmaster.ca/~xwu/cq.c) `C` + 7. [Xiaolin Wu (Smart-K8)](http://www.codeproject.com/Articles/66341/A-Simple-Yet-Quite-Powerful-Palette-Quantizer-in-C) `C#` + 8. Xiaolin Wu w/ Alpha (Matt Wrock) [How to add Alpha](https://code.msdn.microsoft.com/windowsdesktop/Convert-32-bit-PNGs-to-81ef8c81/view/SourceCode#content), [Source Code](https://nquant.codeplex.com) `C#` + 9. [MedianCut (mwcz)](https://github.com/mwcz/median-cut-js) `GPLv3` + +- Image Quantization Algorithms + + 1. [All (ImageMagik doc)](http://www.imagemagick.org/Usage/quantize/#dither) + 2. [Error Diffusion dithering (Tanner Helland)](http://www.tannerhelland.com/4660/dithering-eleven-algorithms-source-code) + 3. [Riemersma dithering](http://www.compuphase.com/riemer.htm) `TODO: Check License` + 4. [Ordered dithering (Joel Yliluoma)](http://bisqwit.iki.fi/story/howto/dither/jy) + +- Color Distance Formulas + + [Calculator + Info](http://colorizer.org/) + + 1. Euclidean Distance + 2. Manhattan Distance + 3. CIE94 Distance + - [Source Code (Iulius Curt)](https://github.com/iuliux/CIE94.js) + 4. CIEDE2000 + - [Math and Test Data Table (PDF)](http://www.ece.rochester.edu/~gsharma/ciede2000/ciede2000noteCRNA.pdf) + - [Info](http://www.ece.rochester.edu/~gsharma/ciede2000/) + - [Source Code (Greg Fiumara)](https://github.com/gfiumara/CIEDE2000) `C` + - [Source Code (THEjoezack)](https://github.com/THEjoezack/ColorMine/blob/master/ColorMine/ColorSpaces/Comparisons/CieDe2000Comparison.cs) `C#` + - [Online Calculator](http://colormine.org/delta-e-calculator/cie2000) + 5. Euclidean Distance w/o Alpha (RGBQuant) + 6. Euclidean Distance w/o sRGB coefficients (Xiaolin Wu Quant) + 7. Manhattan Distance w/o sRGB coefficients (NeuQuant) + 8. [CMetric](http://www.compuphase.com/cmetric.htm) `DRAFT!` + +- Color conversion formulas + + 1. [Pseudo-code](http://www.easyrgb.com/?X=MATH) + +> Be sure to fix rgb2xyz/xyz2lab. Issue is with strange part of code: `r = r > 0.04045 ? ...`. Check http://en.wikipedia.org/wiki/Lab_color_space + +- Image Quality Assessment + + 1. [SSIM info](http://en.wikipedia.org/wiki/Structural_similarity) + 2. [SSIM (Rhys-e)](https://github.com/rhys-e/structural-similarity) `Java` `License: MIT` + 3. PSNR ? TBD + 4. MSE ? TBD + +- Other + + 1. [HUSL (Boronine) - info](http://www.husl-colors.org) + 2. [HUSL (Boronine) - code](https://github.com/husl-colors/husl) + 3. [Color Image Quantization for Frame Buffer Display](https://www.cs.cmu.edu/~ph/ciq_thesis) + 4. [K-Means](http://arxiv.org/pdf/1101.0395.pdf) + 5. [Efficient Color Quantization by Hierarchical Clustering Algorithms](ftp://cs.joensuu.fi/pub/Theses/2005_MSc_Hautamaki_Ville.pdf) + 6. http://www.codeproject.com/Articles/66341/A-Simple-Yet-Quite-Powerful-Palette-Quantizer-in-C + +## License + +[MIT](LICENSE) diff --git a/node_modules/image-q/node_modules/@types/node/LICENSE b/node_modules/image-q/node_modules/@types/node/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/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/image-q/node_modules/@types/node/README.md b/node_modules/image-q/node_modules/@types/node/README.md new file mode 100644 index 00000000..46cc81d0 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Thu, 09 Sep 2021 20:01:20 GMT + * Dependencies: none + * Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require` + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Minh Son Nguyen](https://github.com/nguymin4), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Surasak Chaisurin](https://github.com/Ryan-Willpower), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Jason Kwok](https://github.com/JasonHK), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), and [wafuwafu13](https://github.com/wafuwafu13). diff --git a/node_modules/image-q/node_modules/@types/node/assert.d.ts b/node_modules/image-q/node_modules/@types/node/assert.d.ts new file mode 100644 index 00000000..19f1e7de --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/assert.d.ts @@ -0,0 +1,912 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/assert.js) + */ +declare module 'assert' { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * tracker.report(); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new () => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison) ( `==` ). `NaN` is special handled + * and treated as being identical in case both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison)(`!=` ). `NaN` is special handled and treated as + * being identical in case both + * sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(obj1); + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text' + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text' + * } + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * } + * ); + * + * // Using regular expressions to validate error properties: + * throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text' + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i + * } + * ); + * + * // Fails due to the different `message` and `name` properties: + * throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/ + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error' + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops' + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: Omit & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module 'node:assert' { + import assert = require('assert'); + export = assert; +} diff --git a/node_modules/image-q/node_modules/@types/node/assert/strict.d.ts b/node_modules/image-q/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 00000000..b4319b97 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module 'assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} +declare module 'node:assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} diff --git a/node_modules/image-q/node_modules/@types/node/async_hooks.d.ts b/node_modules/image-q/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 00000000..157bea9f --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,497 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/async_hooks.js) + */ +declare module 'async_hooks' { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'fs'; + * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * } + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { } + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `async_hooks` module,`AsyncLocalStorage` should be preferred as it is a performant and memory safe + * implementation that involves significant optimizations that are non-obvious to + * implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'http'; + * import { AsyncLocalStorage } from 'async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function or + * the asynchronous operations created within the callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module 'node:async_hooks' { + export * from 'async_hooks'; +} diff --git a/node_modules/image-q/node_modules/@types/node/buffer.d.ts b/node_modules/image-q/node_modules/@types/node/buffer.d.ts new file mode 100644 index 00000000..9bf8ff9b --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2142 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/buffer.js) + */ +declare module 'buffer' { + import { BinaryLike } from 'node:crypto'; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' | 'binary'; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new (size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0 + * @experimental + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): unknown; // pending web streams types + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + global { + // Buffer class + type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new (str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new (arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: ReadonlyArray): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new (buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | ReadonlyArray): Buffer; + from(data: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: 'string'): string; + }, + encoding?: BufferEncoding + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`,`Buffer.from(array)`, `Buffer.concat()`, and the + * deprecated`new Buffer(size)` constructor only when `size` is less than or equal + * to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created + * if `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: 'Buffer'; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare(target: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This is the same behavior as `buf.subarray()`. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * ``` + * @since v0.3.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.slice()`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0 + * @deprecated Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0 + * @deprecated Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + } +} +declare module 'node:buffer' { + export * from 'buffer'; +} diff --git a/node_modules/image-q/node_modules/@types/node/child_process.d.ts b/node_modules/image-q/node_modules/@types/node/child_process.d.ts new file mode 100644 index 00000000..66540c39 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1355 @@ +/** + * The `child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if it is in the `options` object. Otherwise, `process.env.PATH` is + * used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `child_process` module provides a handful of synchronous + * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/child_process.js) + */ +declare module 'child_process' { + import { ObjectEncodingOptions } from 'node:fs'; + import { EventEmitter, Abortable } from 'node:events'; + import * as net from 'node:net'; + import { Writable, Readable, Stream, Pipe } from 'node:stream'; + import { URL } from 'node:url'; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel currently exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ] + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See[`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if[`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'] + * } + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on + * a `'message'` event instead of `'connection'` and using `server.bind()` instead + * of `server.listen()`. This is, however, currently only supported on Unix + * platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: 'spawn', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'message', message: Serializable, sendHandle: SendHandle): boolean; + emit(event: 'spawn', listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: 'spawn', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: 'spawn', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: 'spawn', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: 'spawn', listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio extends ChildProcess { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = 'overlapped' | 'pipe' | 'ignore' | 'inherit'; + type StdioOptions = IOType | Array; + type SerializationType = 'json' | 'advanced'; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = 'inherit' | 'ignore' | Stream; + type StdioPipeNamed = 'pipe' | 'overlapped'; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, + * retrieve it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on[shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const exec = util.promisify(require('child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = ExecException & NodeJS.ErrnoException; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const execFile = util.promisify(require('child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile(file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: 'buffer' | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: 'buffer' | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; +} +declare module 'node:child_process' { + export * from 'child_process'; +} diff --git a/node_modules/image-q/node_modules/@types/node/cluster.d.ts b/node_modules/image-q/node_modules/@types/node/cluster.d.ts new file mode 100644 index 00000000..8c4203b6 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,414 @@ +/** + * A single instance of Node.js runs in a single thread. To take advantage of + * multi-core systems, the user will sometimes want to launch a cluster of Node.js + * processes to handle the load. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/cluster.js) + */ +declare module 'cluster' { + import * as child from 'node:child_process'; + import EventEmitter = require('node:events'); + import * as net from 'node:net'; + export interface ClusterSettings { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | 'udp4' | 'udp6'; // 4, 6, -1, "udp4", "udp6" + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the`id`. + * + * While a worker is alive, this is the key that indexes it in`cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using `child_process.fork()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary this sends a message to a specific worker. It is identical to `ChildProcess.send()`. + * + * In a worker this sends a message to the primary. It is identical to`process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * This function will kill the worker. In the primary, it does this + * by disconnecting the `worker.process`, and once disconnected, killing + * with `signal`. In the worker, it does it by disconnecting the channel, + * and then exiting with code `0`. + * + * Because `kill()` attempts to gracefully disconnect the worker process, it is + * susceptible to waiting indefinitely for the disconnect to complete. For example, + * if the worker enters an infinite loop, a graceful disconnect will never occur. + * If the graceful disconnect behavior is not needed, use `worker.process.kill()`. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * This method is aliased as `worker.destroy()` for backward compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is `kill()`. + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.kill()` or`.disconnect()`. If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'exit', listener: (code: number, signal: string) => void): this; + addListener(event: 'listening', listener: (address: Address) => void): this; + addListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'exit', code: number, signal: string): boolean; + emit(event: 'listening', address: Address): boolean; + emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'exit', listener: (code: number, signal: string) => void): this; + on(event: 'listening', listener: (address: Address) => void): this; + on(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'exit', listener: (code: number, signal: string) => void): this; + once(event: 'listening', listener: (address: Address) => void): this; + once(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependListener(event: 'listening', listener: (address: Address) => void): this; + prependListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'online', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependOnceListener(event: 'listening', listener: (address: Address) => void): this; + prependOnceListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'online', listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: (worker: Worker) => void): this; + addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: 'fork', listener: (worker: Worker) => void): this; + addListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + addListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: (worker: Worker) => void): this; + addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect', worker: Worker): boolean; + emit(event: 'exit', worker: Worker, code: number, signal: string): boolean; + emit(event: 'fork', worker: Worker): boolean; + emit(event: 'listening', worker: Worker, address: Address): boolean; + emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online', worker: Worker): boolean; + emit(event: 'setup', settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: (worker: Worker) => void): this; + on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: 'fork', listener: (worker: Worker) => void): this; + on(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + on(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: (worker: Worker) => void): this; + on(event: 'setup', listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: (worker: Worker) => void): this; + once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: 'fork', listener: (worker: Worker) => void): this; + once(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + once(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: (worker: Worker) => void): this; + once(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: 'fork', listener: (worker: Worker) => void): this; + prependListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'message', listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void): this; + prependListener(event: 'online', listener: (worker: Worker) => void): this; + prependListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: 'online', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module 'node:cluster' { + export * from 'cluster'; + export { default as default } from 'cluster'; +} diff --git a/node_modules/image-q/node_modules/@types/node/console.d.ts b/node_modules/image-q/node_modules/@types/node/console.d.ts new file mode 100644 index 00000000..60a5294f --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/console.d.ts @@ -0,0 +1,407 @@ +/** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/console.js) + */ +declare module 'console' { + import console = require('node:console'); + export = console; +} +declare module 'node:console' { + import { InspectOptions } from 'node:util'; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation`length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See `util.format()` for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can’t be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: ReadonlyArray): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | 'auto' | undefined; + inspectOptions?: InspectOptions | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new (options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/node_modules/image-q/node_modules/@types/node/constants.d.ts b/node_modules/image-q/node_modules/@types/node/constants.d.ts new file mode 100644 index 00000000..208020dc --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/constants.d.ts @@ -0,0 +1,18 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module 'constants' { + import { constants as osConstants, SignalConstants } from 'node:os'; + import { constants as cryptoConstants } from 'node:crypto'; + import { constants as fsConstants } from 'node:fs'; + + const exp: typeof osConstants.errno & + typeof osConstants.priority & + SignalConstants & + typeof cryptoConstants & + typeof fsConstants; + export = exp; +} + +declare module 'node:constants' { + import constants = require('constants'); + export = constants; +} diff --git a/node_modules/image-q/node_modules/@types/node/crypto.d.ts b/node_modules/image-q/node_modules/@types/node/crypto.d.ts new file mode 100644 index 00000000..8b7c1a30 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,3243 @@ +/** + * The `crypto` module provides cryptographic functionality that includes a set of + * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * + * ```js + * const { createHmac } = await import('crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/crypto.js) + */ +declare module 'crypto' { + import * as stream from 'node:stream'; + import { PeerCertificate } from 'node:tls'; + interface Certificate { + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + const Certificate: Certificate & { + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + new (): Certificate; + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + (): Certificate; + /** + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + }; + namespace constants { + // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const ALPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = 'base64' | 'hex'; + type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1'; + type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2'; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid'; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = 'secret' | 'public' | 'private'; + interface KeyExportOptions { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<'pem'>): string | Buffer; + export(options?: KeyExportOptions<'der'>): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of[`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an[initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of[`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an[initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions): DecipherCCM; + function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions): DecipherGCM; + function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; + passphrase?: string | Buffer | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'spki' | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey + * } = await import('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: 'hmac' | 'aes', + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void + ): void; + interface JsonWebKeyInput { + key: JsonWebKey; + format: 'jwk'; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = 'der' | 'ieee-p1363'; + interface SigningOptions { + /** + * @See crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1' + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, outputFormat: BinaryToTextEncoding): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createDiffieHellman + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `constants`module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in[RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The + * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman + * } = await import('crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellman; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2 + * } = await import('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync + * } = await import('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 248. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt + * } = await import('crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt + * } = await import('crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void; + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync + * } = await import('crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves + * } = await import('crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * ```js + * const { + * getHashes + * } = await import('crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createECDH + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH + * } = await import('crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: 'latin1' | 'hex' | 'base64', + format?: 'uncompressed' | 'compressed' | 'hybrid' + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or[capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; + type KeyFormat = 'pem' | 'der'; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, + * Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync + * } = await import('crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, + * Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair + * } = await import('crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + namespace generateKeyPair { + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts'; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdf + * } = await import('crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf(digest: string, irm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdfSync + * } = await import('crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync(digest: string, ikm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0 + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject: 'always' | 'never'; + /** + * @default true + */ + wildcards: boolean; + /** + * @default true + */ + partialWildcards: boolean; + /** + * @default false + */ + multiLabelWildcards: boolean; + /** + * @default false + */ + singleLabelSubdomains: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (ca) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * @since v15.6.0 + */ + readonly subjectAltName: string; + /** + * The information access content of this certificate. + * @since v15.6.0 + */ + readonly infoAccess: string; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * @since v15.6.0 + * @return Returns `name` if the certificate matches, `undefined` if it does not. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [<bigint>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [<bigint>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + namespace webcrypto { + class CryptoKey {} // placeholder + } +} +declare module 'node:crypto' { + export * from 'crypto'; +} diff --git a/node_modules/image-q/node_modules/@types/node/dgram.d.ts b/node_modules/image-q/node_modules/@types/node/dgram.d.ts new file mode 100644 index 00000000..72751d6a --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,545 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/dgram.js) + */ +declare module 'dgram' { + import { AddressInfo } from 'node:net'; + import * as dns from 'node:dns'; + import { EventEmitter, Abortable } from 'node:events'; + interface RemoteInfo { + address: string; + family: 'IPv4' | 'IPv6'; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = 'udp4' | 'udp6'; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: ((hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void) | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'cluster'; + * import dgram from 'dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family` and `port`properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: () => void): void; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): void; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise falsy, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send(msg: string | Uint8Array | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to[IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): void; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): void; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): void; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no addition effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'message', msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + } +} +declare module 'node:dgram' { + export * from 'dgram'; +} diff --git a/node_modules/image-q/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/image-q/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 00000000..c27846ba --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,128 @@ +/** + * The `diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/diagnostics_channel.js) + */ +declare module 'diagnostics_channel' { + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string): boolean; + /** + * This is the primary entry-point for anyone wanting to interact with a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @param name The channel name + * @return The named channel object + */ + function channel(name: string): Channel; + type ChannelListener = (name: string, message: unknown) => void; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is use to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + */ + class Channel { + readonly name: string; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + */ + readonly hasSubscribers: boolean; + private constructor(name: string); + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @param onMessage The previous subscribed handler to remove + */ + unsubscribe(onMessage: ChannelListener): void; + } +} +declare module 'node:diagnostics_channel' { + export * from 'diagnostics_channel'; +} diff --git a/node_modules/image-q/node_modules/@types/node/dns.d.ts b/node_modules/image-q/node_modules/@types/node/dns.d.ts new file mode 100644 index 00000000..c34f4c17 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/dns.d.ts @@ -0,0 +1,643 @@ +/** + * The `dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the `Implementation considerations section` for more information. + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/dns.js) + */ +declare module 'dns' { + import * as dnsPromises from 'node:dns/promises'; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses, and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the `Implementation considerations section` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * @since v0.1.90 + */ + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On an error, `err` is an `Error` object, where `err.code` is the error code. + * + * ```js + * const dns = require('dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: 'A'; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: 'AAAA'; + } + export interface CaaRecord { + critial: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: 'MX'; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: 'NAPTR'; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: 'SOA'; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: 'SRV'; + } + export interface AnyTxtRecord { + type: 'TXT'; + entries: string[]; + } + export interface AnyNsRecord { + type: 'NS'; + value: string; + } + export interface AnyPtrRecord { + type: 'PTR'; + value: string; + } + export interface AnyCnameRecord { + type: 'CNAME'; + value: string; + } + export type AnyRecord = AnyARecord | AnyAaaaRecord | AnyCnameRecord | AnyMxRecord | AnyNaptrRecord | AnyNsRecord | AnyPtrRecord | AnySoaRecord | AnySrvRecord | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'A', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'AAAA', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'ANY', callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'CNAME', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'MX', callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NAPTR', callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NS', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'PTR', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'SOA', callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: 'SRV', callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'TXT', callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: 'A' | 'AAAA' | 'CNAME' | 'NS' | 'PTR'): Promise; + function __promisify__(hostname: string, rrtype: 'ANY'): Promise; + function __promisify__(hostname: string, rrtype: 'MX'): Promise; + function __promisify__(hostname: string, rrtype: 'NAPTR'): Promise; + function __promisify__(hostname: string, rrtype: 'SOA'): Promise; + function __promisify__(hostname: string, rrtype: 'SRV'): Promise; + function __promisify__(hostname: string, rrtype: 'TXT'): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0 + */ + export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC + * 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an `Error` object, where `err.code` is + * one of the `DNS error codes`. + * @since v0.1.16 + */ + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like[resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of `RFC 5952` formatted addresses + */ + export function setServers(servers: ReadonlyArray): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default, and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module 'node:dns' { + export * from 'dns'; +} diff --git a/node_modules/image-q/node_modules/@types/node/dns/promises.d.ts b/node_modules/image-q/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 00000000..9ce3fd2e --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,357 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('dns').promises` or `require('dns/promises')`. + * @since v10.6.0 + */ +declare module 'dns/promises' { + import { + LookupAddress, + LookupOneOptions, + LookupAllOptions, + LookupOptions, + AnyRecord, + CaaRecord, + MxRecord, + NaptrRecord, + SoaRecord, + SrvRecord, + ResolveWithTtlOptions, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + } from 'node:dns'; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses, and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the `Implementation considerations section` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: 'A'): Promise; + function resolve(hostname: string, rrtype: 'AAAA'): Promise; + function resolve(hostname: string, rrtype: 'ANY'): Promise; + function resolve(hostname: string, rrtype: 'CAA'): Promise; + function resolve(hostname: string, rrtype: 'CNAME'): Promise; + function resolve(hostname: string, rrtype: 'MX'): Promise; + function resolve(hostname: string, rrtype: 'NAPTR'): Promise; + function resolve(hostname: string, rrtype: 'NS'): Promise; + function resolve(hostname: string, rrtype: 'PTR'): Promise; + function resolve(hostname: string, rrtype: 'SOA'): Promise; + function resolve(hostname: string, rrtype: 'SRV'): Promise; + function resolve(hostname: string, rrtype: 'TXT'): Promise; + function resolve(hostname: string, rrtype: string): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like[resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: ReadonlyArray): void; + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module 'node:dns/promises' { + export * from 'dns/promises'; +} diff --git a/node_modules/image-q/node_modules/@types/node/domain.d.ts b/node_modules/image-q/node_modules/@types/node/domain.d.ts new file mode 100644 index 00000000..7b3018e5 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/domain.d.ts @@ -0,0 +1,169 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should**not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/domain.js) + */ +declare module 'domain' { + import EventEmitter = require('node:events'); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and lowlevel requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('domain'); + * const fs = require('fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module 'node:domain' { + export * from 'domain'; +} diff --git a/node_modules/image-q/node_modules/@types/node/events.d.ts b/node_modules/image-q/node_modules/@types/node/events.d.ts new file mode 100644 index 00000000..97c70551 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/events.d.ts @@ -0,0 +1,623 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * const EventEmitter = require('events'); + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/events.js) + */ +declare module 'events' { + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + interface DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + } + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('events'); + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter { + constructor(options?: EventEmitterOptions); + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform[EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once(emitter: NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise; + static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * const { on, EventEmitter } = require('events'); + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on(emitter: NodeJS.EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('events'); + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0 + */ + static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted, therefore the process will still crash if no + * regular `'error'` listener is installed. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + static defaultMaxListeners: number; + } + import internal = require('node:events'); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + } + global { + namespace NodeJS { + interface EventEmitter { + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and_before_ the last listener finishes execution will + * not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(event?: string | symbol): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: string | symbol): Function[]; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * const EventEmitter = require('events'); + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to the event named `eventName`. + * @since v3.2.0 + * @param eventName The name of the event being listened for + */ + listenerCount(eventName: string | symbol): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the_beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * const EventEmitter = require('events'); + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array; + } + } + } + export = EventEmitter; +} +declare module 'node:events' { + import events = require('events'); + export = events; +} diff --git a/node_modules/image-q/node_modules/@types/node/fs.d.ts b/node_modules/image-q/node_modules/@types/node/fs.d.ts new file mode 100644 index 00000000..d50eadec --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/fs.d.ts @@ -0,0 +1,3723 @@ +/** + * The `fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/fs.js) + */ +declare module 'fs' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import { URL } from 'node:url'; + import * as promises from 'node:fs/promises'; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | 'buffer' + | { + encoding: 'buffer'; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'close', listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'close', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'close', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function stat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: TDescriptor, options?: undefined): Stats; + ( + path: TDescriptor, + options?: StatOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + } + ): Stats | undefined; + ( + path: TDescriptor, + options: StatOptions & { + bigint: true; + throwIfNoEntry: false; + } + ): BigIntStats | undefined; + ( + path: TDescriptor, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Stats; + ( + path: TDescriptor, + options: StatOptions & { + bigint: true; + } + ): BigIntStats; + ( + path: TDescriptor, + options: StatOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + } + ): Stats | BigIntStats; + (path: TDescriptor, options?: StatOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function fstat(fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export const fstatSync: StatSyncFn; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function lstat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX[`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than a + * possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX[`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If + * the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './example/mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` in the `example` which points + * to `mew` in the same directory: + * + * ```bash + * $ tree example/ + * example/ + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + */ + export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = 'dir' | 'file' | 'junction'; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode soperations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err, [path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. + * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs'; + * + * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from 'fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | 'buffer' + | { + encoding: 'buffer'; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer', + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | 'buffer' + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by[this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. If `buffer` is a normal object, it + * must have an own `toString` function property. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @return The number of bytes written. + */ + export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; + export type ReadPosition = number | bigint; + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param [buffer=Buffer.alloc(16384)] The buffer that the data will be written to. + * @param [offset=0] The position in `buffer` to write the data to. + * @param [length=buffer.byteLength] The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + } + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): string | Buffer; + export type WriteFileOptions = + | (ObjectEncodingOptions & + Abortable & { + mode?: Mode | undefined; + flag?: string | undefined; + }) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; + } + /** + * Returns `undefined`. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile(path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * ```js + * import { appendFileSync } from 'fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync(path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtime` and `prev.mtime`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | { + persistent?: boolean | undefined; + interval?: number | undefined; + } + | undefined, + listener: (curr: Stats, prev: Stats) => void + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | 'buffer' | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = 'rename' | 'change'; + export type WatchListener = (event: WatchEventType, filename: T) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer', + listener?: WatchListener + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options?: WatchOptions | BufferEncoding | null, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: WatchOptions | string, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won’t be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file exists in the current directory, and if it is writable. + * access(file, constants.F_OK | constants.W_OK, (err) => { + * if (err) { + * console.error( + * `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`); + * } else { + * console.log(`${file} exists, and it is writable`); + * } + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. Check `File access constants` for + * possible values of `mode`. It is possible to create a mask consisting of + * the bitwise OR of two or more values + * (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + /** + * @default false + */ + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadStreamOptions extends StreamOptions { + end?: number | undefined; + } + /** + * Unlike the 16 kb default `highWaterMark` for a readable stream, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed, like most `Readable` streams. Set the `emitClose` option to`false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * overrides for `open`, `read`, and `close` are required. + * + * ```js + * import { createReadStream } from 'fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + * @return See `Readable Stream`. + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than replacing + * it may require the `flags` option to be set to `r+` rather than the default `w`. + * The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed, like most `Writable` streams. Set the `emitClose` option to`false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for `open`,`close`, and at least one of `write` and `writev` are required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + * @return See `Writable Stream`. + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | StreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX[`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX[`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + */ + export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function writev( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + */ + export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function readv( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; + export interface OpenDirOptions { + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: string, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export namespace opendir { + function __promisify__(path: string, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + throwIfNoEntry?: boolean | undefined; + } + export interface CopyOptions { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp(source: string, destination: string, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function cp(source: string, destination: string, opts: CopyOptions, callback: (err: NodeJS.ErrnoException | null) => void): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string, destination: string, opts?: CopyOptions): void; +} +declare module 'node:fs' { + export * from 'fs'; +} diff --git a/node_modules/image-q/node_modules/@types/node/fs/promises.d.ts b/node_modules/image-q/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 00000000..ea65b7dc --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,997 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module 'fs/promises' { + import { Abortable } from 'node:events'; + import { Stream } from 'node:stream'; + import { + Stats, + BigIntStats, + StatOptions, + WriteVResult, + ReadVResult, + PathLike, + RmDirOptions, + RmOptions, + MakeDirectoryOptions, + Dirent, + OpenDirOptions, + Dir, + ObjectEncodingOptions, + BufferEncodingOption, + OpenMode, + Mode, + WatchOptions, + WatchEventType, + CopyOptions, + } from 'node:fs'; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX[`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fufills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param [offset=0] The location in the buffer at which to start filling. + * @param [length=buffer.byteLength] The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read(buffer: T, offset?: number | null, length?: number | null, position?: number | null): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + } + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then resolves the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, or an object with an own `toString` function + * property. The promise is resolved with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode & Abortable) | BufferEncoding | null): Promise; + /** + * Write `buffer` to the file. + * + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * The promise is resolved with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). For this + * scenario, use `fs.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param [offset=0] The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength] The number of bytes from `buffer` to write. + * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. + * See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [<ArrayBufferView>](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView)s to the file. + * + * The promise is resolved with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be resolved (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param position The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: ReadonlyArray, position?: number): Promise; + /** + * Read from a file and write to an array of [<ArrayBufferView>](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView)s + * @since v13.13.0, v12.17.0 + * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: ReadonlyArray, position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If the accessibility check is successful, the promise is resolved with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [<Error>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access } from 'fs/promises'; + * import { constants } from 'fs'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by[this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX[`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * resolved with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX[`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html)documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a `Buffer`, or, an object with an own (not inherited)`toString` function property. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs/promises'; + * import { Buffer } from 'buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: string | NodeJS.ArrayBufferView | Iterable | AsyncIterable | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | (ObjectEncodingOptions & + Abortable & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX[`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: string, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer' + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: WatchOptions | string): AsyncIterable> | AsyncIterable>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string, destination: string, opts?: CopyOptions): Promise; +} +declare module 'node:fs/promises' { + export * from 'fs/promises'; +} diff --git a/node_modules/image-q/node_modules/@types/node/globals.d.ts b/node_modules/image-q/node_modules/@types/node/globals.d.ts new file mode 100644 index 00000000..ae974db7 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/globals.d.ts @@ -0,0 +1,284 @@ +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + +// For backwards compability +interface NodeRequire extends NodeJS.Require { } +interface RequireResolve extends NodeJS.RequireResolve { } +interface NodeModule extends NodeJS.Module { } + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +/** + * Only available if `--expose-gc` is passed to the process. + */ +declare var gc: undefined | (() => void); + +//#region borrowed +// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib +/** A controller object that allows you to abort one or more DOM requests as and when desired. */ +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ +interface AbortSignal { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; + // TODO: Add abort() static +}; +//#endregion borrowed + +//#region ArrayLike.at() +interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; +} +interface String extends RelativeIndexable {} +interface Array extends RelativeIndexable {} +interface Int8Array extends RelativeIndexable {} +interface Uint8Array extends RelativeIndexable {} +interface Uint8ClampedArray extends RelativeIndexable {} +interface Int16Array extends RelativeIndexable {} +interface Uint16Array extends RelativeIndexable {} +interface Int32Array extends RelativeIndexable {} +interface Uint32Array extends RelativeIndexable {} +interface Float32Array extends RelativeIndexable {} +interface Float64Array extends RelativeIndexable {} +interface BigInt64Array extends RelativeIndexable {} +interface BigUint64Array extends RelativeIndexable {} +//#endregion ArrayLike.at() end + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): void; + end(data: string | Uint8Array, cb?: () => void): void; + end(str: string, encoding?: BufferEncoding, cb?: () => void): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined; }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + '.js': (m: Module, filename: string) => any; + '.json': (m: Module, filename: string) => any; + '.node': (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } +} diff --git a/node_modules/image-q/node_modules/@types/node/globals.global.d.ts b/node_modules/image-q/node_modules/@types/node/globals.global.d.ts new file mode 100644 index 00000000..ef1198c0 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/node_modules/image-q/node_modules/@types/node/http.d.ts b/node_modules/image-q/node_modules/@types/node/http.d.ts new file mode 100644 index 00000000..4f012531 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/http.d.ts @@ -0,0 +1,1358 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'mysite.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'mysite.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/http.js) + */ +declare module 'http' { + import * as stream from 'node:stream'; + import { URL } from 'node:url'; + import { Socket, Server as NetServer } from 'node:net'; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + 'accept-language'?: string | undefined; + 'accept-patch'?: string | undefined; + 'accept-ranges'?: string | undefined; + 'access-control-allow-credentials'?: string | undefined; + 'access-control-allow-headers'?: string | undefined; + 'access-control-allow-methods'?: string | undefined; + 'access-control-allow-origin'?: string | undefined; + 'access-control-expose-headers'?: string | undefined; + 'access-control-max-age'?: string | undefined; + 'access-control-request-headers'?: string | undefined; + 'access-control-request-method'?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + 'alt-svc'?: string | undefined; + authorization?: string | undefined; + 'cache-control'?: string | undefined; + connection?: string | undefined; + 'content-disposition'?: string | undefined; + 'content-encoding'?: string | undefined; + 'content-language'?: string | undefined; + 'content-length'?: string | undefined; + 'content-location'?: string | undefined; + 'content-range'?: string | undefined; + 'content-type'?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + 'if-match'?: string | undefined; + 'if-modified-since'?: string | undefined; + 'if-none-match'?: string | undefined; + 'if-unmodified-since'?: string | undefined; + 'last-modified'?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + 'proxy-authenticate'?: string | undefined; + 'proxy-authorization'?: string | undefined; + 'public-key-pins'?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + 'retry-after'?: string | undefined; + 'sec-websocket-accept'?: string | undefined; + 'sec-websocket-extensions'?: string | undefined; + 'sec-websocket-key'?: string | undefined; + 'sec-websocket-protocol'?: string | undefined; + 'sec-websocket-version'?: string | undefined; + 'set-cookie'?: string[] | undefined; + 'strict-transport-security'?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + 'transfer-encoding'?: string | undefined; + upgrade?: string | undefined; + 'user-agent'?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + 'www-authenticate'?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict {} + interface ClientRequestArgs { + abort?: AbortSignal | undefined; + protocol?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + family?: number | undefined; + port?: number | string | null | undefined; + defaultPort?: number | string | undefined; + localAddress?: string | undefined; + socketPath?: string | undefined; + /** + * @default 8192 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + headers?: OutgoingHttpHeaders | undefined; + auth?: string | null | undefined; + agent?: Agent | boolean | undefined; + _defaultAgent?: Agent | undefined; + timeout?: number | undefined; + setHost?: boolean | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined; + } + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage | undefined; + ServerResponse?: typeof ServerResponse | undefined; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 8192 + */ + maxHeaderSize?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when true. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + } + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + /** + * @since v0.1.17 + */ + class Server extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * In case of inactivity, the rules defined in `server.timeout` apply. However, + * that inactivity based timeout would still allow the connection to be kept open + * if the headers are being sent very slowly (by default, up to a byte per 2 + * minutes). In order to prevent this, whenever header data arrives an additional + * check is made that more than `server.headersTimeout` milliseconds has not + * passed since the connection was established. If the check fails, a `'timeout'`event is emitted on the server object, and (by default) the socket is destroyed. + * See `server.timeout` for more information on how timeout behavior can be + * customized. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: RequestListener): this; + addListener(event: 'checkExpectation', listener: RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + addListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: RequestListener): this; + addListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; + emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'upgrade', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: RequestListener): this; + on(event: 'checkExpectation', listener: RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: RequestListener): this; + once(event: 'checkExpectation', listener: RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + once(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: 'request', listener: RequestListener): this; + once(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: RequestListener): this; + prependListener(event: 'checkExpectation', listener: RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from + * the perspective of the participants of HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: IncomingMessage; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Aliases of `outgoingMessage.socket` + * @since v0.3.0 + * @deprecated Since v15.12.0 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * occurs, Same as binding to the `timeout` event. + * + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value for the header object. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | ReadonlyArray): this; + /** + * Gets the value of HTTP header with the given name. If such a name doesn't + * exist in message, it will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript Object. This means that + * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.0.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array of names of headers of the outgoing outgoingMessage. All + * names are lowercase. + * @since v8.0.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v8.0.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Compulsorily flushes the message headers + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + constructor(req: IncomingMessage); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends a HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain' + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0 + */ + getRawHeaderNames(): string[]; + addListener(event: 'abort', listener: () => void): this; + addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'continue', listener: () => void): this; + addListener(event: 'information', listener: (info: InformationEvent) => void): this; + addListener(event: 'response', listener: (response: IncomingMessage) => void): this; + addListener(event: 'socket', listener: (socket: Socket) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'abort', listener: () => void): this; + on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'continue', listener: () => void): this; + on(event: 'information', listener: (info: InformationEvent) => void): this; + on(event: 'response', listener: (response: IncomingMessage) => void): this; + on(event: 'socket', listener: (socket: Socket) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'abort', listener: () => void): this; + once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'continue', listener: () => void): this; + once(event: 'information', listener: (info: InformationEvent) => void): this; + once(event: 'response', listener: (response: IncomingMessage) => void): this; + once(event: 'socket', listener: (socket: Socket) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'abort', listener: () => void): this; + prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'continue', listener: () => void): this; + prependListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependListener(event: 'socket', listener: (socket: Socket) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'abort', listener: () => void): this; + prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'continue', listener: () => void): this; + prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST' + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket`. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with '; '. + * * For all other headers, the values are joined together with ', '. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.headers.host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.headers.host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): void; + } + interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: 'fifo' | 'lifo' | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ + class Agent { + /** + * By default set to 256\. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * @since v0.1.13 + */ + function createServer(requestListener?: RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const http = require('http'); + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!' + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData) + * } + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request itself. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the + * response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!' + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module 'node:http' { + export * from 'http'; +} diff --git a/node_modules/image-q/node_modules/@types/node/http2.d.ts b/node_modules/image-q/node_modules/@types/node/http2.d.ts new file mode 100644 index 00000000..bf0ae2d4 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2100 @@ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/http2.js) + */ +declare module 'http2' { + import EventEmitter = require('node:events'); + import * as fs from 'node:fs'; + import * as net from 'node:net'; + import * as stream from 'node:stream'; + import * as tls from 'node:tls'; + import * as url from 'node:url'; + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; + export { OutgoingHttpHeaders } from 'node:http'; + export interface IncomingHttpStatusHeader { + ':status'?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ':path'?: string | undefined; + ':method'?: string | undefined; + ':authority'?: string | undefined; + ':scheme'?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set the `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: 'aborted', listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'streamClosed', listener: (code: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'wantTrailers', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted'): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'frameError', frameType: number, errorCode: number): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: 'streamClosed', code: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'trailers', trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'wantTrailers'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: 'streamClosed', listener: (code: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'wantTrailers', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: 'streamClosed', listener: (code: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'wantTrailers', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'streamClosed', listener: (code: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'wantTrailers', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'streamClosed', listener: (code: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'wantTrailers', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: 'continue', listener: () => {}): this; + addListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'continue'): boolean; + emit(event: 'headers', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: 'push', headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'response', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'continue', listener: () => {}): this; + on(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'continue', listener: () => {}): this; + once(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'continue', listener: () => {}): this; + prependListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'continue', listener: () => {}): this; + prependOnceListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.log(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: NodeJS.ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings(settings: Settings): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: 'localSettings', listener: (settings: Settings) => void): this; + addListener(event: 'ping', listener: () => void): this; + addListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'frameError', frameType: number, errorCode: number, streamID: number): boolean; + emit(event: 'goaway', errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: 'localSettings', settings: Settings): boolean; + emit(event: 'ping'): boolean; + emit(event: 'remoteSettings', settings: Settings): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: 'localSettings', listener: (settings: Settings) => void): this; + on(event: 'ping', listener: () => void): this; + on(event: 'remoteSettings', listener: (settings: Settings) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: 'localSettings', listener: (settings: Settings) => void): this; + once(event: 'ping', listener: () => void): this; + once(event: 'remoteSettings', listener: (settings: Settings) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'ping', listener: () => void): this; + prependListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'ping', listener: () => void): this; + prependOnceListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: 'origin', listener: (origins: string[]) => void): this; + addListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'altsvc', alt: string, origin: string, stream: number): boolean; + emit(event: 'origin', origins: ReadonlyArray): boolean; + emit(event: 'connect', session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + on(event: 'origin', listener: (origins: string[]) => void): this; + on(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + once(event: 'origin', listener: (origins: string[]) => void): this; + once(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: 'origin', listener: (origins: string[]) => void): this; + prependListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: 'origin', listener: (origins: string[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'connect', session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: 'http:' | 'https:' | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'unknownProtocol', socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + readonly url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted', hadError: boolean, code: number): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'end'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 request object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ''; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): void; + end(data: string | Uint8Array, callback?: () => void): void; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): void; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | ReadonlyArray): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses_must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support[unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem') + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect(authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void + ): ClientHttp2Session; +} +declare module 'node:http2' { + export * from 'http2'; +} diff --git a/node_modules/image-q/node_modules/@types/node/https.d.ts b/node_modules/image-q/node_modules/@types/node/https.d.ts new file mode 100644 index 00000000..4b740178 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/https.d.ts @@ -0,0 +1,391 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/https.js) + */ +declare module 'https' { + import { Duplex } from 'node:stream'; + import * as tls from 'node:tls'; + import * as http from 'node:http'; + import { URL } from 'node:url'; + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = http.RequestOptions & + tls.SecureContextOptions & { + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor(options: ServerOptions, requestListener?: http.RequestListener); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Duplex) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: http.RequestListener): this; + addListener(event: 'checkExpectation', listener: http.RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + addListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: tls.TLSSocket): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Duplex): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'checkExpectation', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: Duplex): boolean; + emit(event: 'connect', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + emit(event: 'request', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'upgrade', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Duplex) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: http.RequestListener): this; + on(event: 'checkExpectation', listener: http.RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + on(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Duplex) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: http.RequestListener): this; + once(event: 'checkExpectation', listener: http.RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + once(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: http.RequestListener): this; + prependListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: http.RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample' + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer(requestListener?: http.RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET' + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('tls'); + * const https = require('https'); + * const crypto = require('crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha25 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} +declare module 'node:https' { + export * from 'https'; +} diff --git a/node_modules/image-q/node_modules/@types/node/index.d.ts b/node_modules/image-q/node_modules/@types/node/index.d.ts new file mode 100644 index 00000000..9636fae7 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/index.d.ts @@ -0,0 +1,132 @@ +// Type definitions for non-npm package Node.js 16.9 +// Project: https://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Hannes Magnusson +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Minh Son Nguyen +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Surasak Chaisurin +// Piotr Błażejewicz +// Anna Henningsen +// Jason Kwok +// Victor Perin +// Yongsheng Zhang +// NodeJS Contributors +// Linus Unnebäck +// wafuwafu13 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support NodeJS and TypeScript 3.7+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/node_modules/image-q/node_modules/@types/node/inspector.d.ts b/node_modules/image-q/node_modules/@types/node/inspector.d.ts new file mode 100644 index 00000000..0317192e --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2738 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +// tslint:disable:max-line-length + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the[Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help see https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help see https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +declare module 'node:inspector' { + import EventEmitter = require('inspector'); + export = EventEmitter; +} diff --git a/node_modules/image-q/node_modules/@types/node/module.d.ts b/node_modules/image-q/node_modules/@types/node/module.d.ts new file mode 100644 index 00000000..d83aec94 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/module.d.ts @@ -0,0 +1,114 @@ +/** + * @since v0.3.7 + */ +declare module 'module' { + import { URL } from 'node:url'; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line number and column number in the generated source file, returns + * an object representing the position in the original file. The object returned + * consists of the following keys: + */ + findEntry(line: number, column: number): SourceMapping; + } + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static Module: typeof Module; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + export = Module; +} +declare module 'node:module' { + import module = require('module'); + export = module; +} diff --git a/node_modules/image-q/node_modules/@types/node/net.d.ts b/node_modules/image-q/node_modules/@types/node/net.d.ts new file mode 100644 index 00000000..a704b5f3 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/net.d.ts @@ -0,0 +1,783 @@ +/** + * > Stability: 2 - Stable + * + * The `net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/net.js) + */ +declare module 'net' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import * as dns from 'node:dns'; + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will_not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`,`socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort: number; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): void; + end(buffer: Uint8Array | string, callback?: () => void): void; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (hadError: boolean) => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'data', listener: (data: Buffer) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'timeout', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', hadError: boolean): boolean; + emit(event: 'connect'): boolean; + emit(event: 'data', data: Buffer): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'lookup', err: Error, address: string, family: string | number, host: string): boolean; + emit(event: 'ready'): boolean; + emit(event: 'timeout'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (hadError: boolean) => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'data', listener: (data: Buffer) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'timeout', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (hadError: boolean) => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'data', listener: (data: Buffer) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'timeout', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (hadError: boolean) => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'data', listener: (data: Buffer) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (hadError: boolean) => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'data', listener: (data: Buffer) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.log('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will_not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + } + type IPVersion = 'ipv4' | 'ipv6'; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of an TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```console + * $ telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```console + * $ nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Tests if input is an IP address. Returns `0` for invalid strings, + * returns `4` for IP version 4 addresses, and returns `6` for IP version 6 + * addresses. + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if input is a version 4 IP address, otherwise returns `false`. + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if input is a version 6 IP address, otherwise returns `false`. + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0 + */ + readonly port: number; + /** + * @since v15.14.0 + */ + readonly flowlabel: number; + } +} +declare module 'node:net' { + export * from 'net'; +} diff --git a/node_modules/image-q/node_modules/@types/node/os.d.ts b/node_modules/image-q/node_modules/@types/node/os.d.ts new file mode 100644 index 00000000..000fa5e4 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/os.d.ts @@ -0,0 +1,455 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/os.js) + */ +declare module 'os' { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: 'IPv4'; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: 'IPv6'; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20 + * } + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling[`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. + * See[https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: 'buffer' }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling[`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See[https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform. The value is set + * at compile time. Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): 'BE' | 'LE'; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module 'node:os' { + export * from 'os'; +} diff --git a/node_modules/image-q/node_modules/@types/node/package.json b/node_modules/image-q/node_modules/@types/node/package.json new file mode 100644 index 00000000..9319db34 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/package.json @@ -0,0 +1,235 @@ +{ + "name": "@types/node", + "version": "16.9.1", + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft", + "githubUsername": "Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped", + "githubUsername": "DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno", + "githubUsername": "jkomyno" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis", + "githubUsername": "alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya", + "githubUsername": "r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg", + "githubUsername": "btoueg" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89", + "githubUsername": "smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy", + "githubUsername": "touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas", + "githubUsername": "DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs", + "githubUsername": "eyqs" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK", + "githubUsername": "Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29", + "githubUsername": "hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin", + "githubUsername": "kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff", + "githubUsername": "ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude", + "githubUsername": "islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk", + "githubUsername": "mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1", + "githubUsername": "mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e", + "githubUsername": "n-e" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin", + "githubUsername": "galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs", + "githubUsername": "parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon", + "githubUsername": "eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick", + "githubUsername": "SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH", + "githubUsername": "ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker", + "githubUsername": "WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3", + "githubUsername": "wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela", + "githubUsername": "samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein", + "githubUsername": "kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy", + "githubUsername": "bhongy" + }, + { + "name": "Marcin Kopacz", + "url": "https://github.com/chyzwar", + "githubUsername": "chyzwar" + }, + { + "name": "Trivikram Kamat", + "url": "https://github.com/trivikr", + "githubUsername": "trivikr" + }, + { + "name": "Minh Son Nguyen", + "url": "https://github.com/nguymin4", + "githubUsername": "nguymin4" + }, + { + "name": "Junxiao Shi", + "url": "https://github.com/yoursunny", + "githubUsername": "yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "url": "https://github.com/qwelias", + "githubUsername": "qwelias" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss", + "githubUsername": "ExE-Boss" + }, + { + "name": "Surasak Chaisurin", + "url": "https://github.com/Ryan-Willpower", + "githubUsername": "Ryan-Willpower" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz", + "githubUsername": "peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax", + "githubUsername": "addaleax" + }, + { + "name": "Jason Kwok", + "url": "https://github.com/JasonHK", + "githubUsername": "JasonHK" + }, + { + "name": "Victor Perin", + "url": "https://github.com/victorperin", + "githubUsername": "victorperin" + }, + { + "name": "Yongsheng Zhang", + "url": "https://github.com/ZYSzys", + "githubUsername": "ZYSzys" + }, + { + "name": "NodeJS Contributors", + "url": "https://github.com/NodeJS", + "githubUsername": "NodeJS" + }, + { + "name": "Linus Unnebäck", + "url": "https://github.com/LinusU", + "githubUsername": "LinusU" + }, + { + "name": "wafuwafu13", + "url": "https://github.com/wafuwafu13", + "githubUsername": "wafuwafu13" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "2d4a0159d689896e5538afa996ef597df6922b3b716729c273148522b74b9f6c", + "typeScriptVersion": "3.7" +} \ No newline at end of file diff --git a/node_modules/image-q/node_modules/@types/node/path.d.ts b/node_modules/image-q/node_modules/@types/node/path.d.ts new file mode 100644 index 00000000..58712bef --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/path.d.ts @@ -0,0 +1,172 @@ +declare module 'path/posix' { + import path = require('path'); + export = path; +} +declare module 'path/win32' { + import path = require('path'); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/path.js) + */ +declare module 'path' { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + isAbsolute(p: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + parse(p: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + format(pP: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module 'node:path' { + import path = require('path'); + export = path; +} diff --git a/node_modules/image-q/node_modules/@types/node/perf_hooks.d.ts b/node_modules/image-q/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 00000000..02f330c7 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,555 @@ +/** + * This module provides an implementation of a subset of the W3C[Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * + * ```js + * const { PerformanceObserver, performance } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/perf_hooks.js) + */ +declare module 'perf_hooks' { + import { AsyncResource } from 'node:async_hooks'; + type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly details?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()`. + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string, options?: MarkOptions): void; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark?: string, endMark?: string): void; + measure(name: string, options: MeasureOptions): void; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called three times synchronously. `list` contains one item. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: ReadonlyArray; + } + | { + type: EntryType; + } + ): void; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * + * ## Examples + * @since v15.9.0 + */ + recordDelta(): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; +} +declare module 'node:perf_hooks' { + export * from 'perf_hooks'; +} diff --git a/node_modules/image-q/node_modules/@types/node/process.d.ts b/node_modules/image-q/node_modules/@types/node/process.d.ts new file mode 100644 index 00000000..1f0d144a --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/process.d.ts @@ -0,0 +1,1477 @@ +declare module 'process' { + import * as tty from 'node:tty'; + import { Worker } from 'node:worker_threads'; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; + type Signals = + | 'SIGABRT' + | 'SIGALRM' + | 'SIGBUS' + | 'SIGCHLD' + | 'SIGCONT' + | 'SIGFPE' + | 'SIGHUP' + | 'SIGILL' + | 'SIGINT' + | 'SIGIO' + | 'SIGIOT' + | 'SIGKILL' + | 'SIGPIPE' + | 'SIGPOLL' + | 'SIGPROF' + | 'SIGPWR' + | 'SIGQUIT' + | 'SIGSEGV' + | 'SIGSTKFLT' + | 'SIGSTOP' + | 'SIGSYS' + | 'SIGTERM' + | 'SIGTRAP' + | 'SIGTSTP' + | 'SIGTTIN' + | 'SIGTTOU' + | 'SIGUNUSED' + | 'SIGURG' + | 'SIGUSR1' + | 'SIGUSR2' + | 'SIGVTALRM' + | 'SIGWINCH' + | 'SIGXCPU' + | 'SIGXFSZ' + | 'SIGBREAK' + | 'SIGLOST' + | 'SIGINFO'; + type UncaughtExceptionOrigin = 'uncaughtException' | 'unhandledRejection'; + type MultipleResolveType = 'resolve' | 'reject'; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: unknown) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @defaul false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread’s `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit_before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. + */ + exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid(): number; + /** + * The `process.setgid()` method sets the group identity of the process. (See[`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid(id: number | string): void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid(): number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See[`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid(id: number | string): void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid(): number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid(id: number | string): void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid(): number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid(id: number | string): void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups(): number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups(groups: ReadonlyArray): void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `Object` containing the JavaScript + * representation of the configure options used to compile the current Node.js + * executable. This is the same as the `config.gypi` file that was produced when + * running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * ```js + * import { arch } from 'process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: string; + /** + * The `process.platform` property returns a string identifying the operating + * system platform on which the Node.js process is running. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js[is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be`undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: 'beforeExit', listener: BeforeExitListener): this; + addListener(event: 'disconnect', listener: DisconnectListener): this; + addListener(event: 'exit', listener: ExitListener): this; + addListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + addListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + addListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + addListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + addListener(event: 'warning', listener: WarningListener): this; + addListener(event: 'message', listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + addListener(event: 'worker', listener: WorkerListener): this; + emit(event: 'beforeExit', code: number): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'exit', code: number): boolean; + emit(event: 'rejectionHandled', promise: Promise): boolean; + emit(event: 'uncaughtException', error: Error): boolean; + emit(event: 'uncaughtExceptionMonitor', error: Error): boolean; + emit(event: 'unhandledRejection', reason: unknown, promise: Promise): boolean; + emit(event: 'warning', warning: Error): boolean; + emit(event: 'message', message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: 'multipleResolves', type: MultipleResolveType, promise: Promise, value: unknown): this; + emit(event: 'worker', listener: WorkerListener): this; + on(event: 'beforeExit', listener: BeforeExitListener): this; + on(event: 'disconnect', listener: DisconnectListener): this; + on(event: 'exit', listener: ExitListener): this; + on(event: 'rejectionHandled', listener: RejectionHandledListener): this; + on(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + on(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + on(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + on(event: 'warning', listener: WarningListener): this; + on(event: 'message', listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: 'multipleResolves', listener: MultipleResolveListener): this; + on(event: 'worker', listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'beforeExit', listener: BeforeExitListener): this; + once(event: 'disconnect', listener: DisconnectListener): this; + once(event: 'exit', listener: ExitListener): this; + once(event: 'rejectionHandled', listener: RejectionHandledListener): this; + once(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + once(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + once(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + once(event: 'warning', listener: WarningListener): this; + once(event: 'message', listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: 'multipleResolves', listener: MultipleResolveListener): this; + once(event: 'worker', listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependListener(event: 'disconnect', listener: DisconnectListener): this; + prependListener(event: 'exit', listener: ExitListener): this; + prependListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependListener(event: 'warning', listener: WarningListener): this; + prependListener(event: 'message', listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependListener(event: 'worker', listener: WorkerListener): this; + prependOnceListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependOnceListener(event: 'disconnect', listener: DisconnectListener): this; + prependOnceListener(event: 'exit', listener: ExitListener): this; + prependOnceListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependOnceListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependOnceListener(event: 'warning', listener: WarningListener): this; + prependOnceListener(event: 'message', listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependOnceListener(event: 'worker', listener: WorkerListener): this; + listeners(event: 'beforeExit'): BeforeExitListener[]; + listeners(event: 'disconnect'): DisconnectListener[]; + listeners(event: 'exit'): ExitListener[]; + listeners(event: 'rejectionHandled'): RejectionHandledListener[]; + listeners(event: 'uncaughtException'): UncaughtExceptionListener[]; + listeners(event: 'uncaughtExceptionMonitor'): UncaughtExceptionListener[]; + listeners(event: 'unhandledRejection'): UnhandledRejectionListener[]; + listeners(event: 'warning'): WarningListener[]; + listeners(event: 'message'): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: 'multipleResolves'): MultipleResolveListener[]; + listeners(event: 'worker'): WorkerListener[]; + } + } + } + export = process; +} +declare module 'node:process' { + import process = require('process'); + export = process; +} diff --git a/node_modules/image-q/node_modules/@types/node/punycode.d.ts b/node_modules/image-q/node_modules/@types/node/punycode.d.ts new file mode 100644 index 00000000..5854d674 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/punycode.js) + */ +declare module 'punycode' { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a[Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492)encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: ReadonlyArray): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module 'node:punycode' { + export * from 'punycode'; +} diff --git a/node_modules/image-q/node_modules/@types/node/querystring.d.ts b/node_modules/image-q/node_modules/@types/node/querystring.d.ts new file mode 100644 index 00000000..ce6e60cf --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,131 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('querystring'); + * ``` + * + * The `querystring` API is considered Legacy. While it is still maintained, + * new code should use the `URLSearchParams` API instead. + * @deprecated Legacy + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/querystring.js) + */ +declare module 'querystring' { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | null> {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [<number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [<bigint>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [<string\[\]>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [<number\[\]>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [<bigint\[\]>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [<boolean\[\]>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module 'node:querystring' { + export * from 'querystring'; +} diff --git a/node_modules/image-q/node_modules/@types/node/readline.d.ts b/node_modules/image-q/node_modules/@types/node/readline.d.ts new file mode 100644 index 00000000..0f0706a6 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/readline.d.ts @@ -0,0 +1,542 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. It can be accessed + * using: + * + * ```js + * const readline = require('readline'); + * ``` + * + * The following simple example illustrates the basic use of the `readline` module. + * + * ```js + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * + * rl.question('What do you think of Node.js? ', (answer) => { + * // TODO: Log the answer in a database + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * }); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/readline.js) + */ +declare module 'readline' { + import { Abortable, EventEmitter } from 'node:events'; + interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' ') + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `readline.Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `readline.Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'history', listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'history', history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'history', listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'history', listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'history', listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'history', listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + type ReadLine = Interface; // type forwarded for backwards compatibility + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; + type CompleterResult = [string[], string]; + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * process.stdin.unref(); + * ``` + * @since v0.1.98 + */ + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * @since v0.7.7 + */ + function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + type Direction = -1 | 0 | 1; + interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given `TTY` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module 'node:readline' { + export * from 'readline'; +} diff --git a/node_modules/image-q/node_modules/@types/node/repl.d.ts b/node_modules/image-q/node_modules/@types/node/repl.d.ts new file mode 100644 index 00000000..053d9778 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/repl.d.ts @@ -0,0 +1,424 @@ +/** + * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that + * is available both as a standalone program or includible in other applications. + * It can be accessed using: + * + * ```js + * const repl = require('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/repl.js) + */ +declare module 'repl' { + import { Interface, Completer, AsyncCompleter } from 'node:readline'; + import { Context } from 'node:vm'; + import { InspectOptions } from 'node:util'; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * } + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (*without* a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'exit', listener: () => void): this; + addListener(event: 'reset', listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'exit'): boolean; + emit(event: 'reset', context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'exit', listener: () => void): this; + on(event: 'reset', listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'exit', listener: () => void): this; + once(event: 'reset', listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'exit', listener: () => void): this; + prependListener(event: 'reset', listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'exit', listener: () => void): this; + prependOnceListener(event: 'reset', listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module 'node:repl' { + export * from 'repl'; +} diff --git a/node_modules/image-q/node_modules/@types/node/stream.d.ts b/node_modules/image-q/node_modules/@types/node/stream.d.ts new file mode 100644 index 00000000..9fdf3bdb --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1218 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/stream.js) + */ +declare module 'stream' { + import { EventEmitter, Abortable } from 'node:events'; + import * as streamPromises from 'node:stream/promises'; + import * as streamConsumers from 'node:stream/consumers'; + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + } + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0 + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method pulls some data out of the internal buffer and + * returns it. If no data available to be read, `null` is returned. By default, + * the data will be returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.match(/\n\n/)) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * } else { + * // Still reading the header. + * header += str; + * } + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `stream` module API + * as it is currently defined. (See `Compatibility` for more information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): void; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'pause'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?(this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * It is recommended that once `write()` returns false, no more chunks be written + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): void; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, it is recommended that calls to `writable.uncork()` be + * deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): void; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'unpipe', src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from(src: Stream | Blob | ArrayBuffer | string | Iterable | AsyncIterable | AsyncGeneratorFunction | Promise | Object): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): void; + cork(): void; + uncork(): void; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * + * ```js + * const fs = require('fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides promise version: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | ((source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable : S) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends PipelineTransformSource + ? NodeJS.WritableStream | PipelineDestinationIterableFunction | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends PipelineDestinationPromiseFunction + ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal: AbortSignal; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * } + * ); + * ``` + * + * The `pipeline` API provides a promise version, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const options = { + * signal: ac.signal, + * }; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * options, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield chunk.toUpperCase(); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)> + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module 'node:stream' { + import stream = require('stream'); + export = stream; +} diff --git a/node_modules/image-q/node_modules/@types/node/stream/consumers.d.ts b/node_modules/image-q/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 00000000..ce6c9bb7 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,24 @@ +// Duplicates of interface in lib.dom.ts. +// Duplicated here rather than referencing lib.dom.ts because doing so causes lib.dom.ts to be loaded for "test-all" +// Which in turn causes tests to pass that shouldn't pass. +// +// This interface is not, and should not be, exported. +interface Blob { + readonly size: number; + readonly type: string; + arrayBuffer(): Promise; + slice(start?: number, end?: number, contentType?: string): Blob; + stream(): NodeJS.ReadableStream; + text(): Promise; +} +declare module 'stream/consumers' { + import { Readable } from 'node:stream'; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; +} +declare module 'node:stream/consumers' { + export * from 'stream/consumers'; +} diff --git a/node_modules/image-q/node_modules/@types/node/stream/promises.d.ts b/node_modules/image-q/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 00000000..b427073d --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,42 @@ +declare module 'stream/promises' { + import { FinishedOptions, PipelineSource, PipelineTransform, PipelineDestination, PipelinePromise, PipelineOptions } from 'node:stream'; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + function pipeline, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module 'node:stream/promises' { + export * from 'stream/promises'; +} diff --git a/node_modules/image-q/node_modules/@types/node/stream/web.d.ts b/node_modules/image-q/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 00000000..a9d75c19 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,6 @@ +declare module 'stream/web' { + // stub module, pending copy&paste from .d.ts or manual impl +} +declare module 'node:stream/web' { + export * from 'stream/web'; +} diff --git a/node_modules/image-q/node_modules/@types/node/string_decoder.d.ts b/node_modules/image-q/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 00000000..f12aa98f --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `string_decoder` module provides an API for decoding `Buffer` objects into + * strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/string_decoder.js) + */ +declare module 'string_decoder' { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module 'node:string_decoder' { + export * from 'string_decoder'; +} diff --git a/node_modules/image-q/node_modules/@types/node/timers.d.ts b/node_modules/image-q/node_modules/@types/node/timers.d.ts new file mode 100644 index 00000000..3f3bacea --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/timers.d.ts @@ -0,0 +1,94 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/timers.js) + */ +declare module 'timers' { + import { Abortable } from 'node:events'; + import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } from 'node:timers/promises'; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + interface Immediate extends RefCounted { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + } + interface Timeout extends Timer { + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + } + } + function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module 'node:timers' { + export * from 'timers'; +} diff --git a/node_modules/image-q/node_modules/@types/node/timers/promises.d.ts b/node_modules/image-q/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 00000000..fd778880 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,68 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module 'timers/promises' { + import { TimerOptions } from 'node:timers'; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; +} +declare module 'node:timers/promises' { + export * from 'timers/promises'; +} diff --git a/node_modules/image-q/node_modules/@types/node/tls.d.ts b/node_modules/image-q/node_modules/@types/node/tls.d.ts new file mode 100644 index 00000000..8d523b4e --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1019 @@ +/** + * The `tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/tls.js) + */ +declare module 'tls' { + import { X509Certificate } from 'node:crypto'; + import * as net from 'node:net'; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: NodeJS.Dict; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + fingerprint256: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * Returns `true` if the peer certificate was signed by one of the CAs specified + * when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: boolean; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * See[SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html)for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See[SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html)for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * Note: The format of the output is identical to the output of `openssl s_client -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's`SSL_trace()` function, the format is + * undocumented, can change without notice, + * and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + addListener(event: 'secureConnect', listener: () => void): this; + addListener(event: 'session', listener: (session: Buffer) => void): this; + addListener(event: 'keylog', listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'OCSPResponse', response: Buffer): boolean; + emit(event: 'secureConnect'): boolean; + emit(event: 'session', session: Buffer): boolean; + emit(event: 'keylog', line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + on(event: 'secureConnect', listener: () => void): this; + on(event: 'session', listener: (session: Buffer) => void): this; + on(event: 'keylog', listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + once(event: 'secureConnect', listener: () => void): this; + once(event: 'session', listener: (session: Buffer) => void): this; + once(event: 'keylog', listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependListener(event: 'secureConnect', listener: () => void): this; + prependListener(event: 'session', listener: (session: Buffer) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependOnceListener(event: 'secureConnect', listener: () => void): this; + prependOnceListener(event: 'session', listener: (session: Buffer) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: TLSSocket): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + interface SecureContextOptions { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use + * openssl dhparam to create the parameters. The key length must be + * greater than or equal to 1024 bits or else an error will be thrown. + * Although 1024 bits is permissible, use 2048 bits or larger for + * stronger security. If omitted or invalid, the parameters are + * silently discarded and DHE ciphers will not be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [<Error>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [<undefined>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function can be overwritten by providing alternative function as part of + * the `options.checkServerIdentity` option passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ] + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair(context?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + /** + * {@link createServer} sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * + * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using[Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of {@link createSecureContext}. + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: ReadonlyArray; +} +declare module 'node:tls' { + export * from 'tls'; +} diff --git a/node_modules/image-q/node_modules/@types/node/trace_events.d.ts b/node_modules/image-q/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 00000000..67f3298a --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,161 @@ +/** + * The `trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. + * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be + * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `trace_events` module: + * + * ```js + * const trace_events = require('trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool)tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in `Worker` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/trace_events.js) + */ +declare module 'trace_events' { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + * @return . + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module 'node:trace_events' { + export * from 'trace_events'; +} diff --git a/node_modules/image-q/node_modules/@types/node/tty.d.ts b/node_modules/image-q/node_modules/@types/node/tty.d.ts new file mode 100644 index 00000000..e8cb2362 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/tty.d.ts @@ -0,0 +1,206 @@ +/** + * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. + * In most cases, it will not be necessary or possible to use this module directly. + * However, it can be accessed using: + * + * ```js + * const tty = require('tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/tty.js) + */ +declare module 'tty' { + import * as net from 'node:net'; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. Defaults to `false`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input characters.Ctrl+C will no longer cause a `SIGINT` when in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'resize', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'resize'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'resize', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'resize', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'resize', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'resize', listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 + * + * colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module 'node:tty' { + export * from 'tty'; +} diff --git a/node_modules/image-q/node_modules/@types/node/url.d.ts b/node_modules/image-q/node_modules/@types/node/url.d.ts new file mode 100644 index 00000000..fe07ea4b --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/url.d.ts @@ -0,0 +1,798 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/url.js) + */ +declare module 'url' { + import { Blob } from 'node:buffer'; + import { ClientRequestArgs } from 'node:http'; + import { ParsedUrlQuery, ParsedUrlQueryInput } from 'node:querystring'; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a Web browser resolving an anchor tag HREF. + * + * ```js + * const url = require('url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * You can achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param from The Base URL being resolved against. + * @param to The HREF URL being resolved. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject` s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: Blob): string; + /** + * Removes the stored `Blob` identified by the given ID. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(objectUrl: string): void; + constructor(input: string, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myUrl.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myUrl.searchParams.sort(); + * + * console.log(myUrl.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a`URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | NodeJS.Dict> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach(callback: (this: TThis, value: string, name: string, searchParams: this) => void, thisArg?: TThis): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} +declare module 'node:url' { + export * from 'url'; +} diff --git a/node_modules/image-q/node_modules/@types/node/util.d.ts b/node_modules/image-q/node_modules/@types/node/util.d.ts new file mode 100644 index 00000000..b8cb07e2 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/util.d.ts @@ -0,0 +1,1564 @@ +/** + * The `util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/util.js) + */ +declare module 'util' { + import * as types from 'node:util/types'; + export interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean | undefined; + showHidden?: boolean | undefined; + /** + * @default 2 + */ + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number | undefined; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * + * @since v16.8.0 + */ + export function toUSVString(string: string): string; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]) + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same[`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('util'); + * const assert = require('assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]) + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1] + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }) + * ); + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('util'); + * const EventEmitter = require('events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && err.hasOwnProperty('reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param original An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + const custom: unique symbol; + } + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/)`TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder('shift_jis'); + * let string = ''; + * let buffer; + * while (buffer = getNextChunkSomehow()) { + * string += decoder.decode(buffer, { stream: true }); + * } + * string += decoder.decode(); // end-of-stream + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + } + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + } + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/)`TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } +} +declare module 'util/types' { + export * from 'util/types'; +} +declare module 'util/types' { + import { KeyObject, webcrypto } from 'node:crypto'; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) + * or[`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)views, such as typed array + * objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent + * to[`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap(object: T | {}): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet(object: T | {}): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in[`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module 'node:util' { + export * from 'util'; +} +declare module 'node:util/types' { + export * from 'util/types'; +} diff --git a/node_modules/image-q/node_modules/@types/node/v8.d.ts b/node_modules/image-q/node_modules/@types/node/v8.d.ts new file mode 100644 index 00000000..35e233dc --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/v8.d.ts @@ -0,0 +1,378 @@ +/** + * The `v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/)built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/v8.js) + */ +declare module 'v8' { + import { Readable } from 'node:stream'; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8[`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running`node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream containing the V8 heap snapshot + */ + function getHeapSnapshot(): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * ```js + * const { writeHeapSnapshot } = require('v8'); + * const { + * Worker, + * isMainThread, + * parentPort + * } = require('worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string): string; + /** + * Returns an object with the following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794 + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer’s internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before`.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer’s internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v12.22.0 + */ + function stopCoverage(): void; +} +declare module 'node:v8' { + export * from 'v8'; +} diff --git a/node_modules/image-q/node_modules/@types/node/vm.d.ts b/node_modules/image-q/node_modules/@types/node/vm.d.ts new file mode 100644 index 00000000..48d1fc89 --- /dev/null +++ b/node_modules/image-q/node_modules/@types/node/vm.d.ts @@ -0,0 +1,508 @@ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. **The `vm` module is not a security mechanism. Do** + * **not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/vm.js) + */ +declare module 'vm' { + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean | undefined; + timeout?: number | undefined; + cachedData?: Buffer | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + type MeasureMemoryMode = 'summary' | 'detailed'; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + context?: Context | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions); + /** + * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('vm'); + * + * const context = { + * animal: 'cat', + * count: 2 + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but_does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, + * the `contextObject` will be the global object, retaining all of its existing + * properties but also having the built-in objects and functions any standard[global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables + * will remain unchanged. + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all `\n```\n\n## How to use\n\nPlease refer to [API Documentation and Usage](http://ibezkrovnyi.github.io/image-quantization/)\n\n## Breaking changes\n\n#### 2.1.1\n\n + PaletteQuantizer#quantize => PaletteQuantizer#quantizeSync\n + ImageQuantizer#quantize => ImageQuantizer#quantizeSync\n\n#### 2.0.1 - 2.0.4 (2018-02-22)\n\n + EuclideanRgbQuantWOAlpha => EuclideanBT709NoAlpha\n + EuclideanRgbQuantWithAlpha => EuclideanBT709\n \t+ ManhattanSRGB => ManhattanBT709\n \t+ IImageDitherer => AbstractImageQuantizer\n \t+ IPaletteQuantizer => AbstractPaletteQuantizer\n \t+ PointContainer.fromNodeCanvas => PointContainer.fromHTMLCanvasElement\n \t+ PointContainer.fromArray => PointContainer.fromUint8Array\n + PointContainer.fromBuffer (Node.js, new)\n \t+ CMETRIC => CMetric\n \t+ PNGQUANT => PNGQuant\n \t+ SSIM Class => ssim function\n\n## TODO\n\n1. ~~notification about progress~~\n2. ~~riemersma dithering~~\n3. ordered dithering <-- is there anyone who needs it?\n4. readme update, more examples\n5. demo update (latest image-q npm version should be used in demo)\n\n## Changelog\n\n##### 4.0.0\n + Test cases for different types of imports and requres added\n\n##### 4.0.0-alpha\n + Try to solve exported bundle types problem. 'umd' bundle removed.\n\n##### 3.0.8\n + Test case for issue #95 added\n\n##### 3.0.7\n + Fixes #96: Fix minimumColorDistanceToDither (PR #97 by @pixelplanetdev)\n\n##### 3.0.6\n + Fixes #95: \"Always empty result in certain webpack / babel configs\" (PR #98)\n\n##### 3.0.4\n + Fixes issue \"Module not found: Can't resolve 'core-js/fn/set-immediate' in ...\"\n\n##### 3.0.0\n + pnpm monorepo, esbuild for faster builds, typescript upgraded\n\n##### 2.1.1\n\n + Basic (Simple) API implemented\n + see breaking changes\n\n##### 2.0.5 (2018-02-23)\n\n + @types/node moved to 'dependencies'\n\n##### 2.0.4 (2018-02-23)\n\n + documentation added\n + some refactorings/renames, see breaking changes\n\n##### 2.0.3 (2018-02-22)\n\n + circular dependency removed\n\n##### 2.0.2 (2018-02-22)\n\n + readme updated\n\n##### 2.0.1 (2018-02-22)\n\n + progress tracking api (using es6 generators) added\n + strinct lint rules (+code cleanup/renames)\n + rollup (3 different versions - umd, cjs, esm + source maps + d.ts)\n + latest TypeScript\n + jest\n + snapshot tests\n + coverage (+coveralls)\n + greenkeeper\n\n##### 1.1.1 (2016-08-28)\n\n + CIEDE2000 - incorrect calculation fixed\n + CIEDE2000 - alpha channel now has only 25% impact on color distance instead of 66%\n + CIE94 - added 2 types (textiles and graphics art) according to spec\n + CIE94 - alpha support added\n + rgb2xyz, lab2xyz, xyz2rgb, xyz2lab - gamma correction\n + lab2xyz, xyz2lab - refY should be 100 (1.00000) instead of 10 (0.10000)\n + manhattan with new (Nommyde) coefficients added\n + mocha tests added\n + webpack integration\n + image-q is now UMD module\n + travis-ci integration\n + typescript 2.0\n + indentation with 4 spaces\n\n##### 0.1.4 (2015-06-24)\n\n + Refactoring\n + Riemersma dithering added (Hilbert Curve)\n + Readme.md updated\n + build.cmd updated\n\n##### 0.1.3 (2015-06-16)\n\n + NeuQuant is fixed (again) according to original Anthony Dekker source code (all values should be integer)\n + Error Diffusion Dithering is now calculates error like XNVIEW\n + Refactoring\n\n##### 0.1.2 (2015-06-16)\n\n + Documentation generation fixed\n + File name case problem fixed\n\n##### 0.1.1 (2015-06-16)\n\n + Auto-generated documentation added\n + Refactoring\n\n##### 0.1.0 (2015-06-16)\n\n + Code cleanup, removed unnecessary files\n\n##### 0.0.5 (2015-06-16)\n\n + PNGQuant color distance added, need to check its quality\n + CIEDE2000 and CIE94 fixed for use in NeuQuant\n + NeuQuant is fixed according to original Anthony Dekker source code (all values should be integer)\n + Code refactoring and cleanup\n * We have some slowdown because of red/green/blue/alpha normalization according to white point per each calculateRaw/calculateNormalized call\n\n##### 0.0.4 (2015-06-15)\n\n + CIEDE2000 color distance equation optimized (original CIEDE2000 equation is available as class `CIEDE2000_Original`)\n\n##### 0.0.3b (2015-06-11)\n\n + CMetric color distance fixed\n\n##### 0.0.3a (2015-06-11)\n\n + Cleanup\n + Draft of CMetric color distance added\n\n##### 0.0.2 (2015-06-10)\n\n + rgb2xyz & xyz2lab fixed. CIEDE2000 works much better now.\n + CIE94 distance formula added. More investigation is needed.\n\n##### 0.0.1\n\n + Initial\n\n## Credits\n\nThanks to Leon Sorokin for information share and his original RGBQuant!\n\n## References\n\n- Palette Quantization Algorithms\n\n 1. [RGBQuant (Leon Sorokin)](https://github.com/leeoniya/RgbQuant.js) `JavaScript`\n 2. [NeuQuant (Johan Nordberg)](https://github.com/jnordberg/gif.js/blob/master/src/TypedNeuQuant.js) `TypeScript`\n 3. [NeuQuant (Tim Oxley)](https://github.com/timoxley/neuquant) `JavaScript`\n 4. [NeuQuant (Devon Govett)](https://github.com/devongovett/neuquant) `JavaScript`\n 5. [NeuQuant32 (Stuart Coyle)](https://github.com/stuart/pngnq/blob/master/src/neuquant32.c) `C`\n 6. [Xiaolin Wu (Xiaolin Wu)](http://www.ece.mcmaster.ca/~xwu/cq.c) `C`\n 7. [Xiaolin Wu (Smart-K8)](http://www.codeproject.com/Articles/66341/A-Simple-Yet-Quite-Powerful-Palette-Quantizer-in-C) `C#`\n 8. Xiaolin Wu w/ Alpha (Matt Wrock) [How to add Alpha](https://code.msdn.microsoft.com/windowsdesktop/Convert-32-bit-PNGs-to-81ef8c81/view/SourceCode#content), [Source Code](https://nquant.codeplex.com) `C#`\n 9. [MedianCut (mwcz)](https://github.com/mwcz/median-cut-js) `GPLv3`\n\n- Image Quantization Algorithms\n\n 1. [All (ImageMagik doc)](http://www.imagemagick.org/Usage/quantize/#dither)\n 2. [Error Diffusion dithering (Tanner Helland)](http://www.tannerhelland.com/4660/dithering-eleven-algorithms-source-code)\n 3. [Riemersma dithering](http://www.compuphase.com/riemer.htm) `TODO: Check License`\n 4. [Ordered dithering (Joel Yliluoma)](http://bisqwit.iki.fi/story/howto/dither/jy)\n\n- Color Distance Formulas\n\n [Calculator + Info](http://colorizer.org/)\n\n 1. Euclidean Distance\n 2. Manhattan Distance\n 3. CIE94 Distance\n - [Source Code (Iulius Curt)](https://github.com/iuliux/CIE94.js)\n 4. CIEDE2000\n - [Math and Test Data Table (PDF)](http://www.ece.rochester.edu/~gsharma/ciede2000/ciede2000noteCRNA.pdf)\n - [Info](http://www.ece.rochester.edu/~gsharma/ciede2000/)\n - [Source Code (Greg Fiumara)](https://github.com/gfiumara/CIEDE2000) `C`\n - [Source Code (THEjoezack)](https://github.com/THEjoezack/ColorMine/blob/master/ColorMine/ColorSpaces/Comparisons/CieDe2000Comparison.cs) `C#`\n - [Online Calculator](http://colormine.org/delta-e-calculator/cie2000)\n 5. Euclidean Distance w/o Alpha (RGBQuant)\n 6. Euclidean Distance w/o sRGB coefficients (Xiaolin Wu Quant)\n 7. Manhattan Distance w/o sRGB coefficients (NeuQuant)\n 8. [CMetric](http://www.compuphase.com/cmetric.htm) `DRAFT!`\n\n- Color conversion formulas\n\n 1. [Pseudo-code](http://www.easyrgb.com/?X=MATH)\n\n> Be sure to fix rgb2xyz/xyz2lab. Issue is with strange part of code: `r = r > 0.04045 ? ...`. Check http://en.wikipedia.org/wiki/Lab_color_space\n\n- Image Quality Assessment\n\n 1. [SSIM info](http://en.wikipedia.org/wiki/Structural_similarity)\n 2. [SSIM (Rhys-e)](https://github.com/rhys-e/structural-similarity) `Java` `License: MIT`\n 3. PSNR ? TBD\n 4. MSE ? TBD\n\n- Other\n\n 1. [HUSL (Boronine) - info](http://www.husl-colors.org)\n 2. [HUSL (Boronine) - code](https://github.com/husl-colors/husl)\n 3. [Color Image Quantization for Frame Buffer Display](https://www.cs.cmu.edu/~ph/ciq_thesis)\n 4. [K-Means](http://arxiv.org/pdf/1101.0395.pdf)\n 5. [Efficient Color Quantization by Hierarchical Clustering Algorithms](ftp://cs.joensuu.fi/pub/Theses/2005_MSc_Hautamaki_Ville.pdf)\n 6. http://www.codeproject.com/Articles/66341/A-Simple-Yet-Quite-Powerful-Palette-Quantizer-in-C\n\n## License\n\n[MIT](LICENSE)\n" +} \ No newline at end of file diff --git a/node_modules/image-q/src/basicAPI.ts b/node_modules/image-q/src/basicAPI.ts new file mode 100644 index 00000000..ce9015a6 --- /dev/null +++ b/node_modules/image-q/src/basicAPI.ts @@ -0,0 +1,287 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * helper.ts - part of Image Quantization Library + */ +import * as distance from './distance'; +import * as image from './image'; +import * as palette from './palette'; +import { AbstractDistanceCalculator } from './distance/distanceCalculator'; +import { PointContainer } from './utils/pointContainer'; +import { Palette } from './utils/palette'; + +const setImmediateImpl = + typeof setImmediate === 'function' + ? setImmediate + : typeof process !== 'undefined' && typeof process?.nextTick === 'function' + ? (callback: () => void) => process.nextTick(callback) + : (callback: () => void) => setTimeout(callback, 0); + +export type ColorDistanceFormula = + | 'cie94-textiles' + | 'cie94-graphic-arts' + | 'ciede2000' + | 'color-metric' + | 'euclidean' + | 'euclidean-bt709-noalpha' + | 'euclidean-bt709' + | 'manhattan' + | 'manhattan-bt709' + | 'manhattan-nommyde' + | 'pngquant'; + +export type PaletteQuantization = + | 'neuquant' + | 'neuquant-float' + | 'rgbquant' + | 'wuquant'; + +export type ImageQuantization = + | 'nearest' + | 'riemersma' + | 'floyd-steinberg' + | 'false-floyd-steinberg' + | 'stucki' + | 'atkinson' + | 'jarvis' + | 'burkes' + | 'sierra' + | 'two-sierra' + | 'sierra-lite'; + +export interface ProgressOptions { + onProgress?: (progress: number) => void; +} + +export interface ApplyPaletteOptions { + colorDistanceFormula?: ColorDistanceFormula; + imageQuantization?: ImageQuantization; +} + +export interface BuildPaletteOptions { + colorDistanceFormula?: ColorDistanceFormula; + paletteQuantization?: PaletteQuantization; + colors?: number; +} + +export function buildPaletteSync( + images: PointContainer[], + { + colorDistanceFormula, + paletteQuantization, + colors, + }: BuildPaletteOptions = {}, +) { + const distanceCalculator = + colorDistanceFormulaToColorDistance(colorDistanceFormula); + const paletteQuantizer = paletteQuantizationToPaletteQuantizer( + distanceCalculator, + paletteQuantization, + colors, + ); + images.forEach((image) => paletteQuantizer.sample(image)); + return paletteQuantizer.quantizeSync(); +} + +export async function buildPalette( + images: PointContainer[], + { + colorDistanceFormula, + paletteQuantization, + colors, + onProgress, + }: BuildPaletteOptions & ProgressOptions = {}, +) { + return new Promise((resolve, reject) => { + const distanceCalculator = + colorDistanceFormulaToColorDistance(colorDistanceFormula); + const paletteQuantizer = paletteQuantizationToPaletteQuantizer( + distanceCalculator, + paletteQuantization, + colors, + ); + images.forEach((image) => paletteQuantizer.sample(image)); + + let palette: Palette; + const iterator = paletteQuantizer.quantize(); + const next = () => { + try { + const result = iterator.next(); + if (result.done) { + resolve(palette); + } else { + if (result.value.palette) palette = result.value.palette; + if (onProgress) onProgress(result.value.progress); + setImmediateImpl(next); + } + } catch (error) { + reject(error); + } + }; + setImmediateImpl(next); + }); +} + +export function applyPaletteSync( + image: PointContainer, + palette: Palette, + { colorDistanceFormula, imageQuantization }: ApplyPaletteOptions = {}, +) { + const distanceCalculator = + colorDistanceFormulaToColorDistance(colorDistanceFormula); + const imageQuantizer = imageQuantizationToImageQuantizer( + distanceCalculator, + imageQuantization, + ); + return imageQuantizer.quantizeSync(image, palette); +} + +export async function applyPalette( + image: PointContainer, + palette: Palette, + { + colorDistanceFormula, + imageQuantization, + onProgress, + }: ApplyPaletteOptions & ProgressOptions = {}, +) { + return new Promise((resolve, reject) => { + const distanceCalculator = + colorDistanceFormulaToColorDistance(colorDistanceFormula); + const imageQuantizer = imageQuantizationToImageQuantizer( + distanceCalculator, + imageQuantization, + ); + + let outPointContainer: PointContainer; + const iterator = imageQuantizer.quantize(image, palette); + const next = () => { + try { + const result = iterator.next(); + if (result.done) { + resolve(outPointContainer); + } else { + if (result.value.pointContainer) { + outPointContainer = result.value.pointContainer; + } + if (onProgress) onProgress(result.value.progress); + setImmediateImpl(next); + } + } catch (error) { + reject(error); + } + }; + setImmediateImpl(next); + }); +} + +function colorDistanceFormulaToColorDistance( + colorDistanceFormula: ColorDistanceFormula = 'euclidean-bt709', +) { + switch (colorDistanceFormula) { + case 'cie94-graphic-arts': + return new distance.CIE94GraphicArts(); + case 'cie94-textiles': + return new distance.CIE94Textiles(); + case 'ciede2000': + return new distance.CIEDE2000(); + case 'color-metric': + return new distance.CMetric(); + case 'euclidean': + return new distance.Euclidean(); + case 'euclidean-bt709': + return new distance.EuclideanBT709(); + case 'euclidean-bt709-noalpha': + return new distance.EuclideanBT709NoAlpha(); + case 'manhattan': + return new distance.Manhattan(); + case 'manhattan-bt709': + return new distance.ManhattanBT709(); + case 'manhattan-nommyde': + return new distance.ManhattanNommyde(); + case 'pngquant': + return new distance.PNGQuant(); + default: + throw new Error(`Unknown colorDistanceFormula ${colorDistanceFormula}`); + } +} + +function imageQuantizationToImageQuantizer( + distanceCalculator: AbstractDistanceCalculator, + imageQuantization: ImageQuantization = 'floyd-steinberg', +) { + switch (imageQuantization) { + case 'nearest': + return new image.NearestColor(distanceCalculator); + case 'riemersma': + return new image.ErrorDiffusionRiemersma(distanceCalculator); + case 'floyd-steinberg': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.FloydSteinberg, + ); + case 'false-floyd-steinberg': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.FalseFloydSteinberg, + ); + case 'stucki': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.Stucki, + ); + case 'atkinson': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.Atkinson, + ); + case 'jarvis': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.Jarvis, + ); + case 'burkes': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.Burkes, + ); + case 'sierra': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.Sierra, + ); + case 'two-sierra': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.TwoSierra, + ); + case 'sierra-lite': + return new image.ErrorDiffusionArray( + distanceCalculator, + image.ErrorDiffusionArrayKernel.SierraLite, + ); + default: + throw new Error(`Unknown imageQuantization ${imageQuantization}`); + } +} + +function paletteQuantizationToPaletteQuantizer( + distanceCalculator: AbstractDistanceCalculator, + paletteQuantization: PaletteQuantization = 'wuquant', + colors = 256, +) { + switch (paletteQuantization) { + case 'neuquant': + return new palette.NeuQuant(distanceCalculator, colors); + case 'rgbquant': + return new palette.RGBQuant(distanceCalculator, colors); + case 'wuquant': + return new palette.WuQuant(distanceCalculator, colors); + case 'neuquant-float': + return new palette.NeuQuantFloat(distanceCalculator, colors); + default: + throw new Error(`Unknown paletteQuantization ${paletteQuantization}`); + } +} diff --git a/node_modules/image-q/src/constants/bt709.ts b/node_modules/image-q/src/constants/bt709.ts new file mode 100644 index 00000000..4bc11d7c --- /dev/null +++ b/node_modules/image-q/src/constants/bt709.ts @@ -0,0 +1,32 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * constants.ts - part of Image Quantization Library + */ + +/** + * sRGB (based on ITU-R Recommendation BT.709) + * http://en.wikipedia.org/wiki/SRGB + */ +export enum Y { + RED = 0.2126, + GREEN = 0.7152, + BLUE = 0.0722, + WHITE = 1, +} + +export enum x { + RED = 0.64, + GREEN = 0.3, + BLUE = 0.15, + WHITE = 0.3127, +} + +export enum y { + RED = 0.33, + GREEN = 0.6, + BLUE = 0.06, + WHITE = 0.329, +} diff --git a/node_modules/image-q/src/constants/index.ts b/node_modules/image-q/src/constants/index.ts new file mode 100644 index 00000000..54ce82ce --- /dev/null +++ b/node_modules/image-q/src/constants/index.ts @@ -0,0 +1,10 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * constants.ts - part of Image Quantization Library + */ +import * as bt709 from './bt709'; + +export { bt709 }; diff --git a/node_modules/image-q/src/conversion/index.ts b/node_modules/image-q/src/conversion/index.ts new file mode 100644 index 00000000..4ca6f8a0 --- /dev/null +++ b/node_modules/image-q/src/conversion/index.ts @@ -0,0 +1,14 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * iq.ts - Image Quantization Library + */ +export { rgb2xyz } from './rgb2xyz'; +export { rgb2hsl } from './rgb2hsl'; +export { rgb2lab } from './rgb2lab'; +export { lab2xyz } from './lab2xyz'; +export { lab2rgb } from './lab2rgb'; +export { xyz2lab } from './xyz2lab'; +export { xyz2rgb } from './xyz2rgb'; diff --git a/node_modules/image-q/src/conversion/lab2rgb.ts b/node_modules/image-q/src/conversion/lab2rgb.ts new file mode 100644 index 00000000..7f5b18b9 --- /dev/null +++ b/node_modules/image-q/src/conversion/lab2rgb.ts @@ -0,0 +1,14 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * lab2rgb.ts - part of Image Quantization Library + */ +import { lab2xyz } from './lab2xyz'; +import { xyz2rgb } from './xyz2rgb'; + +export function lab2rgb(L: number, a: number, b: number) { + const xyz = lab2xyz(L, a, b); + return xyz2rgb(xyz.x, xyz.y, xyz.z); +} diff --git a/node_modules/image-q/src/conversion/lab2xyz.ts b/node_modules/image-q/src/conversion/lab2xyz.ts new file mode 100644 index 00000000..81716e4a --- /dev/null +++ b/node_modules/image-q/src/conversion/lab2xyz.ts @@ -0,0 +1,26 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * lab2xyz.ts - part of Image Quantization Library + */ +const refX = 0.95047; // ref_X = 95.047 Observer= 2°, Illuminant = D65 +const refY = 1.0; // ref_Y = 100.000 +const refZ = 1.08883; // ref_Z = 108.883 + +function pivot(n: number) { + return n > 0.206893034 ? n ** 3 : (n - 16 / 116) / 7.787; +} + +export function lab2xyz(L: number, a: number, b: number) { + const y = (L + 16) / 116; + const x = a / 500 + y; + const z = y - b / 200; + + return { + x: refX * pivot(x), + y: refY * pivot(y), + z: refZ * pivot(z), + }; +} diff --git a/node_modules/image-q/src/conversion/rgb2hsl.ts b/node_modules/image-q/src/conversion/rgb2hsl.ts new file mode 100644 index 00000000..861c80ef --- /dev/null +++ b/node_modules/image-q/src/conversion/rgb2hsl.ts @@ -0,0 +1,40 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * rgb2hsl.ts - part of Image Quantization Library + */ +import { min3, max3 } from '../utils/arithmetic'; + +/** + * Calculate HSL from RGB + * Hue is in degrees [0..360] + * Lightness: [0..1] + * Saturation: [0..1] + * http://web.archive.org/web/20060914040436/http://local.wasp.uwa.edu.au/~pbourke/colour/hsl/ + */ +export function rgb2hsl(r: number, g: number, b: number) { + const min = min3(r, g, b); + const max = max3(r, g, b); + const delta = max - min; + const l = (min + max) / 510; + + let s = 0; + if (l > 0 && l < 1) s = delta / (l < 0.5 ? max + min : 510 - max - min); + + let h = 0; + if (delta > 0) { + if (max === r) { + h = (g - b) / delta; + } else if (max === g) { + h = 2 + (b - r) / delta; + } else { + h = 4 + (r - g) / delta; + } + + h *= 60; + if (h < 0) h += 360; + } + return { h, s, l }; +} diff --git a/node_modules/image-q/src/conversion/rgb2lab.ts b/node_modules/image-q/src/conversion/rgb2lab.ts new file mode 100644 index 00000000..bde1c53d --- /dev/null +++ b/node_modules/image-q/src/conversion/rgb2lab.ts @@ -0,0 +1,14 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * rgb2lab.ts - part of Image Quantization Library + */ +import { rgb2xyz } from './rgb2xyz'; +import { xyz2lab } from './xyz2lab'; + +export function rgb2lab(r: number, g: number, b: number) { + const xyz = rgb2xyz(r, g, b); + return xyz2lab(xyz.x, xyz.y, xyz.z); +} diff --git a/node_modules/image-q/src/conversion/rgb2xyz.ts b/node_modules/image-q/src/conversion/rgb2xyz.ts new file mode 100644 index 00000000..d45b09f8 --- /dev/null +++ b/node_modules/image-q/src/conversion/rgb2xyz.ts @@ -0,0 +1,24 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * rgb2xyz.ts - part of Image Quantization Library + */ +function correctGamma(n: number) { + return n > 0.04045 ? ((n + 0.055) / 1.055) ** 2.4 : n / 12.92; +} + +export function rgb2xyz(r: number, g: number, b: number) { + // gamma correction, see https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation + r = correctGamma(r / 255); + g = correctGamma(g / 255); + b = correctGamma(b / 255); + + // Observer. = 2°, Illuminant = D65 + return { + x: r * 0.4124 + g * 0.3576 + b * 0.1805, + y: r * 0.2126 + g * 0.7152 + b * 0.0722, + z: r * 0.0193 + g * 0.1192 + b * 0.9505, + }; +} diff --git a/node_modules/image-q/src/conversion/xyz2lab.ts b/node_modules/image-q/src/conversion/xyz2lab.ts new file mode 100644 index 00000000..6fc0385e --- /dev/null +++ b/node_modules/image-q/src/conversion/xyz2lab.ts @@ -0,0 +1,27 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * xyz2lab.ts - part of Image Quantization Library + */ +const refX = 0.95047; // ref_X = 95.047 Observer= 2°, Illuminant= D65 +const refY = 1.0; // ref_Y = 100.000 +const refZ = 1.08883; // ref_Z = 108.883 + +function pivot(n: number) { + return n > 0.008856 ? n ** (1 / 3) : 7.787 * n + 16 / 116; +} + +export function xyz2lab(x: number, y: number, z: number) { + x = pivot(x / refX); + y = pivot(y / refY); + z = pivot(z / refZ); + + if (116 * y - 16 < 0) throw new Error('xxx'); + return { + L: Math.max(0, 116 * y - 16), + a: 500 * (x - y), + b: 200 * (y - z), + }; +} diff --git a/node_modules/image-q/src/conversion/xyz2rgb.ts b/node_modules/image-q/src/conversion/xyz2rgb.ts new file mode 100644 index 00000000..5a2c6580 --- /dev/null +++ b/node_modules/image-q/src/conversion/xyz2rgb.ts @@ -0,0 +1,26 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * xyz2rgb.ts - part of Image Quantization Library + */ +import { inRange0to255Rounded } from '../utils/arithmetic'; + +// gamma correction, see https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation +function correctGamma(n: number) { + return n > 0.0031308 ? 1.055 * n ** (1 / 2.4) - 0.055 : 12.92 * n; +} + +export function xyz2rgb(x: number, y: number, z: number) { + // Observer. = 2°, Illuminant = D65 + const r = correctGamma(x * 3.2406 + y * -1.5372 + z * -0.4986); + const g = correctGamma(x * -0.9689 + y * 1.8758 + z * 0.0415); + const b = correctGamma(x * 0.0557 + y * -0.204 + z * 1.057); + + return { + r: inRange0to255Rounded(r * 255), + g: inRange0to255Rounded(g * 255), + b: inRange0to255Rounded(b * 255), + }; +} diff --git a/node_modules/image-q/src/distance/cie94.ts b/node_modules/image-q/src/distance/cie94.ts new file mode 100644 index 00000000..203e0f0a --- /dev/null +++ b/node_modules/image-q/src/distance/cie94.ts @@ -0,0 +1,86 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * cie94.ts - part of Image Quantization Library + */ +import { AbstractDistanceCalculator } from './distanceCalculator'; +import { rgb2lab } from '../conversion/rgb2lab'; +import { inRange0to255 } from '../utils/arithmetic'; + +/** + * CIE94 method of delta-e + * http://en.wikipedia.org/wiki/Color_difference#CIE94 + */ +export abstract class AbstractCIE94 extends AbstractDistanceCalculator { + /** + * Weight in distance: 0.25 + * Max DeltaE: 100 + * Max DeltaA: 255 + */ + declare protected _kA: number; + declare protected _Kl: number; + declare protected _K1: number; + declare protected _K2: number; + + calculateRaw( + r1: number, + g1: number, + b1: number, + a1: number, + r2: number, + g2: number, + b2: number, + a2: number, + ) { + const lab1 = rgb2lab( + inRange0to255(r1 * this._whitePoint.r), + inRange0to255(g1 * this._whitePoint.g), + inRange0to255(b1 * this._whitePoint.b), + ); + const lab2 = rgb2lab( + inRange0to255(r2 * this._whitePoint.r), + inRange0to255(g2 * this._whitePoint.g), + inRange0to255(b2 * this._whitePoint.b), + ); + + const dL = lab1.L - lab2.L; + const dA = lab1.a - lab2.a; + const dB = lab1.b - lab2.b; + const c1 = Math.sqrt(lab1.a * lab1.a + lab1.b * lab1.b); + const c2 = Math.sqrt(lab2.a * lab2.a + lab2.b * lab2.b); + const dC = c1 - c2; + + let deltaH = dA * dA + dB * dB - dC * dC; + deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH); + + const dAlpha = (a2 - a1) * this._whitePoint.a * this._kA; + + // TODO: add alpha channel support + return Math.sqrt( + (dL / this._Kl) ** 2 + + (dC / (1.0 + this._K1 * c1)) ** 2 + + (deltaH / (1.0 + this._K2 * c1)) ** 2 + + dAlpha ** 2, + ); + } +} + +export class CIE94Textiles extends AbstractCIE94 { + protected _setDefaults() { + this._Kl = 2.0; + this._K1 = 0.048; + this._K2 = 0.014; + this._kA = (0.25 * 50) / 255; + } +} + +export class CIE94GraphicArts extends AbstractCIE94 { + protected _setDefaults() { + this._Kl = 1.0; + this._K1 = 0.045; + this._K2 = 0.015; + this._kA = (0.25 * 100) / 255; + } +} diff --git a/node_modules/image-q/src/distance/ciede2000.ts b/node_modules/image-q/src/distance/ciede2000.ts new file mode 100644 index 00000000..9bbc17ac --- /dev/null +++ b/node_modules/image-q/src/distance/ciede2000.ts @@ -0,0 +1,178 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * ciede2000.ts - part of Image Quantization Library + */ +import { AbstractDistanceCalculator } from './distanceCalculator'; +import { rgb2lab } from '../conversion/rgb2lab'; +import { degrees2radians, inRange0to255 } from '../utils/arithmetic'; + +/** + * CIEDE2000 algorithm - Adapted from Sharma et al's MATLAB implementation at + * http://www.ece.rochester.edu/~gsharma/ciede2000/ + */ +export class CIEDE2000 extends AbstractDistanceCalculator { + /** + * Weight in distance: 0.25 + * Max DeltaE: 100 + * Max DeltaA: 255 + */ + private static readonly _kA = (0.25 * 100) / 255; + private static readonly _pow25to7 = 25 ** 7; + private static readonly _deg360InRad = degrees2radians(360); + private static readonly _deg180InRad = degrees2radians(180); + private static readonly _deg30InRad = degrees2radians(30); + private static readonly _deg6InRad = degrees2radians(6); + private static readonly _deg63InRad = degrees2radians(63); + private static readonly _deg275InRad = degrees2radians(275); + private static readonly _deg25InRad = degrees2radians(25); + + protected _setDefaults() {} + + private static _calculatehp(b: number, ap: number) { + const hp = Math.atan2(b, ap); + if (hp >= 0) return hp; + return hp + CIEDE2000._deg360InRad; + } + + private static _calculateRT(ahp: number, aCp: number) { + const aCp_to_7 = aCp ** 7.0; + const R_C = 2.0 * Math.sqrt(aCp_to_7 / (aCp_to_7 + CIEDE2000._pow25to7)); // 25^7 + const delta_theta = + CIEDE2000._deg30InRad * + Math.exp( + -(((ahp - CIEDE2000._deg275InRad) / CIEDE2000._deg25InRad) ** 2.0), + ); + return -Math.sin(2.0 * delta_theta) * R_C; + } + + private static _calculateT(ahp: number) { + return ( + 1.0 - + 0.17 * Math.cos(ahp - CIEDE2000._deg30InRad) + + 0.24 * Math.cos(ahp * 2.0) + + 0.32 * Math.cos(ahp * 3.0 + CIEDE2000._deg6InRad) - + 0.2 * Math.cos(ahp * 4.0 - CIEDE2000._deg63InRad) + ); + } + + private static _calculate_ahp( + C1pC2p: number, + h_bar: number, + h1p: number, + h2p: number, + ) { + const hpSum = h1p + h2p; + if (C1pC2p === 0) return hpSum; + if (h_bar <= CIEDE2000._deg180InRad) return hpSum / 2.0; + if (hpSum < CIEDE2000._deg360InRad) { + return (hpSum + CIEDE2000._deg360InRad) / 2.0; + } + return (hpSum - CIEDE2000._deg360InRad) / 2.0; + } + + private static _calculate_dHp( + C1pC2p: number, + h_bar: number, + h2p: number, + h1p: number, + ) { + let dhp; + if (C1pC2p === 0) { + dhp = 0; + } else if (h_bar <= CIEDE2000._deg180InRad) { + dhp = h2p - h1p; + } else if (h2p <= h1p) { + dhp = h2p - h1p + CIEDE2000._deg360InRad; + } else { + dhp = h2p - h1p - CIEDE2000._deg360InRad; + } + return 2.0 * Math.sqrt(C1pC2p) * Math.sin(dhp / 2.0); + } + + calculateRaw( + r1: number, + g1: number, + b1: number, + a1: number, + r2: number, + g2: number, + b2: number, + a2: number, + ) { + const lab1 = rgb2lab( + inRange0to255(r1 * this._whitePoint.r), + inRange0to255(g1 * this._whitePoint.g), + inRange0to255(b1 * this._whitePoint.b), + ); + const lab2 = rgb2lab( + inRange0to255(r2 * this._whitePoint.r), + inRange0to255(g2 * this._whitePoint.g), + inRange0to255(b2 * this._whitePoint.b), + ); + const dA = (a2 - a1) * this._whitePoint.a * CIEDE2000._kA; + const dE2 = this.calculateRawInLab(lab1, lab2); + + return Math.sqrt(dE2 + dA * dA); + } + + calculateRawInLab( + Lab1: { L: number; a: number; b: number }, + Lab2: { L: number; a: number; b: number }, + ) { + // Get L,a,b values for color 1 + const L1 = Lab1.L; + const a1 = Lab1.a; + const b1 = Lab1.b; + + // Get L,a,b values for color 2 + const L2 = Lab2.L; + const a2 = Lab2.a; + const b2 = Lab2.b; + + // Calculate Cprime1, Cprime2, Cabbar + const C1 = Math.sqrt(a1 * a1 + b1 * b1); + const C2 = Math.sqrt(a2 * a2 + b2 * b2); + const pow_a_C1_C2_to_7 = ((C1 + C2) / 2.0) ** 7.0; + + const G = + 0.5 * + (1.0 - + Math.sqrt(pow_a_C1_C2_to_7 / (pow_a_C1_C2_to_7 + CIEDE2000._pow25to7))); // 25^7 + const a1p = (1.0 + G) * a1; + const a2p = (1.0 + G) * a2; + + const C1p = Math.sqrt(a1p * a1p + b1 * b1); + const C2p = Math.sqrt(a2p * a2p + b2 * b2); + const C1pC2p = C1p * C2p; + + // Angles in Degree. + const h1p = CIEDE2000._calculatehp(b1, a1p); + const h2p = CIEDE2000._calculatehp(b2, a2p); + const h_bar = Math.abs(h1p - h2p); + const dLp = L2 - L1; + const dCp = C2p - C1p; + const dHp = CIEDE2000._calculate_dHp(C1pC2p, h_bar, h2p, h1p); + const ahp = CIEDE2000._calculate_ahp(C1pC2p, h_bar, h1p, h2p); + + const T = CIEDE2000._calculateT(ahp); + + const aCp = (C1p + C2p) / 2.0; + const aLp_minus_50_square = ((L1 + L2) / 2.0 - 50.0) ** 2.0; + const S_L = + 1.0 + + (0.015 * aLp_minus_50_square) / Math.sqrt(20.0 + aLp_minus_50_square); + const S_C = 1.0 + 0.045 * aCp; + const S_H = 1.0 + 0.015 * T * aCp; + + const R_T = CIEDE2000._calculateRT(ahp, aCp); + + const dLpSL = dLp / S_L; // S_L * kL, where kL is 1.0 + const dCpSC = dCp / S_C; // S_C * kC, where kC is 1.0 + const dHpSH = dHp / S_H; // S_H * kH, where kH is 1.0 + + return dLpSL ** 2 + dCpSC ** 2 + dHpSH ** 2 + R_T * dCpSC * dHpSH; + } +} diff --git a/node_modules/image-q/src/distance/cmetric.ts b/node_modules/image-q/src/distance/cmetric.ts new file mode 100644 index 00000000..0ca7141a --- /dev/null +++ b/node_modules/image-q/src/distance/cmetric.ts @@ -0,0 +1,38 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * cmetric.ts - part of Image Quantization Library + */ +import { AbstractDistanceCalculator } from './distanceCalculator'; + +/** + * TODO: Name it: http://www.compuphase.com/cmetric.htm + */ +export class CMetric extends AbstractDistanceCalculator { + calculateRaw( + r1: number, + g1: number, + b1: number, + a1: number, + r2: number, + g2: number, + b2: number, + a2: number, + ) { + const rmean = ((r1 + r2) / 2) * this._whitePoint.r; + const r = (r1 - r2) * this._whitePoint.r; + const g = (g1 - g2) * this._whitePoint.g; + const b = (b1 - b2) * this._whitePoint.b; + const dE = + (((512 + rmean) * r * r) >> 8) + + 4 * g * g + + (((767 - rmean) * b * b) >> 8); + const dA = (a2 - a1) * this._whitePoint.a; + + return Math.sqrt(dE + dA * dA); + } + + protected _setDefaults() {} +} diff --git a/node_modules/image-q/src/distance/distanceCalculator.ts b/node_modules/image-q/src/distance/distanceCalculator.ts new file mode 100644 index 00000000..fdb93c5c --- /dev/null +++ b/node_modules/image-q/src/distance/distanceCalculator.ts @@ -0,0 +1,66 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * common.ts - part of Image Quantization Library + */ +import { PointRGBA } from '../utils/point'; + +export abstract class AbstractDistanceCalculator { + protected _maxDistance!: number; + protected _whitePoint!: { + r: number; + g: number; + b: number; + a: number; + }; + + constructor() { + this._setDefaults(); + + // set default maximal color component deltas (255 - 0 = 255) + this.setWhitePoint(255, 255, 255, 255); + } + + setWhitePoint(r: number, g: number, b: number, a: number) { + this._whitePoint = { + r: r > 0 ? 255 / r : 0, + g: g > 0 ? 255 / g : 0, + b: b > 0 ? 255 / b : 0, + a: a > 0 ? 255 / a : 0, + }; + this._maxDistance = this.calculateRaw(r, g, b, a, 0, 0, 0, 0); + } + + calculateNormalized(colorA: PointRGBA, colorB: PointRGBA) { + return ( + this.calculateRaw( + colorA.r, + colorA.g, + colorA.b, + colorA.a, + colorB.r, + colorB.g, + colorB.b, + colorB.a, + ) / this._maxDistance + ); + } + + /** + * Calculate raw distance (non-normalized) + */ + abstract calculateRaw( + r1: number, + g1: number, + b1: number, + a1: number, + r2: number, + g2: number, + b2: number, + a2: number, + ): number; + + protected abstract _setDefaults(): void; +} diff --git a/node_modules/image-q/src/distance/euclidean.ts b/node_modules/image-q/src/distance/euclidean.ts new file mode 100644 index 00000000..7a700851 --- /dev/null +++ b/node_modules/image-q/src/distance/euclidean.ts @@ -0,0 +1,75 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * euclidean.ts - part of Image Quantization Library + */ +import { AbstractDistanceCalculator } from './distanceCalculator'; +import { Y } from '../constants/bt709'; + +/** + * Euclidean color distance + */ +export abstract class AbstractEuclidean extends AbstractDistanceCalculator { + declare protected _kR: number; + declare protected _kG: number; + declare protected _kB: number; + declare protected _kA: number; + + calculateRaw( + r1: number, + g1: number, + b1: number, + a1: number, + r2: number, + g2: number, + b2: number, + a2: number, + ) { + const dR = r2 - r1; + const dG = g2 - g1; + const dB = b2 - b1; + const dA = a2 - a1; + return Math.sqrt( + this._kR * dR * dR + + this._kG * dG * dG + + this._kB * dB * dB + + this._kA * dA * dA, + ); + } +} + +export class Euclidean extends AbstractEuclidean { + protected _setDefaults() { + this._kR = 1; + this._kG = 1; + this._kB = 1; + this._kA = 1; + } +} + +/** + * Euclidean color distance (RGBQuant modification w Alpha) + */ +export class EuclideanBT709 extends AbstractEuclidean { + protected _setDefaults() { + this._kR = Y.RED; + this._kG = Y.GREEN; + this._kB = Y.BLUE; + // TODO: what is the best coefficient below? + this._kA = 1; + } +} + +/** + * Euclidean color distance (RGBQuant modification w/o Alpha) + */ +export class EuclideanBT709NoAlpha extends AbstractEuclidean { + protected _setDefaults() { + this._kR = Y.RED; + this._kG = Y.GREEN; + this._kB = Y.BLUE; + this._kA = 0; + } +} diff --git a/node_modules/image-q/src/distance/index.ts b/node_modules/image-q/src/distance/index.ts new file mode 100644 index 00000000..03be3734 --- /dev/null +++ b/node_modules/image-q/src/distance/index.ts @@ -0,0 +1,24 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * iq.ts - Image Quantization Library + */ +export { AbstractDistanceCalculator } from './distanceCalculator'; +export { CIE94Textiles, CIE94GraphicArts } from './cie94'; +export { CIEDE2000 } from './ciede2000'; +export { CMetric } from './cmetric'; +export { + AbstractEuclidean, + Euclidean, + EuclideanBT709NoAlpha, + EuclideanBT709, +} from './euclidean'; +export { + AbstractManhattan, + Manhattan, + ManhattanBT709, + ManhattanNommyde, +} from './manhattan'; +export { PNGQuant } from './pngQuant'; diff --git a/node_modules/image-q/src/distance/manhattan.ts b/node_modules/image-q/src/distance/manhattan.ts new file mode 100644 index 00000000..eb743982 --- /dev/null +++ b/node_modules/image-q/src/distance/manhattan.ts @@ -0,0 +1,77 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * manhattanNeuQuant.ts - part of Image Quantization Library + */ +import { AbstractDistanceCalculator } from './distanceCalculator'; +import { Y } from '../constants/bt709'; + +/** + * Manhattan distance (NeuQuant modification) - w/o sRGB coefficients + */ +export abstract class AbstractManhattan extends AbstractDistanceCalculator { + declare protected _kR: number; + declare protected _kG: number; + declare protected _kB: number; + declare protected _kA: number; + + calculateRaw( + r1: number, + g1: number, + b1: number, + a1: number, + r2: number, + g2: number, + b2: number, + a2: number, + ) { + let dR = r2 - r1; + let dG = g2 - g1; + let dB = b2 - b1; + let dA = a2 - a1; + if (dR < 0) dR = 0 - dR; + if (dG < 0) dG = 0 - dG; + if (dB < 0) dB = 0 - dB; + if (dA < 0) dA = 0 - dA; + + return this._kR * dR + this._kG * dG + this._kB * dB + this._kA * dA; + } +} + +export class Manhattan extends AbstractManhattan { + protected _setDefaults() { + this._kR = 1; + this._kG = 1; + this._kB = 1; + this._kA = 1; + } +} + +/** + * Manhattan distance (Nommyde modification) + * https://github.com/igor-bezkrovny/image-quantization/issues/4#issuecomment-235155320 + */ +export class ManhattanNommyde extends AbstractManhattan { + protected _setDefaults() { + this._kR = 0.4984; + this._kG = 0.8625; + this._kB = 0.2979; + // TODO: what is the best coefficient below? + this._kA = 1; + } +} + +/** + * Manhattan distance (sRGB coefficients) + */ +export class ManhattanBT709 extends AbstractManhattan { + protected _setDefaults() { + this._kR = Y.RED; + this._kG = Y.GREEN; + this._kB = Y.BLUE; + // TODO: what is the best coefficient below? + this._kA = 1; + } +} diff --git a/node_modules/image-q/src/distance/pngQuant.ts b/node_modules/image-q/src/distance/pngQuant.ts new file mode 100644 index 00000000..aff7678b --- /dev/null +++ b/node_modules/image-q/src/distance/pngQuant.ts @@ -0,0 +1,74 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * pngQuant.ts - part of Image Quantization Library + */ +import { AbstractDistanceCalculator } from './distanceCalculator'; + +/** + * TODO: check quality of this distance equation + * TODO: ask author for usage rights + * taken from: + * {@link http://stackoverflow.com/questions/4754506/color-similarity-distance-in-rgba-color-space/8796867#8796867} + * {@link https://github.com/pornel/pngquant/blob/cc39b47799a7ff2ef17b529f9415ff6e6b213b8f/lib/pam.h#L148} + */ +export class PNGQuant extends AbstractDistanceCalculator { + /** + * Author's comments + * px_b.rgb = px.rgb + 0*(1-px.a) // blend px on black + * px_b.a = px.a + 1*(1-px.a) + * px_w.rgb = px.rgb + 1*(1-px.a) // blend px on white + * px_w.a = px.a + 1*(1-px.a) + * + * px_b.rgb = px.rgb // difference same as in opaque RGB + * px_b.a = 1 + * px_w.rgb = px.rgb - px.a // difference simplifies to formula below + * px_w.a = 1 + * + * (px.rgb - px.a) - (py.rgb - py.a) + * (px.rgb - py.rgb) + (py.a - px.a) + * + */ + calculateRaw( + r1: number, + g1: number, + b1: number, + a1: number, + r2: number, + g2: number, + b2: number, + a2: number, + ) { + const alphas = (a2 - a1) * this._whitePoint.a; + return ( + this._colordifferenceCh( + r1 * this._whitePoint.r, + r2 * this._whitePoint.r, + alphas, + ) + + this._colordifferenceCh( + g1 * this._whitePoint.g, + g2 * this._whitePoint.g, + alphas, + ) + + this._colordifferenceCh( + b1 * this._whitePoint.b, + b2 * this._whitePoint.b, + alphas, + ) + ); + } + + private _colordifferenceCh(x: number, y: number, alphas: number) { + // maximum of channel blended on white, and blended on black + // premultiplied alpha and backgrounds 0/1 shorten the formula + const black = x - y; + const white = black + alphas; + + return black * black + white * white; + } + + protected _setDefaults() {} +} diff --git a/node_modules/image-q/src/image/array.ts b/node_modules/image-q/src/image/array.ts new file mode 100644 index 00000000..ea04affa --- /dev/null +++ b/node_modules/image-q/src/image/array.ts @@ -0,0 +1,317 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * ditherErrorDiffusionArray.ts - part of Image Quantization Library + */ +import { AbstractImageQuantizer } from './imageQuantizer'; +import { AbstractDistanceCalculator } from '../distance/distanceCalculator'; +import { PointContainer } from '../utils/pointContainer'; +import { Palette } from '../utils/palette'; +import { Point } from '../utils/point'; +import { inRange0to255Rounded } from '../utils/arithmetic'; +import { ImageQuantizerYieldValue } from './imageQuantizerYieldValue'; +import { ProgressTracker } from '../utils/progressTracker'; + +// TODO: is it the best name for this enum "kernel"? +export enum ErrorDiffusionArrayKernel { + FloydSteinberg = 0, + FalseFloydSteinberg, + Stucki, + Atkinson, + Jarvis, + Burkes, + Sierra, + TwoSierra, + SierraLite, +} + +// http://www.tannerhelland.com/4660/dithering-eleven-algorithms-source-code/ +export class ErrorDiffusionArray extends AbstractImageQuantizer { + private _minColorDistance: number; + private _serpentine: boolean; + private _kernel!: number[][]; + /** true = GIMP, false = XNVIEW */ + private _calculateErrorLikeGIMP: boolean; + + private _distance: AbstractDistanceCalculator; + + constructor( + colorDistanceCalculator: AbstractDistanceCalculator, + kernel: ErrorDiffusionArrayKernel, + serpentine = true, + minimumColorDistanceToDither = 0, + calculateErrorLikeGIMP = false, + ) { + super(); + this._setKernel(kernel); + + this._distance = colorDistanceCalculator; + this._minColorDistance = minimumColorDistanceToDither; + this._serpentine = serpentine; + this._calculateErrorLikeGIMP = calculateErrorLikeGIMP; + } + + /** + * adapted from http://jsbin.com/iXofIji/2/edit by PAEz + * fixed version. it doesn't use image pixels as error storage, also it doesn't have 0.3 + 0.3 + 0.3 + 0.3 = 0 error + * Mutates pointContainer + */ + *quantize( + pointContainer: PointContainer, + palette: Palette, + ): IterableIterator { + const pointArray = pointContainer.getPointArray(); + const originalPoint = new Point(); + const width = pointContainer.getWidth(); + const height = pointContainer.getHeight(); + const errorLines: number[][][] = []; + + let dir = 1; + let maxErrorLines = 1; + + // initial error lines (number is taken from dithering kernel) + for (const kernel of this._kernel) { + const kernelErrorLines = kernel[2] + 1; + if (maxErrorLines < kernelErrorLines) maxErrorLines = kernelErrorLines; + } + for (let i = 0; i < maxErrorLines; i++) { + this._fillErrorLine((errorLines[i] = []), width); + } + + const tracker = new ProgressTracker(height, 99); + for (let y = 0; y < height; y++) { + if (tracker.shouldNotify(y)) { + yield { + progress: tracker.progress, + }; + } + + // always serpentine + if (this._serpentine) dir *= -1; + + const lni = y * width; + const xStart = dir === 1 ? 0 : width - 1; + const xEnd = dir === 1 ? width : -1; + + // cyclic shift with erasing + this._fillErrorLine(errorLines[0], width); + // TODO: why it is needed to cast types here? + errorLines.push(errorLines.shift() as number[][]); + + const errorLine = errorLines[0]; + for ( + let x = xStart, idx = lni + xStart; + x !== xEnd; + x += dir, idx += dir + ) { + // Image pixel + const point = pointArray[idx]; + // originalPoint = new Utils.Point(), + const error = errorLine[x]; + + originalPoint.from(point); + + const correctedPoint = Point.createByRGBA( + inRange0to255Rounded(point.r + error[0]), + inRange0to255Rounded(point.g + error[1]), + inRange0to255Rounded(point.b + error[2]), + inRange0to255Rounded(point.a + error[3]), + ); + + // Reduced pixel + const palettePoint = palette.getNearestColor( + this._distance, + correctedPoint, + ); + point.from(palettePoint); + + // dithering strength + if (this._minColorDistance) { + const dist = this._distance.calculateNormalized( + originalPoint, + palettePoint, + ); + if (dist < this._minColorDistance) continue; + } + + // Component distance + let er; + let eg; + let eb; + let ea; + if (this._calculateErrorLikeGIMP) { + er = correctedPoint.r - palettePoint.r; + eg = correctedPoint.g - palettePoint.g; + eb = correctedPoint.b - palettePoint.b; + ea = correctedPoint.a - palettePoint.a; + } else { + er = originalPoint.r - palettePoint.r; + eg = originalPoint.g - palettePoint.g; + eb = originalPoint.b - palettePoint.b; + ea = originalPoint.a - palettePoint.a; + } + + const dStart = dir === 1 ? 0 : this._kernel.length - 1; + const dEnd = dir === 1 ? this._kernel.length : -1; + + for (let i = dStart; i !== dEnd; i += dir) { + const x1 = this._kernel[i][1] * dir; + const y1 = this._kernel[i][2]; + + if (x1 + x >= 0 && x1 + x < width && y1 + y >= 0 && y1 + y < height) { + const d = this._kernel[i][0]; + const e = errorLines[y1][x1 + x]; + + e[0] += er * d; + e[1] += eg * d; + e[2] += eb * d; + e[3] += ea * d; + } + } + } + } + + yield { + pointContainer, + progress: 100, + }; + } + + private _fillErrorLine(errorLine: number[][], width: number) { + // shrink + if (errorLine.length > width) { + errorLine.length = width; + } + + // reuse existing arrays + const l = errorLine.length; + for (let i = 0; i < l; i++) { + const error = errorLine[i]; + error[0] = error[1] = error[2] = error[3] = 0; + } + + // create missing arrays + for (let i = l; i < width; i++) { + errorLine[i] = [0.0, 0.0, 0.0, 0.0]; + } + } + + private _setKernel(kernel: ErrorDiffusionArrayKernel) { + switch (kernel) { + case ErrorDiffusionArrayKernel.FloydSteinberg: + this._kernel = [ + [7 / 16, 1, 0], + [3 / 16, -1, 1], + [5 / 16, 0, 1], + [1 / 16, 1, 1], + ]; + break; + + case ErrorDiffusionArrayKernel.FalseFloydSteinberg: + this._kernel = [ + [3 / 8, 1, 0], + [3 / 8, 0, 1], + [2 / 8, 1, 1], + ]; + break; + + case ErrorDiffusionArrayKernel.Stucki: + this._kernel = [ + [8 / 42, 1, 0], + [4 / 42, 2, 0], + [2 / 42, -2, 1], + [4 / 42, -1, 1], + [8 / 42, 0, 1], + [4 / 42, 1, 1], + [2 / 42, 2, 1], + [1 / 42, -2, 2], + [2 / 42, -1, 2], + [4 / 42, 0, 2], + [2 / 42, 1, 2], + [1 / 42, 2, 2], + ]; + break; + + case ErrorDiffusionArrayKernel.Atkinson: + this._kernel = [ + [1 / 8, 1, 0], + [1 / 8, 2, 0], + [1 / 8, -1, 1], + [1 / 8, 0, 1], + [1 / 8, 1, 1], + [1 / 8, 0, 2], + ]; + break; + + case ErrorDiffusionArrayKernel.Jarvis: + this._kernel = [ + // Jarvis, Judice, and Ninke / JJN? + [7 / 48, 1, 0], + [5 / 48, 2, 0], + [3 / 48, -2, 1], + [5 / 48, -1, 1], + [7 / 48, 0, 1], + [5 / 48, 1, 1], + [3 / 48, 2, 1], + [1 / 48, -2, 2], + [3 / 48, -1, 2], + [5 / 48, 0, 2], + [3 / 48, 1, 2], + [1 / 48, 2, 2], + ]; + break; + + case ErrorDiffusionArrayKernel.Burkes: + this._kernel = [ + [8 / 32, 1, 0], + [4 / 32, 2, 0], + [2 / 32, -2, 1], + [4 / 32, -1, 1], + [8 / 32, 0, 1], + [4 / 32, 1, 1], + [2 / 32, 2, 1], + ]; + break; + + case ErrorDiffusionArrayKernel.Sierra: + this._kernel = [ + [5 / 32, 1, 0], + [3 / 32, 2, 0], + [2 / 32, -2, 1], + [4 / 32, -1, 1], + [5 / 32, 0, 1], + [4 / 32, 1, 1], + [2 / 32, 2, 1], + [2 / 32, -1, 2], + [3 / 32, 0, 2], + [2 / 32, 1, 2], + ]; + break; + + case ErrorDiffusionArrayKernel.TwoSierra: + this._kernel = [ + [4 / 16, 1, 0], + [3 / 16, 2, 0], + [1 / 16, -2, 1], + [2 / 16, -1, 1], + [3 / 16, 0, 1], + [2 / 16, 1, 1], + [1 / 16, 2, 1], + ]; + break; + + case ErrorDiffusionArrayKernel.SierraLite: + this._kernel = [ + [2 / 4, 1, 0], + [1 / 4, -1, 1], + [1 / 4, 0, 1], + ]; + break; + + default: + throw new Error(`ErrorDiffusionArray: unknown kernel = ${kernel}`); + } + } +} diff --git a/node_modules/image-q/src/image/imageQuantizer.ts b/node_modules/image-q/src/image/imageQuantizer.ts new file mode 100644 index 00000000..6eb8c7e9 --- /dev/null +++ b/node_modules/image-q/src/image/imageQuantizer.ts @@ -0,0 +1,27 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * common.ts - part of Image Quantization Library + */ +import { PointContainer } from '../utils/pointContainer'; +import { Palette } from '../utils/palette'; +import { ImageQuantizerYieldValue } from './imageQuantizerYieldValue'; + +export abstract class AbstractImageQuantizer { + abstract quantize( + pointContainer: PointContainer, + palette: Palette, + ): IterableIterator; + + quantizeSync(pointContainer: PointContainer, palette: Palette) { + for (const value of this.quantize(pointContainer, palette)) { + if (value.pointContainer) { + return value.pointContainer; + } + } + + throw new Error('unreachable'); + } +} diff --git a/node_modules/image-q/src/image/imageQuantizerYieldValue.ts b/node_modules/image-q/src/image/imageQuantizerYieldValue.ts new file mode 100644 index 00000000..3fc69782 --- /dev/null +++ b/node_modules/image-q/src/image/imageQuantizerYieldValue.ts @@ -0,0 +1,6 @@ +import { PointContainer } from '../utils'; + +export interface ImageQuantizerYieldValue { + progress: number; + pointContainer?: PointContainer; +} diff --git a/node_modules/image-q/src/image/index.ts b/node_modules/image-q/src/image/index.ts new file mode 100644 index 00000000..a3afdebe --- /dev/null +++ b/node_modules/image-q/src/image/index.ts @@ -0,0 +1,13 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * iq.ts - Image Quantization Library + */ + +export { AbstractImageQuantizer } from './imageQuantizer'; +export { ImageQuantizerYieldValue } from './imageQuantizerYieldValue'; +export { NearestColor } from './nearestColor'; +export { ErrorDiffusionArray, ErrorDiffusionArrayKernel } from './array'; +export { ErrorDiffusionRiemersma } from './riemersma'; diff --git a/node_modules/image-q/src/image/nearestColor.ts b/node_modules/image-q/src/image/nearestColor.ts new file mode 100644 index 00000000..8f0e31b1 --- /dev/null +++ b/node_modules/image-q/src/image/nearestColor.ts @@ -0,0 +1,54 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * nearestColor.ts - part of Image Quantization Library + */ +import { AbstractImageQuantizer } from './imageQuantizer'; +import { AbstractDistanceCalculator } from '../distance/distanceCalculator'; +import { PointContainer } from '../utils/pointContainer'; +import { Palette } from '../utils/palette'; +import { ImageQuantizerYieldValue } from './imageQuantizerYieldValue'; +import { ProgressTracker } from '../utils/progressTracker'; + +export class NearestColor extends AbstractImageQuantizer { + private _distance: AbstractDistanceCalculator; + + constructor(colorDistanceCalculator: AbstractDistanceCalculator) { + super(); + this._distance = colorDistanceCalculator; + } + + /** + * Mutates pointContainer + */ + *quantize( + pointContainer: PointContainer, + palette: Palette, + ): IterableIterator { + const pointArray = pointContainer.getPointArray(); + const width = pointContainer.getWidth(); + const height = pointContainer.getHeight(); + + const tracker = new ProgressTracker(height, 99); + for (let y = 0; y < height; y++) { + if (tracker.shouldNotify(y)) { + yield { + progress: tracker.progress, + }; + } + for (let x = 0, idx = y * width; x < width; x++, idx++) { + // Image pixel + const point = pointArray[idx]; + // Reduced pixel + point.from(palette.getNearestColor(this._distance, point)); + } + } + + yield { + pointContainer, + progress: 100, + }; + } +} diff --git a/node_modules/image-q/src/image/riemersma.ts b/node_modules/image-q/src/image/riemersma.ts new file mode 100644 index 00000000..76b49f08 --- /dev/null +++ b/node_modules/image-q/src/image/riemersma.ts @@ -0,0 +1,135 @@ +/** + * @preserve + * MIT License + * + * Copyright 2015-2018 Igor Bezkrovnyi + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * riemersma.ts - part of Image Quantization Library + */ +import { AbstractImageQuantizer } from './imageQuantizer'; +import { hilbertCurve } from './spaceFillingCurves/hilbertCurve'; +import { AbstractDistanceCalculator } from '../distance/distanceCalculator'; +import { PointContainer } from '../utils/pointContainer'; +import { Palette } from '../utils/palette'; +import { Point } from '../utils/point'; +import { inRange0to255Rounded } from '../utils/arithmetic'; + +export class ErrorDiffusionRiemersma extends AbstractImageQuantizer { + private _distance: AbstractDistanceCalculator; + private _weights: number[]; + private _errorQueueSize: number; + + constructor( + colorDistanceCalculator: AbstractDistanceCalculator, + errorQueueSize = 16, + errorPropagation = 1, + ) { + super(); + this._distance = colorDistanceCalculator; + this._errorQueueSize = errorQueueSize; + this._weights = ErrorDiffusionRiemersma._createWeights( + errorPropagation, + errorQueueSize, + ); + } + + /** + * Mutates pointContainer + */ + *quantize(pointContainer: PointContainer, palette: Palette) { + const pointArray = pointContainer.getPointArray(); + const width = pointContainer.getWidth(); + const height = pointContainer.getHeight(); + const errorQueue: Array<{ + r: number; + g: number; + b: number; + a: number; + }> = []; + + let head = 0; + + for (let i = 0; i < this._errorQueueSize; i++) { + errorQueue[i] = { r: 0, g: 0, b: 0, a: 0 }; + } + + yield* hilbertCurve(width, height, (x, y) => { + const p = pointArray[x + y * width]; + let { r, g, b, a } = p; + for (let i = 0; i < this._errorQueueSize; i++) { + const weight = this._weights[i]; + const e = errorQueue[(i + head) % this._errorQueueSize]; + + r += e.r * weight; + g += e.g * weight; + b += e.b * weight; + a += e.a * weight; + } + + const correctedPoint = Point.createByRGBA( + inRange0to255Rounded(r), + inRange0to255Rounded(g), + inRange0to255Rounded(b), + inRange0to255Rounded(a), + ); + + const quantizedPoint = palette.getNearestColor( + this._distance, + correctedPoint, + ); + + // update head and calculate tail + head = (head + 1) % this._errorQueueSize; + const tail = (head + this._errorQueueSize - 1) % this._errorQueueSize; + + // update error with new value + errorQueue[tail].r = p.r - quantizedPoint.r; + errorQueue[tail].g = p.g - quantizedPoint.g; + errorQueue[tail].b = p.b - quantizedPoint.b; + errorQueue[tail].a = p.a - quantizedPoint.a; + + // update point + p.from(quantizedPoint); + }); + + yield { + pointContainer, + progress: 100, + }; + } + + private static _createWeights( + errorPropagation: number, + errorQueueSize: number, + ) { + const weights = []; + + const multiplier = Math.exp( + Math.log(errorQueueSize) / (errorQueueSize - 1), + ); + for (let i = 0, next = 1; i < errorQueueSize; i++) { + weights[i] = (((next + 0.5) | 0) / errorQueueSize) * errorPropagation; + next *= multiplier; + } + + return weights; + } +} diff --git a/node_modules/image-q/src/image/spaceFillingCurves/hilbertCurve.ts b/node_modules/image-q/src/image/spaceFillingCurves/hilbertCurve.ts new file mode 100644 index 00000000..f0ba5617 --- /dev/null +++ b/node_modules/image-q/src/image/spaceFillingCurves/hilbertCurve.ts @@ -0,0 +1,126 @@ +import { ProgressTracker } from '../../utils/progressTracker'; +import { ImageQuantizerYieldValue } from '../imageQuantizerYieldValue'; + +enum Direction { + NONE = 0, + UP, + LEFT, + RIGHT, + DOWN, +} + +interface Data { + x: number; + y: number; + width: number; + height: number; + level: number; + index: number; + tracker: ProgressTracker; + callback(x: number, y: number): void; +} + +export function* hilbertCurve( + width: number, + height: number, + callback: (x: number, y: number) => void, +) { + const maxBound = Math.max(width, height); + const level = Math.floor(Math.log(maxBound) / Math.log(2) + 1); + const tracker = new ProgressTracker(width * height, 99); + const data = { + width, + height, + level, + callback, + tracker, + index: 0, + x: 0, + y: 0, + }; + yield* walkHilbert(data, Direction.UP); + visit(data, Direction.NONE); +} + +function* walkHilbert( + data: Data, + direction: Direction, +): IterableIterator { + if (data.level < 1) return; + + if (data.tracker.shouldNotify(data.index)) { + yield { progress: data.tracker.progress }; + } + data.level--; + switch (direction) { + case Direction.LEFT: + yield* walkHilbert(data, Direction.UP); + visit(data, Direction.RIGHT); + yield* walkHilbert(data, Direction.LEFT); + visit(data, Direction.DOWN); + yield* walkHilbert(data, Direction.LEFT); + visit(data, Direction.LEFT); + yield* walkHilbert(data, Direction.DOWN); + break; + + case Direction.RIGHT: + yield* walkHilbert(data, Direction.DOWN); + visit(data, Direction.LEFT); + yield* walkHilbert(data, Direction.RIGHT); + visit(data, Direction.UP); + yield* walkHilbert(data, Direction.RIGHT); + visit(data, Direction.RIGHT); + yield* walkHilbert(data, Direction.UP); + break; + + case Direction.UP: + yield* walkHilbert(data, Direction.LEFT); + visit(data, Direction.DOWN); + yield* walkHilbert(data, Direction.UP); + visit(data, Direction.RIGHT); + yield* walkHilbert(data, Direction.UP); + visit(data, Direction.UP); + yield* walkHilbert(data, Direction.RIGHT); + break; + + case Direction.DOWN: + yield* walkHilbert(data, Direction.RIGHT); + visit(data, Direction.UP); + yield* walkHilbert(data, Direction.DOWN); + visit(data, Direction.LEFT); + yield* walkHilbert(data, Direction.DOWN); + visit(data, Direction.DOWN); + yield* walkHilbert(data, Direction.LEFT); + break; + + default: + break; + } + data.level++; +} + +function visit(data: Data, direction: Direction) { + if ( + data.x >= 0 && + data.x < data.width && + data.y >= 0 && + data.y < data.height + ) { + data.callback(data.x, data.y); + data.index++; + } + switch (direction) { + case Direction.LEFT: + data.x--; + break; + case Direction.RIGHT: + data.x++; + break; + case Direction.UP: + data.y--; + break; + case Direction.DOWN: + data.y++; + break; + } +} diff --git a/node_modules/image-q/src/index.ts b/node_modules/image-q/src/index.ts new file mode 100644 index 00000000..9ccd4707 --- /dev/null +++ b/node_modules/image-q/src/index.ts @@ -0,0 +1,29 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * iq.ts - Image Quantization Library + */ +import * as constants from './constants'; +import * as conversion from './conversion'; +import * as distance from './distance'; +import * as palette from './palette'; +import * as image from './image'; +import * as quality from './quality'; +import * as utils from './utils'; + +export { + buildPalette, + buildPaletteSync, + applyPalette, + applyPaletteSync, +} from './basicAPI'; + +export type { + ImageQuantization, + PaletteQuantization, + ColorDistanceFormula, +} from './basicAPI'; + +export { constants, conversion, distance, palette, image, quality, utils }; diff --git a/node_modules/image-q/src/missing-types.d.ts b/node_modules/image-q/src/missing-types.d.ts new file mode 100644 index 00000000..4b1350c0 --- /dev/null +++ b/node_modules/image-q/src/missing-types.d.ts @@ -0,0 +1 @@ +declare module 'core-js/features/*'; diff --git a/node_modules/image-q/src/palette/index.ts b/node_modules/image-q/src/palette/index.ts new file mode 100644 index 00000000..714929b8 --- /dev/null +++ b/node_modules/image-q/src/palette/index.ts @@ -0,0 +1,14 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * iq.ts - Image Quantization Library + */ +export { AbstractPaletteQuantizer } from './paletteQuantizer'; +export { NeuQuant } from './neuquant/neuquant'; +export { NeuQuantFloat } from './neuquant/neuquantFloat'; +export { RGBQuant } from './rgbquant/rgbquant'; +export { ColorHistogram } from './rgbquant/colorHistogram'; +export { WuQuant, WuColorCube } from './wu/wuQuant'; +export { PaletteQuantizerYieldValue } from './paletteQuantizerYieldValue'; diff --git a/node_modules/image-q/src/palette/neuquant/neuquant.ts b/node_modules/image-q/src/palette/neuquant/neuquant.ts new file mode 100644 index 00000000..b4b64a22 --- /dev/null +++ b/node_modules/image-q/src/palette/neuquant/neuquant.ts @@ -0,0 +1,405 @@ +/* + * NeuQuant Neural-Net Quantization Algorithm + * ------------------------------------------ + * + * Copyright (c) 1994 Anthony Dekker + * + * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See + * "Kohonen neural networks for optimal colour quantization" in "Network: + * Computation in Neural Systems" Vol. 5 (1994) pp 351-367. for a discussion of + * the algorithm. + * + * Any party obtaining a copy of these files from the author, directly or + * indirectly, is granted, free of charge, a full and unrestricted irrevocable, + * world-wide, paid up, royalty-free, nonexclusive right and license to deal in + * this software and documentation files (the "Software"), including without + * limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons who + * receive copies from any such party to do so, with the only requirement being + * that this copyright notice remain intact. + */ + +/** + * @preserve TypeScript port: + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * neuquant.ts - part of Image Quantization Library + */ + +import { Palette } from '../../utils/palette'; +import { Point } from '../../utils/point'; +import { PointContainer } from '../../utils/pointContainer'; +import { AbstractDistanceCalculator } from '../../distance/distanceCalculator'; +import { AbstractPaletteQuantizer } from '../paletteQuantizer'; +import { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue'; +import { ProgressTracker } from '../../utils'; + +// bias for colour values +const networkBiasShift = 3; + +class Neuron { + r: number; + g: number; + b: number; + a: number; + + constructor(defaultValue: number) { + this.r = this.g = this.b = this.a = defaultValue; + } + + /** + * There is a fix in original NEUQUANT by Anthony Dekker (http://members.ozemail.com.au/~dekker/NEUQUANT.HTML) + * @example + * r = Math.min(255, (neuron.r + (1 << (networkBiasShift - 1))) >> networkBiasShift); + */ + toPoint() { + return Point.createByRGBA( + this.r >> networkBiasShift, + this.g >> networkBiasShift, + this.b >> networkBiasShift, + this.a >> networkBiasShift, + ); + } + + subtract(r: number, g: number, b: number, a: number) { + this.r -= r | 0; + this.g -= g | 0; + this.b -= b | 0; + this.a -= a | 0; + } + + /* + public subtract(r : number, g : number, b : number, a : number) : void { + this.r = (-r + this.r) | 0; + this.g = (-g + this.g) | 0; + this.b = (-b + this.b) | 0; + this.a = (-a + this.a) | 0; + + this.r -= r; + this.g -= g; + this.b -= b; + this.a -= a; + + this.r -= r | 0; + this.g -= g | 0; + this.b -= b | 0; + this.a -= a | 0; + } + */ +} + +export class NeuQuant extends AbstractPaletteQuantizer { + /* + four primes near 500 - assume no image has a length so large + that it is divisible by all four primes + */ + private static readonly _prime1 = 499; + private static readonly _prime2 = 491; + private static readonly _prime3 = 487; + private static readonly _prime4 = 503; + private static readonly _minpicturebytes = NeuQuant._prime4; + + // no. of learning cycles + private static readonly _nCycles = 100; + + // defs for freq and bias + private static readonly _initialBiasShift = 16; + + // bias for fractions + private static readonly _initialBias = 1 << NeuQuant._initialBiasShift; + private static readonly _gammaShift = 10; + + // gamma = 1024 + // TODO: why gamma is never used? + // private static _gamma : number = (1 << NeuQuant._gammaShift); + private static readonly _betaShift = 10; + private static readonly _beta = NeuQuant._initialBias >> NeuQuant._betaShift; + + // beta = 1/1024 + private static readonly _betaGamma = + NeuQuant._initialBias << (NeuQuant._gammaShift - NeuQuant._betaShift); + + /* + * for 256 cols, radius starts + */ + private static readonly _radiusBiasShift = 6; + + // at 32.0 biased by 6 bits + private static readonly _radiusBias = 1 << NeuQuant._radiusBiasShift; + + // and decreases by a factor of 1/30 each cycle + private static readonly _radiusDecrease = 30; + + /* defs for decreasing alpha factor */ + + // alpha starts at 1.0 + private static readonly _alphaBiasShift = 10; + + // biased by 10 bits + private static readonly _initAlpha = 1 << NeuQuant._alphaBiasShift; + + /* radBias and alphaRadBias used for radpower calculation */ + private static readonly _radBiasShift = 8; + private static readonly _radBias = 1 << NeuQuant._radBiasShift; + private static readonly _alphaRadBiasShift = + NeuQuant._alphaBiasShift + NeuQuant._radBiasShift; + private static readonly _alphaRadBias = 1 << NeuQuant._alphaRadBiasShift; + + private _pointArray: Point[]; + private readonly _networkSize: number; + private _network!: Neuron[]; + + /** sampling factor 1..30 */ + private readonly _sampleFactor!: number; + private _radPower!: number[]; + + // bias and freq arrays for learning + private _freq!: number[]; + + /* for network lookup - really 256 */ + private _bias!: number[]; + private readonly _distance: AbstractDistanceCalculator; + + constructor( + colorDistanceCalculator: AbstractDistanceCalculator, + colors = 256, + ) { + super(); + this._distance = colorDistanceCalculator; + this._pointArray = []; + this._sampleFactor = 1; + this._networkSize = colors; + + this._distance.setWhitePoint( + 255 << networkBiasShift, + 255 << networkBiasShift, + 255 << networkBiasShift, + 255 << networkBiasShift, + ); + } + + sample(pointContainer: PointContainer) { + this._pointArray = this._pointArray.concat(pointContainer.getPointArray()); + } + + *quantize(): IterableIterator { + this._init(); + + yield* this._learn(); + + yield { + palette: this._buildPalette(), + progress: 100, + }; + } + + private _init() { + this._freq = []; + this._bias = []; + this._radPower = []; + this._network = []; + for (let i = 0; i < this._networkSize; i++) { + this._network[i] = new Neuron( + ((i << (networkBiasShift + 8)) / this._networkSize) | 0, + ); + + // 1/this._networkSize + this._freq[i] = (NeuQuant._initialBias / this._networkSize) | 0; + this._bias[i] = 0; + } + } + + /** + * Main Learning Loop + */ + private *_learn() { + let sampleFactor = this._sampleFactor; + const pointsNumber = this._pointArray.length; + if (pointsNumber < NeuQuant._minpicturebytes) sampleFactor = 1; + + const alphadec = (30 + (sampleFactor - 1) / 3) | 0; + const pointsToSample = (pointsNumber / sampleFactor) | 0; + + let delta = (pointsToSample / NeuQuant._nCycles) | 0; + let alpha = NeuQuant._initAlpha; + let radius = (this._networkSize >> 3) * NeuQuant._radiusBias; + + let rad = radius >> NeuQuant._radiusBiasShift; + if (rad <= 1) rad = 0; + + for (let i = 0; i < rad; i++) { + this._radPower[i] = + (alpha * (((rad * rad - i * i) * NeuQuant._radBias) / (rad * rad))) >>> + 0; + } + + let step; + if (pointsNumber < NeuQuant._minpicturebytes) { + step = 1; + } else if (pointsNumber % NeuQuant._prime1 !== 0) { + step = NeuQuant._prime1; + } else if (pointsNumber % NeuQuant._prime2 !== 0) { + step = NeuQuant._prime2; + } else if (pointsNumber % NeuQuant._prime3 !== 0) { + step = NeuQuant._prime3; + } else { + step = NeuQuant._prime4; + } + + const tracker = new ProgressTracker(pointsToSample, 99); + for (let i = 0, pointIndex = 0; i < pointsToSample; ) { + if (tracker.shouldNotify(i)) { + yield { + progress: tracker.progress, + }; + } + + const point = this._pointArray[pointIndex]; + const b = point.b << networkBiasShift; + const g = point.g << networkBiasShift; + const r = point.r << networkBiasShift; + const a = point.a << networkBiasShift; + const neuronIndex = this._contest(b, g, r, a); + + this._alterSingle(alpha, neuronIndex, b, g, r, a); + if (rad !== 0) this._alterNeighbour(rad, neuronIndex, b, g, r, a); + + /* alter neighbours */ + pointIndex += step; + if (pointIndex >= pointsNumber) pointIndex -= pointsNumber; + i++; + + if (delta === 0) delta = 1; + + if (i % delta === 0) { + alpha -= (alpha / alphadec) | 0; + radius -= (radius / NeuQuant._radiusDecrease) | 0; + rad = radius >> NeuQuant._radiusBiasShift; + + if (rad <= 1) rad = 0; + for (let j = 0; j < rad; j++) { + this._radPower[j] = + (alpha * + (((rad * rad - j * j) * NeuQuant._radBias) / (rad * rad))) >>> + 0; + } + } + } + } + + private _buildPalette() { + const palette = new Palette(); + + this._network.forEach((neuron) => { + palette.add(neuron.toPoint()); + }); + + palette.sort(); + return palette; + } + + /** + * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|] + */ + private _alterNeighbour( + rad: number, + i: number, + b: number, + g: number, + r: number, + al: number, + ) { + let lo = i - rad; + if (lo < -1) lo = -1; + + let hi = i + rad; + if (hi > this._networkSize) hi = this._networkSize; + + let j = i + 1; + let k = i - 1; + let m = 1; + + while (j < hi || k > lo) { + const a = this._radPower[m++] / NeuQuant._alphaRadBias; + if (j < hi) { + const p = this._network[j++]; + p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al)); + } + + if (k > lo) { + const p = this._network[k--]; + p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al)); + } + } + } + + /** + * Move neuron i towards biased (b,g,r) by factor alpha + */ + private _alterSingle( + alpha: number, + i: number, + b: number, + g: number, + r: number, + a: number, + ) { + alpha /= NeuQuant._initAlpha; + + /* alter hit neuron */ + const n = this._network[i]; + n.subtract( + alpha * (n.r - r), + alpha * (n.g - g), + alpha * (n.b - b), + alpha * (n.a - a), + ); + } + + /** + * Search for biased BGR values + * description: + * finds closest neuron (min dist) and updates freq + * finds best neuron (min dist-bias) and returns position + * for frequently chosen neurons, freq[i] is high and bias[i] is negative + * bias[i] = _gamma*((1/this._networkSize)-freq[i]) + * + * Original distance equation: + * dist = abs(dR) + abs(dG) + abs(dB) + */ + private _contest(b: number, g: number, r: number, a: number) { + const multiplier = (255 * 4) << networkBiasShift; + + let bestd = ~(1 << 31); + let bestbiasd = bestd; + let bestpos = -1; + let bestbiaspos = bestpos; + + for (let i = 0; i < this._networkSize; i++) { + const n = this._network[i]; + const dist = + (this._distance.calculateNormalized(n, { r, g, b, a }) * multiplier) | + 0; + + if (dist < bestd) { + bestd = dist; + bestpos = i; + } + + const biasdist = + dist - + (this._bias[i] >> (NeuQuant._initialBiasShift - networkBiasShift)); + if (biasdist < bestbiasd) { + bestbiasd = biasdist; + bestbiaspos = i; + } + const betafreq = this._freq[i] >> NeuQuant._betaShift; + this._freq[i] -= betafreq; + this._bias[i] += betafreq << NeuQuant._gammaShift; + } + this._freq[bestpos] += NeuQuant._beta; + this._bias[bestpos] -= NeuQuant._betaGamma; + return bestbiaspos; + } +} diff --git a/node_modules/image-q/src/palette/neuquant/neuquantFloat.ts b/node_modules/image-q/src/palette/neuquant/neuquantFloat.ts new file mode 100644 index 00000000..0a7452e6 --- /dev/null +++ b/node_modules/image-q/src/palette/neuquant/neuquantFloat.ts @@ -0,0 +1,383 @@ +/* + * NeuQuantFloat Neural-Net Quantization Algorithm + * ------------------------------------------ + * + * Copyright (c) 1994 Anthony Dekker + * + * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See + * "Kohonen neural networks for optimal colour quantization" in "Network: + * Computation in Neural Systems" Vol. 5 (1994) pp 351-367. for a discussion of + * the algorithm. + * + * Any party obtaining a copy of these files from the author, directly or + * indirectly, is granted, free of charge, a full and unrestricted irrevocable, + * world-wide, paid up, royalty-free, nonexclusive right and license to deal in + * this software and documentation files (the "Software"), including without + * limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons who + * receive copies from any such party to do so, with the only requirement being + * that this copyright notice remain intact. + */ +/** + * @preserve TypeScript port: + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * neuquant.ts - part of Image Quantization Library + */ +import { Palette } from '../../utils/palette'; +import { Point } from '../../utils/point'; +import { PointContainer } from '../../utils/pointContainer'; +import { AbstractDistanceCalculator } from '../../distance/distanceCalculator'; +import { AbstractPaletteQuantizer } from '../paletteQuantizer'; +import { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue'; +import { ProgressTracker } from '../../utils'; + +// bias for colour values +const networkBiasShift = 3; + +class NeuronFloat { + r: number; + g: number; + b: number; + a: number; + + constructor(defaultValue: number) { + this.r = this.g = this.b = this.a = defaultValue; + } + + /** + * There is a fix in original NEUQUANT by Anthony Dekker (http://members.ozemail.com.au/~dekker/NEUQUANT.HTML) + * @example + * r = Math.min(255, (neuron.r + (1 << (networkBiasShift - 1))) >> networkBiasShift); + */ + toPoint() { + return Point.createByRGBA( + this.r >> networkBiasShift, + this.g >> networkBiasShift, + this.b >> networkBiasShift, + this.a >> networkBiasShift, + ); + } + + subtract(r: number, g: number, b: number, a: number) { + this.r -= r; + this.g -= g; + this.b -= b; + this.a -= a; + } +} + +export class NeuQuantFloat extends AbstractPaletteQuantizer { + /* + four primes near 500 - assume no image has a length so large + that it is divisible by all four primes + */ + private static readonly _prime1 = 499; + private static readonly _prime2 = 491; + private static readonly _prime3 = 487; + private static readonly _prime4 = 503; + private static readonly _minpicturebytes = NeuQuantFloat._prime4; + + // no. of learning cycles + private static readonly _nCycles = 100; + + // defs for freq and bias + private static readonly _initialBiasShift = 16; + + // bias for fractions + private static readonly _initialBias = 1 << NeuQuantFloat._initialBiasShift; + private static readonly _gammaShift = 10; + + // gamma = 1024 + // TODO: why gamma is never used? + // private static _gamma : number = (1 << NeuQuantFloat._gammaShift); + private static readonly _betaShift = 10; + private static readonly _beta = + NeuQuantFloat._initialBias >> NeuQuantFloat._betaShift; + + // beta = 1/1024 + private static readonly _betaGamma = + NeuQuantFloat._initialBias << + (NeuQuantFloat._gammaShift - NeuQuantFloat._betaShift); + + /* + * for 256 cols, radius starts + */ + private static readonly _radiusBiasShift = 6; + + // at 32.0 biased by 6 bits + private static readonly _radiusBias = 1 << NeuQuantFloat._radiusBiasShift; + + // and decreases by a factor of 1/30 each cycle + private static readonly _radiusDecrease = 30; + + /* defs for decreasing alpha factor */ + + // alpha starts at 1.0 + private static readonly _alphaBiasShift = 10; + + // biased by 10 bits + private static readonly _initAlpha = 1 << NeuQuantFloat._alphaBiasShift; + + /* radBias and alphaRadBias used for radpower calculation */ + private static readonly _radBiasShift = 8; + private static readonly _radBias = 1 << NeuQuantFloat._radBiasShift; + private static readonly _alphaRadBiasShift = + NeuQuantFloat._alphaBiasShift + NeuQuantFloat._radBiasShift; + private static readonly _alphaRadBias = 1 << NeuQuantFloat._alphaRadBiasShift; + + private _pointArray!: Point[]; + private readonly _networkSize!: number; + private _network!: NeuronFloat[]; + + /** sampling factor 1..30 */ + private readonly _sampleFactor!: number; + private _radPower!: number[]; + + // bias and freq arrays for learning + private _freq!: number[]; + + /* for network lookup - really 256 */ + private _bias!: number[]; + private readonly _distance: AbstractDistanceCalculator; + + constructor( + colorDistanceCalculator: AbstractDistanceCalculator, + colors = 256, + ) { + super(); + this._distance = colorDistanceCalculator; + this._pointArray = []; + this._sampleFactor = 1; + this._networkSize = colors; + + this._distance.setWhitePoint( + 255 << networkBiasShift, + 255 << networkBiasShift, + 255 << networkBiasShift, + 255 << networkBiasShift, + ); + } + + sample(pointContainer: PointContainer) { + this._pointArray = this._pointArray.concat(pointContainer.getPointArray()); + } + + *quantize() { + this._init(); + yield* this._learn(); + + yield { + palette: this._buildPalette(), + progress: 100, + }; + } + + private _init() { + this._freq = []; + this._bias = []; + this._radPower = []; + this._network = []; + for (let i = 0; i < this._networkSize; i++) { + this._network[i] = new NeuronFloat( + (i << (networkBiasShift + 8)) / this._networkSize, + ); + + // 1/this._networkSize + this._freq[i] = NeuQuantFloat._initialBias / this._networkSize; + this._bias[i] = 0; + } + } + + /** + * Main Learning Loop + */ + private *_learn(): IterableIterator { + let sampleFactor = this._sampleFactor; + + const pointsNumber = this._pointArray.length; + if (pointsNumber < NeuQuantFloat._minpicturebytes) sampleFactor = 1; + + const alphadec = 30 + (sampleFactor - 1) / 3; + const pointsToSample = pointsNumber / sampleFactor; + + let delta = (pointsToSample / NeuQuantFloat._nCycles) | 0; + let alpha = NeuQuantFloat._initAlpha; + let radius = (this._networkSize >> 3) * NeuQuantFloat._radiusBias; + + let rad = radius >> NeuQuantFloat._radiusBiasShift; + if (rad <= 1) rad = 0; + + for (let i = 0; i < rad; i++) { + this._radPower[i] = + alpha * (((rad * rad - i * i) * NeuQuantFloat._radBias) / (rad * rad)); + } + + let step; + if (pointsNumber < NeuQuantFloat._minpicturebytes) { + step = 1; + } else if (pointsNumber % NeuQuantFloat._prime1 !== 0) { + step = NeuQuantFloat._prime1; + } else if (pointsNumber % NeuQuantFloat._prime2 !== 0) { + step = NeuQuantFloat._prime2; + } else if (pointsNumber % NeuQuantFloat._prime3 !== 0) { + step = NeuQuantFloat._prime3; + } else { + step = NeuQuantFloat._prime4; + } + + const tracker = new ProgressTracker(pointsToSample, 99); + for (let i = 0, pointIndex = 0; i < pointsToSample; ) { + if (tracker.shouldNotify(i)) { + yield { + progress: tracker.progress, + }; + } + + const point = this._pointArray[pointIndex]; + const b = point.b << networkBiasShift; + const g = point.g << networkBiasShift; + const r = point.r << networkBiasShift; + const a = point.a << networkBiasShift; + const neuronIndex = this._contest(b, g, r, a); + + this._alterSingle(alpha, neuronIndex, b, g, r, a); + if (rad !== 0) this._alterNeighbour(rad, neuronIndex, b, g, r, a); + + /* alter neighbours */ + pointIndex += step; + if (pointIndex >= pointsNumber) pointIndex -= pointsNumber; + i++; + + if (delta === 0) delta = 1; + + if (i % delta === 0) { + alpha -= alpha / alphadec; + radius -= radius / NeuQuantFloat._radiusDecrease; + rad = radius >> NeuQuantFloat._radiusBiasShift; + + if (rad <= 1) rad = 0; + for (let j = 0; j < rad; j++) { + this._radPower[j] = + alpha * + (((rad * rad - j * j) * NeuQuantFloat._radBias) / (rad * rad)); + } + } + } + } + + private _buildPalette() { + const palette = new Palette(); + + this._network.forEach((neuron) => { + palette.add(neuron.toPoint()); + }); + + palette.sort(); + return palette; + } + + /** + * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|] + */ + private _alterNeighbour( + rad: number, + i: number, + b: number, + g: number, + r: number, + al: number, + ) { + let lo = i - rad; + if (lo < -1) lo = -1; + + let hi = i + rad; + if (hi > this._networkSize) hi = this._networkSize; + + let j = i + 1; + let k = i - 1; + let m = 1; + + while (j < hi || k > lo) { + const a = this._radPower[m++] / NeuQuantFloat._alphaRadBias; + if (j < hi) { + const p = this._network[j++]; + p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al)); + } + + if (k > lo) { + const p = this._network[k--]; + p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al)); + } + } + } + + /** + * Move neuron i towards biased (b,g,r) by factor alpha + */ + private _alterSingle( + alpha: number, + i: number, + b: number, + g: number, + r: number, + a: number, + ) { + alpha /= NeuQuantFloat._initAlpha; + + /* alter hit neuron */ + const n = this._network[i]; + n.subtract( + alpha * (n.r - r), + alpha * (n.g - g), + alpha * (n.b - b), + alpha * (n.a - a), + ); + } + + /** + * Search for biased BGR values + * description: + * finds closest neuron (min dist) and updates freq + * finds best neuron (min dist-bias) and returns position + * for frequently chosen neurons, freq[i] is high and bias[i] is negative + * bias[i] = _gamma*((1/this._networkSize)-freq[i]) + * + * Original distance equation: + * dist = abs(dR) + abs(dG) + abs(dB) + */ + private _contest(b: number, g: number, r: number, al: number) { + const multiplier = (255 * 4) << networkBiasShift; + + let bestd = ~(1 << 31); + let bestbiasd = bestd; + let bestpos = -1; + let bestbiaspos = bestpos; + + for (let i = 0; i < this._networkSize; i++) { + const n = this._network[i]; + const dist = + this._distance.calculateNormalized(n, { r, g, b, a: al }) * multiplier; + + if (dist < bestd) { + bestd = dist; + bestpos = i; + } + + const biasdist = + dist - + (this._bias[i] >> (NeuQuantFloat._initialBiasShift - networkBiasShift)); + if (biasdist < bestbiasd) { + bestbiasd = biasdist; + bestbiaspos = i; + } + const betafreq = this._freq[i] >> NeuQuantFloat._betaShift; + this._freq[i] -= betafreq; + this._bias[i] += betafreq << NeuQuantFloat._gammaShift; + } + this._freq[bestpos] += NeuQuantFloat._beta; + this._bias[bestpos] -= NeuQuantFloat._betaGamma; + return bestbiaspos; + } +} diff --git a/node_modules/image-q/src/palette/paletteQuantizer.ts b/node_modules/image-q/src/palette/paletteQuantizer.ts new file mode 100644 index 00000000..2f8f21be --- /dev/null +++ b/node_modules/image-q/src/palette/paletteQuantizer.ts @@ -0,0 +1,24 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * common.ts - part of Image Quantization Library + */ +import { PointContainer } from '../utils/pointContainer'; +import { PaletteQuantizerYieldValue } from './paletteQuantizerYieldValue'; + +export abstract class AbstractPaletteQuantizer { + abstract sample(pointContainer: PointContainer): void; + abstract quantize(): IterableIterator; + + quantizeSync() { + for (const value of this.quantize()) { + if (value.palette) { + return value.palette; + } + } + + throw new Error('unreachable'); + } +} diff --git a/node_modules/image-q/src/palette/paletteQuantizerYieldValue.ts b/node_modules/image-q/src/palette/paletteQuantizerYieldValue.ts new file mode 100644 index 00000000..8803d8fb --- /dev/null +++ b/node_modules/image-q/src/palette/paletteQuantizerYieldValue.ts @@ -0,0 +1,6 @@ +import { Palette } from '../utils'; + +export interface PaletteQuantizerYieldValue { + progress: number; + palette?: Palette; +} diff --git a/node_modules/image-q/src/palette/rgbquant/colorHistogram.ts b/node_modules/image-q/src/palette/rgbquant/colorHistogram.ts new file mode 100644 index 00000000..42928584 --- /dev/null +++ b/node_modules/image-q/src/palette/rgbquant/colorHistogram.ts @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2015, Leon Sorokin + * All rights reserved. (MIT Licensed) + * + * ColorHistogram.js - an image quantization lib + */ + +/** + * @preserve TypeScript port: + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * colorHistogram.ts - part of Image Quantization Library + */ +import { HueStatistics } from '../../utils/hueStatistics'; +import { PointContainer } from '../../utils/pointContainer'; +import { stableSort } from '../../utils/arithmetic'; + +interface Box { + x: number; + y: number; + h: number; + w: number; +} + +export class ColorHistogram { + private static _boxSize = [64, 64]; + private static _boxPixels = 2; + private static _hueGroups = 10; + + // 1 = by global population, 2 = subregion population threshold + private _method: number; + + // HueStatistics instance + private _hueStats: HueStatistics; + + private _histogram: { [color: string]: number }; + + // # of highest-frequency colors to start with for palette reduction + private _initColors: number; + + // if > 0, enables hues stats and min-color retention per group + private _minHueCols: number; + + constructor(method: number, colors: number) { + // 1 = by global population, 2 = subregion population threshold + this._method = method; + + // if > 0, enables hues stats and min-color retention per group + this._minHueCols = colors << 2; // opts.minHueCols || 0; + + // # of highest-frequency colors to start with for palette reduction + this._initColors = colors << 2; + + // HueStatistics instance + this._hueStats = new HueStatistics( + ColorHistogram._hueGroups, + this._minHueCols, + ); + + this._histogram = Object.create(null); + } + + sample(pointContainer: PointContainer) { + switch (this._method) { + case 1: + this._colorStats1D(pointContainer); + break; + case 2: + this._colorStats2D(pointContainer); + break; + } + } + + getImportanceSortedColorsIDXI32() { + // TODO: fix typing issue in stableSort func + const sorted = stableSort( + Object.keys(this._histogram), + (a, b) => this._histogram[b] - this._histogram[a], + ); + if (sorted.length === 0) { + return []; + } + + let idxi32; + switch (this._method) { + case 1: + const initialColorsLimit = Math.min(sorted.length, this._initColors); + const last = sorted[initialColorsLimit - 1]; + const freq = this._histogram[last]; + + idxi32 = sorted.slice(0, initialColorsLimit); + + // add any cut off colors with same freq as last + let pos = initialColorsLimit; + const len = sorted.length; + while (pos < len && this._histogram[sorted[pos]] === freq) { + idxi32.push(sorted[pos++]); + } + + // inject min huegroup colors + this._hueStats.injectIntoArray(idxi32); + break; + + case 2: + idxi32 = sorted; + break; + + default: + // TODO: rethink errors + throw new Error('Incorrect method'); + } + + // int32-ify values + return idxi32.map((v) => +v); + } + + // global top-population + private _colorStats1D(pointContainer: PointContainer) { + const histG = this._histogram; + const pointArray = pointContainer.getPointArray(); + const len = pointArray.length; + + for (let i = 0; i < len; i++) { + const col = pointArray[i].uint32; + + // collect hue stats + this._hueStats.check(col); + + if (col in histG) { + histG[col]++; + } else { + histG[col] = 1; + } + } + } + + // population threshold within subregions + // FIXME: this can over-reduce (few/no colors same?), need a way to keep + // important colors that dont ever reach local thresholds (gradients?) + private _colorStats2D(pointContainer: PointContainer) { + const width = pointContainer.getWidth(); + const height = pointContainer.getHeight(); + const pointArray = pointContainer.getPointArray(); + + const boxW = ColorHistogram._boxSize[0]; + const boxH = ColorHistogram._boxSize[1]; + const area = boxW * boxH; + const boxes = this._makeBoxes(width, height, boxW, boxH); + const histG = this._histogram; + + boxes.forEach((box) => { + let effc = Math.round((box.w * box.h) / area) * ColorHistogram._boxPixels; + if (effc < 2) effc = 2; + + const histL: Record = {}; + this._iterateBox(box, width, (i) => { + const col = pointArray[i].uint32; + + // collect hue stats + this._hueStats.check(col); + + if (col in histG) { + histG[col]++; + } else if (col in histL) { + if (++histL[col] >= effc) { + histG[col] = histL[col]; + } + } else { + histL[col] = 1; + } + }); + }); + + // inject min huegroup colors + this._hueStats.injectIntoDictionary(histG); + } + + // iterates @bbox within a parent rect of width @wid; calls @fn, passing index within parent + private _iterateBox(bbox: Box, wid: number, fn: (i: number) => void) { + const b = bbox; + const i0 = b.y * wid + b.x; + const i1 = (b.y + b.h - 1) * wid + (b.x + b.w - 1); + const incr = wid - b.w + 1; + + let cnt = 0; + let i = i0; + + do { + fn.call(this, i); + i += ++cnt % b.w === 0 ? incr : 1; + } while (i <= i1); + } + + /** + * partitions a rectangle of width x height into + * array of boxes stepX x stepY (or less) + */ + private _makeBoxes( + width: number, + height: number, + stepX: number, + stepY: number, + ) { + const wrem = width % stepX; + const hrem = height % stepY; + const xend = width - wrem; + const yend = height - hrem; + const boxesArray = []; + + for (let y = 0; y < height; y += stepY) { + for (let x = 0; x < width; x += stepX) { + boxesArray.push({ + x, + y, + w: x === xend ? wrem : stepX, + h: y === yend ? hrem : stepY, + }); + } + } + + return boxesArray; + } +} diff --git a/node_modules/image-q/src/palette/rgbquant/rgbquant.ts b/node_modules/image-q/src/palette/rgbquant/rgbquant.ts new file mode 100644 index 00000000..9c4b9484 --- /dev/null +++ b/node_modules/image-q/src/palette/rgbquant/rgbquant.ts @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2015, Leon Sorokin + * All rights reserved. (MIT Licensed) + * + * RGBQuant.js - an image quantization lib + */ + +/** + * @preserve TypeScript port: + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * rgbquant.ts - part of Image Quantization Library + */ + +import { Palette } from '../../utils/palette'; +import { Point } from '../../utils/point'; +import { PointContainer } from '../../utils/pointContainer'; +import { AbstractDistanceCalculator } from '../../distance/distanceCalculator'; +import { ColorHistogram } from './colorHistogram'; +import { AbstractPaletteQuantizer } from '../paletteQuantizer'; +import { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue'; +import { stableSort } from '../../utils/arithmetic'; +import { ProgressTracker } from '../../utils'; + +class RemovedColor { + readonly index: number; + readonly color: Point; + readonly distance: number; + + constructor(index: number, color: Point, distance: number) { + this.index = index; + this.color = color; + this.distance = distance; + } +} + +// TODO: make input/output image and input/output palettes with instances of class Point only! +export class RGBQuant extends AbstractPaletteQuantizer { + // desired final palette size + private readonly _colors: number; + + // color-distance threshold for initial reduction pass + private readonly _initialDistance: number; + + // subsequent passes threshold + private readonly _distanceIncrement: number; + + // accumulated histogram + private readonly _histogram: ColorHistogram; + private readonly _distance: AbstractDistanceCalculator; + + constructor( + colorDistanceCalculator: AbstractDistanceCalculator, + colors = 256, + method = 2, + ) { + super(); + this._distance = colorDistanceCalculator; + // desired final palette size + this._colors = colors; + + // histogram to accumulate + this._histogram = new ColorHistogram(method, colors); + + this._initialDistance = 0.01; + this._distanceIncrement = 0.005; + } + + // gathers histogram info + sample(image: PointContainer) { + /* + var pointArray = image.getPointArray(), max = [0, 0, 0, 0], min = [255, 255, 255, 255]; + + for (var i = 0, l = pointArray.length; i < l; i++) { + var color = pointArray[i]; + for (var componentIndex = 0; componentIndex < 4; componentIndex++) { + if (max[componentIndex] < color.rgba[componentIndex]) max[componentIndex] = color.rgba[componentIndex]; + if (min[componentIndex] > color.rgba[componentIndex]) min[componentIndex] = color.rgba[componentIndex]; + } + } + var rd = max[0] - min[0], gd = max[1] - min[1], bd = max[2] - min[2], ad = max[3] - min[3]; + this._distance.setWhitePoint(rd, gd, bd, ad); + + this._initialDistance = (Math.sqrt(rd * rd + gd * gd + bd * bd + ad * ad) / Math.sqrt(255 * 255 + 255 * 255 + 255 * 255)) * 0.01; + */ + + this._histogram.sample(image); + } + + // reduces histogram to palette, remaps & memoizes reduced colors + *quantize() { + const idxi32 = this._histogram.getImportanceSortedColorsIDXI32(); + if (idxi32.length === 0) { + throw new Error('No colors in image'); + } + + yield* this._buildPalette(idxi32); + } + + // reduces similar colors from an importance-sorted Uint32 rgba array + private *_buildPalette( + idxi32: number[], + ): IterableIterator { + // reduce histogram to create initial palette + // build full rgb palette + const palette = new Palette(); + const colorArray = palette.getPointContainer().getPointArray(); + const usageArray = new Array(idxi32.length); + + for (let i = 0; i < idxi32.length; i++) { + colorArray.push(Point.createByUint32(idxi32[i])); + usageArray[i] = 1; + } + + const len = colorArray.length; + const memDist = []; + + let palLen = len; + let thold = this._initialDistance; + + // palette already at or below desired length + const tracker = new ProgressTracker(palLen - this._colors, 99); + while (palLen > this._colors) { + memDist.length = 0; + + // iterate palette + for (let i = 0; i < len; i++) { + if (tracker.shouldNotify(len - palLen)) { + yield { + progress: tracker.progress, + }; + } + + if (usageArray[i] === 0) continue; + const pxi = colorArray[i]; + // if (!pxi) continue; + + for (let j = i + 1; j < len; j++) { + if (usageArray[j] === 0) continue; + const pxj = colorArray[j]; + // if (!pxj) continue; + + const dist = this._distance.calculateNormalized(pxi, pxj); + if (dist < thold) { + // store index,rgb,dist + memDist.push(new RemovedColor(j, pxj, dist)); + usageArray[j] = 0; + palLen--; + } + } + } + // palette reduction pass + // console.log("palette length: " + palLen); + + // if palette is still much larger than target, increment by larger initDist + thold += + palLen > this._colors * 3 + ? this._initialDistance + : this._distanceIncrement; + } + + // if palette is over-reduced, re-add removed colors with largest distances from last round + if (palLen < this._colors) { + // sort descending + stableSort(memDist, (a, b) => b.distance - a.distance); + + let k = 0; + while (palLen < this._colors && k < memDist.length) { + const removedColor = memDist[k]; + // re-inject rgb into final palette + usageArray[removedColor.index] = 1; + palLen++; + k++; + } + } + + let colors = colorArray.length; + for (let colorIndex = colors - 1; colorIndex >= 0; colorIndex--) { + if (usageArray[colorIndex] === 0) { + if (colorIndex !== colors - 1) { + colorArray[colorIndex] = colorArray[colors - 1]; + } + --colors; + } + } + colorArray.length = colors; + + palette.sort(); + + yield { + palette, + progress: 100, + }; + } +} diff --git a/node_modules/image-q/src/palette/wu/wuQuant.ts b/node_modules/image-q/src/palette/wu/wuQuant.ts new file mode 100644 index 00000000..25a99da7 --- /dev/null +++ b/node_modules/image-q/src/palette/wu/wuQuant.ts @@ -0,0 +1,1124 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * wuQuant.ts - part of Image Quantization Library + */ +import { Palette } from '../../utils/palette'; +import { Point } from '../../utils/point'; +import { PointContainer } from '../../utils/pointContainer'; +import { AbstractDistanceCalculator } from '../../distance/distanceCalculator'; +import { AbstractPaletteQuantizer } from '../paletteQuantizer'; +import { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue'; +import { ProgressTracker } from '../../utils'; + +function createArray1D(dimension1: number) { + const a = []; + for (let k = 0; k < dimension1; k++) { + a[k] = 0; + } + return a; +} + +function createArray4D( + dimension1: number, + dimension2: number, + dimension3: number, + dimension4: number, +): number[][][][] { + const a = new Array(dimension1); + for (let i = 0; i < dimension1; i++) { + a[i] = new Array(dimension2); + for (let j = 0; j < dimension2; j++) { + a[i][j] = new Array(dimension3); + for (let k = 0; k < dimension3; k++) { + a[i][j][k] = new Array(dimension4); + for (let l = 0; l < dimension4; l++) { + a[i][j][k][l] = 0; + } + } + } + } + return a; +} + +function createArray3D( + dimension1: number, + dimension2: number, + dimension3: number, +): number[][][] { + const a = new Array(dimension1); + for (let i = 0; i < dimension1; i++) { + a[i] = new Array(dimension2); + for (let j = 0; j < dimension2; j++) { + a[i][j] = new Array(dimension3); + for (let k = 0; k < dimension3; k++) { + a[i][j][k] = 0; + } + } + } + return a; +} + +function fillArray3D( + a: T[][][], + dimension1: number, + dimension2: number, + dimension3: number, + value: T, +) { + for (let i = 0; i < dimension1; i++) { + a[i] = []; + for (let j = 0; j < dimension2; j++) { + a[i][j] = []; + for (let k = 0; k < dimension3; k++) { + a[i][j][k] = value; + } + } + } +} + +function fillArray1D(a: T[], dimension1: number, value: T) { + for (let i = 0; i < dimension1; i++) { + a[i] = value; + } +} + +export class WuColorCube { + redMinimum!: number; + redMaximum!: number; + greenMinimum!: number; + greenMaximum!: number; + blueMinimum!: number; + blueMaximum!: number; + volume!: number; + alphaMinimum!: number; + alphaMaximum!: number; +} + +export class WuQuant extends AbstractPaletteQuantizer { + private static readonly _alpha = 3; + private static readonly _red = 2; + private static readonly _green = 1; + private static readonly _blue = 0; + + private _reds!: number[]; + private _greens!: number[]; + private _blues!: number[]; + private _alphas!: number[]; + private _sums!: number[]; + + private _weights!: number[][][][]; + private _momentsRed!: number[][][][]; + private _momentsGreen!: number[][][][]; + private _momentsBlue!: number[][][][]; + private _momentsAlpha!: number[][][][]; + private _moments!: number[][][][]; + private _table!: number[]; + private _pixels!: Point[]; + + private _cubes!: WuColorCube[]; + private _colors!: number; + + private _significantBitsPerChannel!: number; + private _maxSideIndex!: number; + private _alphaMaxSideIndex!: number; + private _sideSize!: number; + private _alphaSideSize!: number; + + private readonly _distance: AbstractDistanceCalculator; + + constructor( + colorDistanceCalculator: AbstractDistanceCalculator, + colors = 256, + significantBitsPerChannel = 5, + ) { + super(); + this._distance = colorDistanceCalculator; + this._setQuality(significantBitsPerChannel); + this._initialize(colors); + } + + sample(image: PointContainer) { + const pointArray = image.getPointArray(); + + for (let i = 0, l = pointArray.length; i < l; i++) { + this._addColor(pointArray[i]); + } + + this._pixels = this._pixels.concat(pointArray); + } + + *quantize() { + yield* this._preparePalette(); + + const palette = new Palette(); + + // generates palette + for (let paletteIndex = 0; paletteIndex < this._colors; paletteIndex++) { + if (this._sums[paletteIndex] > 0) { + const sum = this._sums[paletteIndex]; + const r = this._reds[paletteIndex] / sum; + const g = this._greens[paletteIndex] / sum; + const b = this._blues[paletteIndex] / sum; + const a = this._alphas[paletteIndex] / sum; + + const color = Point.createByRGBA(r | 0, g | 0, b | 0, a | 0); + palette.add(color); + } + } + + palette.sort(); + + yield { + palette, + progress: 100, + }; + } + + private *_preparePalette() { + // preprocess the colors + yield* this._calculateMoments(); + + let next = 0; + const volumeVariance = createArray1D(this._colors); + + // processes the cubes + for (let cubeIndex = 1; cubeIndex < this._colors; ++cubeIndex) { + // if cut is possible; make it + if (this._cut(this._cubes[next], this._cubes[cubeIndex])) { + volumeVariance[next] = + this._cubes[next].volume > 1 + ? this._calculateVariance(this._cubes[next]) + : 0.0; + volumeVariance[cubeIndex] = + this._cubes[cubeIndex].volume > 1 + ? this._calculateVariance(this._cubes[cubeIndex]) + : 0.0; + } else { + // the cut was not possible, revert the index + volumeVariance[next] = 0.0; + cubeIndex--; + } + + next = 0; + let temp = volumeVariance[0]; + + for (let index = 1; index <= cubeIndex; ++index) { + if (volumeVariance[index] > temp) { + temp = volumeVariance[index]; + next = index; + } + } + + if (temp <= 0.0) { + this._colors = cubeIndex + 1; + break; + } + } + + const lookupRed = []; + const lookupGreen = []; + const lookupBlue = []; + const lookupAlpha = []; + + // precalculates lookup tables + for (let k = 0; k < this._colors; ++k) { + const weight = WuQuant._volume(this._cubes[k], this._weights); + + if (weight > 0) { + lookupRed[k] = + (WuQuant._volume(this._cubes[k], this._momentsRed) / weight) | 0; + lookupGreen[k] = + (WuQuant._volume(this._cubes[k], this._momentsGreen) / weight) | 0; + lookupBlue[k] = + (WuQuant._volume(this._cubes[k], this._momentsBlue) / weight) | 0; + lookupAlpha[k] = + (WuQuant._volume(this._cubes[k], this._momentsAlpha) / weight) | 0; + } else { + lookupRed[k] = 0; + lookupGreen[k] = 0; + lookupBlue[k] = 0; + lookupAlpha[k] = 0; + } + } + + this._reds = createArray1D(this._colors + 1); + this._greens = createArray1D(this._colors + 1); + this._blues = createArray1D(this._colors + 1); + this._alphas = createArray1D(this._colors + 1); + this._sums = createArray1D(this._colors + 1); + + // scans and adds colors + for (let index = 0, l = this._pixels.length; index < l; index++) { + const color = this._pixels[index]; + + const match = -1; + + let bestMatch = match; + let bestDistance = Number.MAX_VALUE; + + for (let lookup = 0; lookup < this._colors; lookup++) { + const foundRed = lookupRed[lookup]; + const foundGreen = lookupGreen[lookup]; + const foundBlue = lookupBlue[lookup]; + const foundAlpha = lookupAlpha[lookup]; + + const distance = this._distance.calculateRaw( + foundRed, + foundGreen, + foundBlue, + foundAlpha, + color.r, + color.g, + color.b, + color.a, + ); + + if (distance < bestDistance) { + bestDistance = distance; + bestMatch = lookup; + } + } + + this._reds[bestMatch] += color.r; + this._greens[bestMatch] += color.g; + this._blues[bestMatch] += color.b; + this._alphas[bestMatch] += color.a; + this._sums[bestMatch]++; + } + } + + private _addColor(color: Point) { + const bitsToRemove = 8 - this._significantBitsPerChannel; + const indexRed = (color.r >> bitsToRemove) + 1; + const indexGreen = (color.g >> bitsToRemove) + 1; + const indexBlue = (color.b >> bitsToRemove) + 1; + const indexAlpha = (color.a >> bitsToRemove) + 1; + + // if(color.a > 10) { + this._weights[indexAlpha][indexRed][indexGreen][indexBlue]++; + this._momentsRed[indexAlpha][indexRed][indexGreen][indexBlue] += color.r; + this._momentsGreen[indexAlpha][indexRed][indexGreen][indexBlue] += color.g; + this._momentsBlue[indexAlpha][indexRed][indexGreen][indexBlue] += color.b; + this._momentsAlpha[indexAlpha][indexRed][indexGreen][indexBlue] += color.a; + this._moments[indexAlpha][indexRed][indexGreen][indexBlue] += + this._table[color.r] + + this._table[color.g] + + this._table[color.b] + + this._table[color.a]; + // } + } + + /** + * Converts the histogram to a series of _moments. + */ + private *_calculateMoments(): IterableIterator { + const area: number[] = []; + const areaRed: number[] = []; + const areaGreen: number[] = []; + const areaBlue: number[] = []; + const areaAlpha: number[] = []; + const area2: number[] = []; + + const xarea = createArray3D(this._sideSize, this._sideSize, this._sideSize); + const xareaRed = createArray3D( + this._sideSize, + this._sideSize, + this._sideSize, + ); + const xareaGreen = createArray3D( + this._sideSize, + this._sideSize, + this._sideSize, + ); + const xareaBlue = createArray3D( + this._sideSize, + this._sideSize, + this._sideSize, + ); + const xareaAlpha = createArray3D( + this._sideSize, + this._sideSize, + this._sideSize, + ); + const xarea2 = createArray3D( + this._sideSize, + this._sideSize, + this._sideSize, + ); + + let trackerProgress = 0; + const tracker = new ProgressTracker( + this._alphaMaxSideIndex * this._maxSideIndex, + 99, + ); + + for ( + let alphaIndex = 1; + alphaIndex <= this._alphaMaxSideIndex; + ++alphaIndex + ) { + fillArray3D( + xarea, + this._sideSize, + this._sideSize, + this._sideSize, + 0, + ); + fillArray3D( + xareaRed, + this._sideSize, + this._sideSize, + this._sideSize, + 0, + ); + fillArray3D( + xareaGreen, + this._sideSize, + this._sideSize, + this._sideSize, + 0, + ); + fillArray3D( + xareaBlue, + this._sideSize, + this._sideSize, + this._sideSize, + 0, + ); + fillArray3D( + xareaAlpha, + this._sideSize, + this._sideSize, + this._sideSize, + 0, + ); + fillArray3D( + xarea2, + this._sideSize, + this._sideSize, + this._sideSize, + 0, + ); + + for ( + let redIndex = 1; + redIndex <= this._maxSideIndex; + ++redIndex, ++trackerProgress + ) { + if (tracker.shouldNotify(trackerProgress)) { + yield { + progress: tracker.progress, + }; + } + + fillArray1D(area, this._sideSize, 0); + fillArray1D(areaRed, this._sideSize, 0); + fillArray1D(areaGreen, this._sideSize, 0); + fillArray1D(areaBlue, this._sideSize, 0); + fillArray1D(areaAlpha, this._sideSize, 0); + fillArray1D(area2, this._sideSize, 0); + + for ( + let greenIndex = 1; + greenIndex <= this._maxSideIndex; + ++greenIndex + ) { + let line = 0; + let lineRed = 0; + let lineGreen = 0; + let lineBlue = 0; + let lineAlpha = 0; + let line2 = 0.0; + + for ( + let blueIndex = 1; + blueIndex <= this._maxSideIndex; + ++blueIndex + ) { + line += this._weights[alphaIndex][redIndex][greenIndex][blueIndex]; + lineRed += + this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex]; + lineGreen += + this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex]; + lineBlue += + this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex]; + lineAlpha += + this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex]; + line2 += this._moments[alphaIndex][redIndex][greenIndex][blueIndex]; + + area[blueIndex] += line; + areaRed[blueIndex] += lineRed; + areaGreen[blueIndex] += lineGreen; + areaBlue[blueIndex] += lineBlue; + areaAlpha[blueIndex] += lineAlpha; + area2[blueIndex] += line2; + + xarea[redIndex][greenIndex][blueIndex] = + xarea[redIndex - 1][greenIndex][blueIndex] + area[blueIndex]; + xareaRed[redIndex][greenIndex][blueIndex] = + xareaRed[redIndex - 1][greenIndex][blueIndex] + + areaRed[blueIndex]; + xareaGreen[redIndex][greenIndex][blueIndex] = + xareaGreen[redIndex - 1][greenIndex][blueIndex] + + areaGreen[blueIndex]; + xareaBlue[redIndex][greenIndex][blueIndex] = + xareaBlue[redIndex - 1][greenIndex][blueIndex] + + areaBlue[blueIndex]; + xareaAlpha[redIndex][greenIndex][blueIndex] = + xareaAlpha[redIndex - 1][greenIndex][blueIndex] + + areaAlpha[blueIndex]; + xarea2[redIndex][greenIndex][blueIndex] = + xarea2[redIndex - 1][greenIndex][blueIndex] + area2[blueIndex]; + + this._weights[alphaIndex][redIndex][greenIndex][blueIndex] = + this._weights[alphaIndex - 1][redIndex][greenIndex][blueIndex] + + xarea[redIndex][greenIndex][blueIndex]; + this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex] = + this._momentsRed[alphaIndex - 1][redIndex][greenIndex][ + blueIndex + ] + xareaRed[redIndex][greenIndex][blueIndex]; + this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex] = + this._momentsGreen[alphaIndex - 1][redIndex][greenIndex][ + blueIndex + ] + xareaGreen[redIndex][greenIndex][blueIndex]; + this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex] = + this._momentsBlue[alphaIndex - 1][redIndex][greenIndex][ + blueIndex + ] + xareaBlue[redIndex][greenIndex][blueIndex]; + this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex] = + this._momentsAlpha[alphaIndex - 1][redIndex][greenIndex][ + blueIndex + ] + xareaAlpha[redIndex][greenIndex][blueIndex]; + this._moments[alphaIndex][redIndex][greenIndex][blueIndex] = + this._moments[alphaIndex - 1][redIndex][greenIndex][blueIndex] + + xarea2[redIndex][greenIndex][blueIndex]; + } + } + } + } + } + + /** + * Computes the volume of the cube in a specific moment. + */ + private static _volumeFloat(cube: WuColorCube, moment: number[][][][]) { + return ( + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][ + cube.blueMaximum + ] - + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][ + cube.blueMaximum + ] - + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][ + cube.blueMaximum + ] + + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][ + cube.blueMaximum + ] - + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][ + cube.blueMaximum + ] + + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][ + cube.blueMaximum + ] + + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][ + cube.blueMaximum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMaximum + ] - + (moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][ + cube.blueMinimum + ] - + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][ + cube.blueMinimum + ] - + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][ + cube.blueMinimum + ] - + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][ + cube.blueMinimum + ] + + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ]) + ); + } + + /** + * Computes the volume of the cube in a specific moment. + */ + private static _volume(cube: WuColorCube, moment: number[][][][]) { + return WuQuant._volumeFloat(cube, moment) | 0; + } + + /** + * Splits the cube in given position][and color direction. + */ + private static _top( + cube: WuColorCube, + direction: number, + position: number, + moment: number[][][][], + ) { + let result; + switch (direction) { + case WuQuant._alpha: + result = + moment[position][cube.redMaximum][cube.greenMaximum][ + cube.blueMaximum + ] - + moment[position][cube.redMaximum][cube.greenMinimum][ + cube.blueMaximum + ] - + moment[position][cube.redMinimum][cube.greenMaximum][ + cube.blueMaximum + ] + + moment[position][cube.redMinimum][cube.greenMinimum][ + cube.blueMaximum + ] - + (moment[position][cube.redMaximum][cube.greenMaximum][ + cube.blueMinimum + ] - + moment[position][cube.redMaximum][cube.greenMinimum][ + cube.blueMinimum + ] - + moment[position][cube.redMinimum][cube.greenMaximum][ + cube.blueMinimum + ] + + moment[position][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ]); + break; + + case WuQuant._red: + result = + moment[cube.alphaMaximum][position][cube.greenMaximum][ + cube.blueMaximum + ] - + moment[cube.alphaMaximum][position][cube.greenMinimum][ + cube.blueMaximum + ] - + moment[cube.alphaMinimum][position][cube.greenMaximum][ + cube.blueMaximum + ] + + moment[cube.alphaMinimum][position][cube.greenMinimum][ + cube.blueMaximum + ] - + (moment[cube.alphaMaximum][position][cube.greenMaximum][ + cube.blueMinimum + ] - + moment[cube.alphaMaximum][position][cube.greenMinimum][ + cube.blueMinimum + ] - + moment[cube.alphaMinimum][position][cube.greenMaximum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][position][cube.greenMinimum][ + cube.blueMinimum + ]); + break; + + case WuQuant._green: + result = + moment[cube.alphaMaximum][cube.redMaximum][position][ + cube.blueMaximum + ] - + moment[cube.alphaMaximum][cube.redMinimum][position][ + cube.blueMaximum + ] - + moment[cube.alphaMinimum][cube.redMaximum][position][ + cube.blueMaximum + ] + + moment[cube.alphaMinimum][cube.redMinimum][position][ + cube.blueMaximum + ] - + (moment[cube.alphaMaximum][cube.redMaximum][position][ + cube.blueMinimum + ] - + moment[cube.alphaMaximum][cube.redMinimum][position][ + cube.blueMinimum + ] - + moment[cube.alphaMinimum][cube.redMaximum][position][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMinimum][position][ + cube.blueMinimum + ]); + break; + + case WuQuant._blue: + result = + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][ + position + ] - + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][ + position + ] - + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][ + position + ] + + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][ + position + ] - + (moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][ + position + ] - + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][ + position + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][ + position + ] + + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + position + ]); + break; + default: + throw new Error('impossible'); + } + + return result | 0; + } + + /** + * Splits the cube in a given color direction at its minimum. + */ + private static _bottom( + cube: WuColorCube, + direction: number, + moment: number[][][][], + ) { + switch (direction) { + case WuQuant._alpha: + return ( + -moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][ + cube.blueMaximum + ] + + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][ + cube.blueMaximum + ] + + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][ + cube.blueMaximum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMaximum + ] - + (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][ + cube.blueMinimum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ]) + ); + + case WuQuant._red: + return ( + -moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][ + cube.blueMaximum + ] + + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][ + cube.blueMaximum + ] + + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][ + cube.blueMaximum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMaximum + ] - + (-moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][ + cube.blueMinimum + ] + + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][ + cube.blueMinimum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ]) + ); + + case WuQuant._green: + return ( + -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][ + cube.blueMaximum + ] + + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][ + cube.blueMaximum + ] + + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][ + cube.blueMaximum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMaximum + ] - + (-moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][ + cube.blueMinimum + ] + + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][ + cube.blueMinimum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ]) + ); + + case WuQuant._blue: + return ( + -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][ + cube.blueMinimum + ] + + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][ + cube.blueMinimum + ] + + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][ + cube.blueMinimum + ] - + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ] - + (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][ + cube.blueMinimum + ] + + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][ + cube.blueMinimum + ] - + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][ + cube.blueMinimum + ]) + ); + + default: + // TODO: why here is return 0, and in this._top there is no default at all (now it is throw error)? + return 0; + } + } + + /** + * Calculates statistical variance for a given cube. + */ + private _calculateVariance(cube: WuColorCube) { + const volumeRed = WuQuant._volume(cube, this._momentsRed); + const volumeGreen = WuQuant._volume(cube, this._momentsGreen); + const volumeBlue = WuQuant._volume(cube, this._momentsBlue); + const volumeAlpha = WuQuant._volume(cube, this._momentsAlpha); + const volumeMoment = WuQuant._volumeFloat(cube, this._moments); + const volumeWeight = WuQuant._volume(cube, this._weights); + const distance = + volumeRed * volumeRed + + volumeGreen * volumeGreen + + volumeBlue * volumeBlue + + volumeAlpha * volumeAlpha; + + return volumeMoment - distance / volumeWeight; + } + + /** + * Finds the optimal (maximal) position for the cut. + */ + private _maximize( + cube: WuColorCube, + direction: number, + first: number, + last: number, + wholeRed: number, + wholeGreen: number, + wholeBlue: number, + wholeAlpha: number, + wholeWeight: number, + ) { + const bottomRed = WuQuant._bottom(cube, direction, this._momentsRed) | 0; + const bottomGreen = + WuQuant._bottom(cube, direction, this._momentsGreen) | 0; + const bottomBlue = WuQuant._bottom(cube, direction, this._momentsBlue) | 0; + const bottomAlpha = + WuQuant._bottom(cube, direction, this._momentsAlpha) | 0; + const bottomWeight = WuQuant._bottom(cube, direction, this._weights) | 0; + + let result = 0.0; + let cutPosition = -1; + + for (let position = first; position < last; ++position) { + // determines the cube cut at a certain position + let halfRed = + bottomRed + WuQuant._top(cube, direction, position, this._momentsRed); + let halfGreen = + bottomGreen + + WuQuant._top(cube, direction, position, this._momentsGreen); + let halfBlue = + bottomBlue + WuQuant._top(cube, direction, position, this._momentsBlue); + let halfAlpha = + bottomAlpha + + WuQuant._top(cube, direction, position, this._momentsAlpha); + let halfWeight = + bottomWeight + WuQuant._top(cube, direction, position, this._weights); + + // the cube cannot be cut at bottom (this would lead to empty cube) + if (halfWeight !== 0) { + let halfDistance = + halfRed * halfRed + + halfGreen * halfGreen + + halfBlue * halfBlue + + halfAlpha * halfAlpha; + let temp = halfDistance / halfWeight; + + halfRed = wholeRed - halfRed; + halfGreen = wholeGreen - halfGreen; + halfBlue = wholeBlue - halfBlue; + halfAlpha = wholeAlpha - halfAlpha; + halfWeight = wholeWeight - halfWeight; + + if (halfWeight !== 0) { + halfDistance = + halfRed * halfRed + + halfGreen * halfGreen + + halfBlue * halfBlue + + halfAlpha * halfAlpha; + temp += halfDistance / halfWeight; + + if (temp > result) { + result = temp; + cutPosition = position; + } + } + } + } + + return { max: result, position: cutPosition }; + } + + // Cuts a cube with another one. + private _cut(first: WuColorCube, second: WuColorCube) { + let direction; + + const wholeRed = WuQuant._volume(first, this._momentsRed); + const wholeGreen = WuQuant._volume(first, this._momentsGreen); + const wholeBlue = WuQuant._volume(first, this._momentsBlue); + const wholeAlpha = WuQuant._volume(first, this._momentsAlpha); + const wholeWeight = WuQuant._volume(first, this._weights); + + const red = this._maximize( + first, + WuQuant._red, + first.redMinimum + 1, + first.redMaximum, + wholeRed, + wholeGreen, + wholeBlue, + wholeAlpha, + wholeWeight, + ); + const green = this._maximize( + first, + WuQuant._green, + first.greenMinimum + 1, + first.greenMaximum, + wholeRed, + wholeGreen, + wholeBlue, + wholeAlpha, + wholeWeight, + ); + const blue = this._maximize( + first, + WuQuant._blue, + first.blueMinimum + 1, + first.blueMaximum, + wholeRed, + wholeGreen, + wholeBlue, + wholeAlpha, + wholeWeight, + ); + const alpha = this._maximize( + first, + WuQuant._alpha, + first.alphaMinimum + 1, + first.alphaMaximum, + wholeRed, + wholeGreen, + wholeBlue, + wholeAlpha, + wholeWeight, + ); + + if ( + alpha.max >= red.max && + alpha.max >= green.max && + alpha.max >= blue.max + ) { + direction = WuQuant._alpha; + + // cannot split empty cube + if (alpha.position < 0) return false; + } else if ( + red.max >= alpha.max && + red.max >= green.max && + red.max >= blue.max + ) { + direction = WuQuant._red; + } else if ( + green.max >= alpha.max && + green.max >= red.max && + green.max >= blue.max + ) { + direction = WuQuant._green; + } else { + direction = WuQuant._blue; + } + + second.redMaximum = first.redMaximum; + second.greenMaximum = first.greenMaximum; + second.blueMaximum = first.blueMaximum; + second.alphaMaximum = first.alphaMaximum; + + // cuts in a certain direction + switch (direction) { + case WuQuant._red: + second.redMinimum = first.redMaximum = red.position; + second.greenMinimum = first.greenMinimum; + second.blueMinimum = first.blueMinimum; + second.alphaMinimum = first.alphaMinimum; + break; + + case WuQuant._green: + second.greenMinimum = first.greenMaximum = green.position; + second.redMinimum = first.redMinimum; + second.blueMinimum = first.blueMinimum; + second.alphaMinimum = first.alphaMinimum; + break; + + case WuQuant._blue: + second.blueMinimum = first.blueMaximum = blue.position; + second.redMinimum = first.redMinimum; + second.greenMinimum = first.greenMinimum; + second.alphaMinimum = first.alphaMinimum; + break; + + case WuQuant._alpha: + second.alphaMinimum = first.alphaMaximum = alpha.position; + second.blueMinimum = first.blueMinimum; + second.redMinimum = first.redMinimum; + second.greenMinimum = first.greenMinimum; + break; + } + + // determines the volumes after cut + first.volume = + (first.redMaximum - first.redMinimum) * + (first.greenMaximum - first.greenMinimum) * + (first.blueMaximum - first.blueMinimum) * + (first.alphaMaximum - first.alphaMinimum); + second.volume = + (second.redMaximum - second.redMinimum) * + (second.greenMaximum - second.greenMinimum) * + (second.blueMaximum - second.blueMinimum) * + (second.alphaMaximum - second.alphaMinimum); + + // the cut was successful + return true; + } + + private _initialize(colors: number) { + this._colors = colors; + + // creates all the _cubes + this._cubes = []; + + // initializes all the _cubes + for (let cubeIndex = 0; cubeIndex < colors; cubeIndex++) { + this._cubes[cubeIndex] = new WuColorCube(); + } + + // resets the reference minimums + this._cubes[0].redMinimum = 0; + this._cubes[0].greenMinimum = 0; + this._cubes[0].blueMinimum = 0; + this._cubes[0].alphaMinimum = 0; + + // resets the reference maximums + this._cubes[0].redMaximum = this._maxSideIndex; + this._cubes[0].greenMaximum = this._maxSideIndex; + this._cubes[0].blueMaximum = this._maxSideIndex; + this._cubes[0].alphaMaximum = this._alphaMaxSideIndex; + + this._weights = createArray4D( + this._alphaSideSize, + this._sideSize, + this._sideSize, + this._sideSize, + ); + this._momentsRed = createArray4D( + this._alphaSideSize, + this._sideSize, + this._sideSize, + this._sideSize, + ); + this._momentsGreen = createArray4D( + this._alphaSideSize, + this._sideSize, + this._sideSize, + this._sideSize, + ); + this._momentsBlue = createArray4D( + this._alphaSideSize, + this._sideSize, + this._sideSize, + this._sideSize, + ); + this._momentsAlpha = createArray4D( + this._alphaSideSize, + this._sideSize, + this._sideSize, + this._sideSize, + ); + this._moments = createArray4D( + this._alphaSideSize, + this._sideSize, + this._sideSize, + this._sideSize, + ); + + this._table = []; + for (let tableIndex = 0; tableIndex < 256; ++tableIndex) { + this._table[tableIndex] = tableIndex * tableIndex; + } + + this._pixels = []; + } + + private _setQuality(significantBitsPerChannel = 5) { + this._significantBitsPerChannel = significantBitsPerChannel; + this._maxSideIndex = 1 << this._significantBitsPerChannel; + this._alphaMaxSideIndex = this._maxSideIndex; + + this._sideSize = this._maxSideIndex + 1; + this._alphaSideSize = this._alphaMaxSideIndex + 1; + } +} diff --git a/node_modules/image-q/src/quality/index.ts b/node_modules/image-q/src/quality/index.ts new file mode 100644 index 00000000..3aaaa7b9 --- /dev/null +++ b/node_modules/image-q/src/quality/index.ts @@ -0,0 +1,8 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * iq.ts - Image Quantization Library + */ +export { ssim } from './ssim'; diff --git a/node_modules/image-q/src/quality/ssim.ts b/node_modules/image-q/src/quality/ssim.ts new file mode 100644 index 00000000..436891ca --- /dev/null +++ b/node_modules/image-q/src/quality/ssim.ts @@ -0,0 +1,145 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * ssim.ts - part of Image Quantization Library + */ +import { PointContainer } from '../utils/pointContainer'; +import { Y } from '../constants/bt709'; + +// based on https://github.com/rhys-e/structural-similarity +// http://en.wikipedia.org/wiki/Structural_similarity +const K1 = 0.01; +const K2 = 0.03; + +export function ssim(image1: PointContainer, image2: PointContainer) { + if ( + image1.getHeight() !== image2.getHeight() || + image1.getWidth() !== image2.getWidth() + ) { + throw new Error('Images have different sizes!'); + } + + const bitsPerComponent = 8; + const L = (1 << bitsPerComponent) - 1; + const c1 = (K1 * L) ** 2; + const c2 = (K2 * L) ** 2; + + let numWindows = 0; + let mssim = 0.0; + + // calculate ssim for each window + iterate( + image1, + image2, + (lumaValues1, lumaValues2, averageLumaValue1, averageLumaValue2) => { + // calculate variance and covariance + let sigxy = 0.0; + let sigsqx = 0.0; + let sigsqy = 0.0; + + for (let i = 0; i < lumaValues1.length; i++) { + sigsqx += (lumaValues1[i] - averageLumaValue1) ** 2; + sigsqy += (lumaValues2[i] - averageLumaValue2) ** 2; + + sigxy += + (lumaValues1[i] - averageLumaValue1) * + (lumaValues2[i] - averageLumaValue2); + } + + const numPixelsInWin = lumaValues1.length - 1; + sigsqx /= numPixelsInWin; + sigsqy /= numPixelsInWin; + sigxy /= numPixelsInWin; + + // perform ssim calculation on window + const numerator = + (2 * averageLumaValue1 * averageLumaValue2 + c1) * (2 * sigxy + c2); + const denominator = + (averageLumaValue1 ** 2 + averageLumaValue2 ** 2 + c1) * + (sigsqx + sigsqy + c2); + const ssim = numerator / denominator; + + mssim += ssim; + numWindows++; + }, + ); + return mssim / numWindows; +} + +function iterate( + image1: PointContainer, + image2: PointContainer, + callback: ( + lumaValues1: number[], + lumaValues2: number[], + averageLumaValue1: number, + averageLumaValue2: number, + ) => void, +) { + const windowSize = 8; + const width = image1.getWidth(); + const height = image1.getHeight(); + + for (let y = 0; y < height; y += windowSize) { + for (let x = 0; x < width; x += windowSize) { + // avoid out-of-width/height + const windowWidth = Math.min(windowSize, width - x); + const windowHeight = Math.min(windowSize, height - y); + + const lumaValues1 = calculateLumaValuesForWindow( + image1, + x, + y, + windowWidth, + windowHeight, + ); + const lumaValues2 = calculateLumaValuesForWindow( + image2, + x, + y, + windowWidth, + windowHeight, + ); + const averageLuma1 = calculateAverageLuma(lumaValues1); + const averageLuma2 = calculateAverageLuma(lumaValues2); + + callback(lumaValues1, lumaValues2, averageLuma1, averageLuma2); + } + } +} + +function calculateLumaValuesForWindow( + image: PointContainer, + x: number, + y: number, + width: number, + height: number, +) { + const pointArray = image.getPointArray(); + const lumaValues = []; + + let counter = 0; + + for (let j = y; j < y + height; j++) { + const offset = j * image.getWidth(); + for (let i = x; i < x + width; i++) { + const point = pointArray[offset + i]; + lumaValues[counter] = + point.r * Y.RED + point.g * Y.GREEN + point.b * Y.BLUE; + counter++; + } + } + + return lumaValues; +} + +function calculateAverageLuma(lumaValues: number[]) { + let sumLuma = 0.0; + for (const luma of lumaValues) { + sumLuma += luma; + } + + return sumLuma / lumaValues.length; +} diff --git a/node_modules/image-q/src/utils/arithmetic.ts b/node_modules/image-q/src/utils/arithmetic.ts new file mode 100644 index 00000000..d9b95206 --- /dev/null +++ b/node_modules/image-q/src/utils/arithmetic.ts @@ -0,0 +1,62 @@ +export function degrees2radians(n: number) { + return n * (Math.PI / 180); +} + +export function max3(a: number, b: number, c: number) { + let m = a; + if (m < b) m = b; + if (m < c) m = c; + return m; +} + +export function min3(a: number, b: number, c: number) { + let m = a; + if (m > b) m = b; + if (m > c) m = c; + return m; +} + +export function intInRange(value: number, low: number, high: number) { + if (value > high) value = high; + if (value < low) value = low; + return value | 0; +} + +export function inRange0to255Rounded(n: number) { + n = Math.round(n); + if (n > 255) n = 255; + else if (n < 0) n = 0; + return n; +} + +export function inRange0to255(n: number) { + if (n > 255) n = 255; + else if (n < 0) n = 0; + return n; +} + +export function stableSort( + arrayToSort: T[], + callback: (a: T, b: T) => number, +) { + const type = typeof arrayToSort[0]; + let sorted: T[]; + + if (type === 'number' || type === 'string') { + const ord = Object.create(null); + for (let i = 0, l = arrayToSort.length; i < l; i++) { + const val = arrayToSort[i] as unknown as string; + if (ord[val] || ord[val] === 0) continue; + ord[val] = i; + } + + sorted = arrayToSort.sort((a, b) => callback(a, b) || ord[a] - ord[b]); + } else { + const ord2 = arrayToSort.slice(0); + sorted = arrayToSort.sort( + (a, b) => callback(a, b) || ord2.indexOf(a) - ord2.indexOf(b), + ); + } + + return sorted; +} diff --git a/node_modules/image-q/src/utils/hueStatistics.ts b/node_modules/image-q/src/utils/hueStatistics.ts new file mode 100644 index 00000000..fb7e6d8f --- /dev/null +++ b/node_modules/image-q/src/utils/hueStatistics.ts @@ -0,0 +1,88 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * hueStatistics.ts - part of Image Quantization Library + */ +import { rgb2hsl } from '../conversion/rgb2hsl'; +import { hueGroup } from './palette'; + +class HueGroup { + num = 0; + cols: number[] = []; +} + +export class HueStatistics { + private _numGroups: number; + private _minCols: number; + private _stats: HueGroup[]; + private _groupsFull: number; + + constructor(numGroups: number, minCols: number) { + this._numGroups = numGroups; + this._minCols = minCols; + this._stats = []; + + for (let i = 0; i <= numGroups; i++) { + this._stats[i] = new HueGroup(); + } + + this._groupsFull = 0; + } + + check(i32: number) { + if (this._groupsFull === this._numGroups + 1) { + this.check = () => {}; + } + + const r = i32 & 0xff; + const g = (i32 >>> 8) & 0xff; + const b = (i32 >>> 16) & 0xff; + const hg = + r === g && g === b + ? 0 + : 1 + hueGroup(rgb2hsl(r, g, b).h, this._numGroups); + const gr = this._stats[hg]; + const min = this._minCols; + + gr.num++; + + if (gr.num > min) { + return; + } + if (gr.num === min) { + this._groupsFull++; + } + + if (gr.num <= min) { + this._stats[hg].cols.push(i32); + } + } + + injectIntoDictionary(histG: Record) { + for (let i = 0; i <= this._numGroups; i++) { + if (this._stats[i].num <= this._minCols) { + this._stats[i].cols.forEach((col: number) => { + if (!histG[col]) { + histG[col] = 1; + } else { + histG[col]++; + } + }); + } + } + } + + injectIntoArray(histG: string[]) { + for (let i = 0; i <= this._numGroups; i++) { + if (this._stats[i].num <= this._minCols) { + this._stats[i].cols.forEach((col: unknown) => { + if (histG.indexOf(col as string) === -1) { + histG.push(col as string); + } + }); + } + } + } +} diff --git a/node_modules/image-q/src/utils/index.ts b/node_modules/image-q/src/utils/index.ts new file mode 100644 index 00000000..3feb682e --- /dev/null +++ b/node_modules/image-q/src/utils/index.ts @@ -0,0 +1,22 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * iq.ts - Image Quantization Library + */ +import * as arithmetic from './arithmetic'; +import { HueStatistics } from './hueStatistics'; +import { Palette } from './palette'; +import { Point } from './point'; +import { PointContainer } from './pointContainer'; +import { ProgressTracker } from './progressTracker'; + +export { + Point, + PointContainer, + Palette, + HueStatistics, + ProgressTracker, + arithmetic, +}; diff --git a/node_modules/image-q/src/utils/palette.ts b/node_modules/image-q/src/utils/palette.ts new file mode 100644 index 00000000..f445bcf5 --- /dev/null +++ b/node_modules/image-q/src/utils/palette.ts @@ -0,0 +1,219 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * palette.ts - part of Image Quantization Library + */ + +import { Point } from './point'; +import { PointContainer } from './pointContainer'; +import { AbstractDistanceCalculator } from '../distance/distanceCalculator'; +import { rgb2hsl } from '../conversion/rgb2hsl'; + +// TODO: make paletteArray via pointContainer, so, export will be available via pointContainer.exportXXX + +const hueGroups = 10; + +export function hueGroup(hue: number, segmentsNumber: number) { + const maxHue = 360; + const seg = maxHue / segmentsNumber; + const half = seg / 2; + + for (let i = 1, mid = seg - half; i < segmentsNumber; i++, mid += seg) { + if (hue >= mid && hue < mid + seg) return i; + } + return 0; +} + +export class Palette { + private readonly _pointContainer: PointContainer; + private readonly _pointArray: Point[] = []; + private _i32idx: { [key: string]: number } = {}; + + constructor() { + this._pointContainer = new PointContainer(); + this._pointContainer.setHeight(1); + this._pointArray = this._pointContainer.getPointArray(); + } + + add(color: Point) { + this._pointArray.push(color); + this._pointContainer.setWidth(this._pointArray.length); + } + + has(color: Point) { + for (let i = this._pointArray.length - 1; i >= 0; i--) { + if (color.uint32 === this._pointArray[i].uint32) return true; + } + + return false; + } + + // TOTRY: use HUSL - http://boronine.com/husl/ http://www.husl-colors.org/ https://github.com/husl-colors/husl + getNearestColor( + colorDistanceCalculator: AbstractDistanceCalculator, + color: Point, + ) { + return this._pointArray[ + this._getNearestIndex(colorDistanceCalculator, color) | 0 + ]; + } + + getPointContainer() { + return this._pointContainer; + } + + // TOTRY: use HUSL - http://boronine.com/husl/ + /* + public nearestIndexByUint32(i32) { + var idx : number = this._nearestPointFromCache("" + i32); + if (idx >= 0) return idx; + + var min = 1000, + rgb = [ + (i32 & 0xff), + (i32 >>> 8) & 0xff, + (i32 >>> 16) & 0xff, + (i32 >>> 24) & 0xff + ], + len = this._pointArray.length; + + idx = 0; + for (var i = 0; i < len; i++) { + var dist = Utils.distEuclidean(rgb, this._pointArray[i].rgba); + + if (dist < min) { + min = dist; + idx = i; + } + } + + this._i32idx[i32] = idx; + return idx; + } + */ + + private _nearestPointFromCache(key: string) { + return typeof this._i32idx[key] === 'number' ? this._i32idx[key] : -1; + } + + private _getNearestIndex( + colorDistanceCalculator: AbstractDistanceCalculator, + point: Point, + ) { + let idx = this._nearestPointFromCache('' + point.uint32); + if (idx >= 0) return idx; + + let minimalDistance = Number.MAX_VALUE; + + idx = 0; + for (let i = 0, l = this._pointArray.length; i < l; i++) { + const p = this._pointArray[i]; + const distance = colorDistanceCalculator.calculateRaw( + point.r, + point.g, + point.b, + point.a, + p.r, + p.g, + p.b, + p.a, + ); + + if (distance < minimalDistance) { + minimalDistance = distance; + idx = i; + } + } + + this._i32idx[point.uint32] = idx; + return idx; + } + + /* + public reduce(histogram : ColorHistogram, colors : number) { + if (this._pointArray.length > colors) { + var idxi32 = histogram.getImportanceSortedColorsIDXI32(); + + // quantize histogram to existing palette + var keep = [], uniqueColors = 0, idx, pruned = false; + + for (var i = 0, len = idxi32.length; i < len; i++) { + // palette length reached, unset all remaining colors (sparse palette) + if (uniqueColors >= colors) { + this.prunePal(keep); + pruned = true; + break; + } else { + idx = this.nearestIndexByUint32(idxi32[i]); + if (keep.indexOf(idx) < 0) { + keep.push(idx); + uniqueColors++; + } + } + } + + if (!pruned) { + this.prunePal(keep); + } + } + } + + // TODO: check usage, not tested! + public prunePal(keep : number[]) { + var colors = this._pointArray.length; + for (var colorIndex = colors - 1; colorIndex >= 0; colorIndex--) { + if (keep.indexOf(colorIndex) < 0) { + + if(colorIndex + 1 < colors) { + this._pointArray[ colorIndex ] = this._pointArray [ colors - 1 ]; + } + --colors; + //this._pointArray[colorIndex] = null; + } + } + console.log("colors pruned: " + (this._pointArray.length - colors)); + this._pointArray.length = colors; + this._i32idx = {}; + } + */ + + // TODO: group very low lum and very high lum colors + // TODO: pass custom sort order + // TODO: sort criteria function should be placed to HueStats class + sort() { + this._i32idx = {}; + this._pointArray.sort((a: Point, b: Point) => { + const hslA = rgb2hsl(a.r, a.g, a.b); + const hslB = rgb2hsl(b.r, b.g, b.b); + + // sort all grays + whites together + const hueA = + a.r === a.g && a.g === a.b ? 0 : 1 + hueGroup(hslA.h, hueGroups); + const hueB = + b.r === b.g && b.g === b.b ? 0 : 1 + hueGroup(hslB.h, hueGroups); + /* + var hueA = (a.r === a.g && a.g === a.b) ? 0 : 1 + Utils.hueGroup(hslA.h, hueGroups); + var hueB = (b.r === b.g && b.g === b.b) ? 0 : 1 + Utils.hueGroup(hslB.h, hueGroups); + */ + + const hueDiff = hueB - hueA; + if (hueDiff) return -hueDiff; + + /* + var lumDiff = Utils.lumGroup(+hslB.l.toFixed(2)) - Utils.lumGroup(+hslA.l.toFixed(2)); + if (lumDiff) return -lumDiff; + */ + const lA = a.getLuminosity(true); + const lB = b.getLuminosity(true); + + if (lB - lA !== 0) return lB - lA; + + const satDiff = ((hslB.s * 100) | 0) - ((hslA.s * 100) | 0); + if (satDiff) return -satDiff; + + return 0; + }); + } +} diff --git a/node_modules/image-q/src/utils/point.ts b/node_modules/image-q/src/utils/point.ts new file mode 100644 index 00000000..fdd5a7ee --- /dev/null +++ b/node_modules/image-q/src/utils/point.ts @@ -0,0 +1,167 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * point.ts - part of Image Quantization Library + */ +import { Y } from '../constants/bt709'; + +export interface PointRGBA { + r: number; + g: number; + b: number; + a: number; +} + +/** + * v8 optimized class + * 1) "constructor" should have initialization with worst types + * 2) "set" should have |0 / >>> 0 + */ +export class Point implements PointRGBA { + r: number; + g: number; + b: number; + a: number; + uint32: number; + rgba: number[]; // TODO: better name is quadruplet or quad may be? + // Lab : { L : number; a : number; b : number }; + + static createByQuadruplet(quadruplet: number[]) { + const point = new Point(); + + point.r = quadruplet[0] | 0; + point.g = quadruplet[1] | 0; + point.b = quadruplet[2] | 0; + point.a = quadruplet[3] | 0; + point._loadUINT32(); + point._loadQuadruplet(); + // point._loadLab(); + return point; + } + + static createByRGBA(red: number, green: number, blue: number, alpha: number) { + const point = new Point(); + + point.r = red | 0; + point.g = green | 0; + point.b = blue | 0; + point.a = alpha | 0; + point._loadUINT32(); + point._loadQuadruplet(); + // point._loadLab(); + return point; + } + + static createByUint32(uint32: number) { + const point = new Point(); + + point.uint32 = uint32 >>> 0; + point._loadRGBA(); + point._loadQuadruplet(); + // point._loadLab(); + return point; + } + + constructor() { + this.uint32 = -1 >>> 0; + this.r = this.g = this.b = this.a = 0; + this.rgba = new Array(4); + this.rgba[0] = 0; + this.rgba[1] = 0; + this.rgba[2] = 0; + this.rgba[3] = 0; + /* + this.Lab = { + L : 0.0, + a : 0.0, + b : 0.0 + }; + */ + } + + from(point: Point) { + this.r = point.r; + this.g = point.g; + this.b = point.b; + this.a = point.a; + this.uint32 = point.uint32; + this.rgba[0] = point.r; + this.rgba[1] = point.g; + this.rgba[2] = point.b; + this.rgba[3] = point.a; + + /* + this.Lab.L = point.Lab.L; + this.Lab.a = point.Lab.a; + this.Lab.b = point.Lab.b; + */ + } + + /* + * TODO: + Luminance from RGB: + + Luminance (standard for certain colour spaces): (0.2126*R + 0.7152*G + 0.0722*B) [1] + Luminance (perceived option 1): (0.299*R + 0.587*G + 0.114*B) [2] + Luminance (perceived option 2, slower to calculate): sqrt( 0.241*R^2 + 0.691*G^2 + 0.068*B^2 ) ? sqrt( 0.299*R^2 + 0.587*G^2 + 0.114*B^2 ) (thanks to @MatthewHerbst) [http://alienryderflex.com/hsp.html] + */ + getLuminosity(useAlphaChannel: boolean) { + let r = this.r; + let g = this.g; + let b = this.b; + + if (useAlphaChannel) { + r = Math.min(255, 255 - this.a + (this.a * r) / 255); + g = Math.min(255, 255 - this.a + (this.a * g) / 255); + b = Math.min(255, 255 - this.a + (this.a * b) / 255); + } + + // var luma = this.r * Point._RED_COEFFICIENT + this.g * Point._GREEN_COEFFICIENT + this.b * Point._BLUE_COEFFICIENT; + + /* + if(useAlphaChannel) { + luma = (luma * (255 - this.a)) / 255; + } + */ + + return r * Y.RED + g * Y.GREEN + b * Y.BLUE; + } + + private _loadUINT32() { + this.uint32 = + ((this.a << 24) | (this.b << 16) | (this.g << 8) | this.r) >>> 0; + } + + private _loadRGBA() { + this.r = this.uint32 & 0xff; + this.g = (this.uint32 >>> 8) & 0xff; + this.b = (this.uint32 >>> 16) & 0xff; + this.a = (this.uint32 >>> 24) & 0xff; + } + + private _loadQuadruplet() { + this.rgba[0] = this.r; + this.rgba[1] = this.g; + this.rgba[2] = this.b; + this.rgba[3] = this.a; + + /* + var xyz = rgb2xyz(this.r, this.g, this.b); + var lab = xyz2lab(xyz.x, xyz.y, xyz.z); + this.lab.l = lab.l; + this.lab.a = lab.a; + this.lab.b = lab.b; + */ + } + + /* + private _loadLab() : void { + var Lab = Color.Conversion.rgb2lab(this.r, this.g, this.b); + this.Lab.L = Lab.L; + this.Lab.a = Lab.a; + this.Lab.b = Lab.b; + } + */ +} diff --git a/node_modules/image-q/src/utils/pointContainer.ts b/node_modules/image-q/src/utils/pointContainer.ts new file mode 100644 index 00000000..5a4a32ad --- /dev/null +++ b/node_modules/image-q/src/utils/pointContainer.ts @@ -0,0 +1,148 @@ +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * pointContainer.ts - part of Image Quantization Library + */ +import { Point } from './point'; + +/** + * v8 optimizations done. + * fromXXX methods are static to move out polymorphic code from class instance itself. + */ +export class PointContainer { + private readonly _pointArray: Point[]; + private _width: number; + private _height: number; + + constructor() { + this._width = 0; + this._height = 0; + this._pointArray = []; + } + + getWidth() { + return this._width; + } + + getHeight() { + return this._height; + } + + setWidth(width: number) { + this._width = width; + } + + setHeight(height: number) { + this._height = height; + } + + getPointArray() { + return this._pointArray; + } + + clone() { + const clone = new PointContainer(); + clone._width = this._width; + clone._height = this._height; + + for (let i = 0, l = this._pointArray.length; i < l; i++) { + clone._pointArray[i] = Point.createByUint32( + this._pointArray[i].uint32 | 0, + ); // "| 0" is added for v8 optimization + } + + return clone; + } + + toUint32Array() { + const l = this._pointArray.length; + const uint32Array = new Uint32Array(l); + + for (let i = 0; i < l; i++) { + uint32Array[i] = this._pointArray[i].uint32; + } + + return uint32Array; + } + + toUint8Array() { + return new Uint8Array(this.toUint32Array().buffer); + } + + static fromHTMLImageElement(img: HTMLImageElement) { + const width = img.naturalWidth; + const height = img.naturalHeight; + + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + + const ctx = canvas.getContext('2d')!; + ctx.drawImage(img, 0, 0, width, height, 0, 0, width, height); + + return PointContainer.fromHTMLCanvasElement(canvas); + } + + static fromHTMLCanvasElement(canvas: HTMLCanvasElement) { + const width = canvas.width; + const height = canvas.height; + + const ctx = canvas.getContext('2d')!; + const imgData = ctx.getImageData(0, 0, width, height); + + return PointContainer.fromImageData(imgData); + } + + static fromImageData(imageData: ImageData) { + const width = imageData.width; + const height = imageData.height; + + return PointContainer.fromUint8Array(imageData.data, width, height); + } + + static fromUint8Array( + uint8Array: number[] | Uint8Array | Uint8ClampedArray, + width: number, + height: number, + ) { + switch (Object.prototype.toString.call(uint8Array)) { + case '[object Uint8ClampedArray]': + case '[object Uint8Array]': + break; + + default: + uint8Array = new Uint8Array(uint8Array); + } + + const uint32Array = new Uint32Array((uint8Array as Uint8Array).buffer); + return PointContainer.fromUint32Array(uint32Array, width, height); + } + + static fromUint32Array( + uint32Array: Uint32Array, + width: number, + height: number, + ) { + const container = new PointContainer(); + + container._width = width; + container._height = height; + + for (let i = 0, l = uint32Array.length; i < l; i++) { + container._pointArray[i] = Point.createByUint32(uint32Array[i] | 0); // "| 0" is added for v8 optimization + } + + return container; + } + + static fromBuffer(buffer: Buffer, width: number, height: number) { + const uint32Array = new Uint32Array( + buffer.buffer, + buffer.byteOffset, + buffer.byteLength / Uint32Array.BYTES_PER_ELEMENT, + ); + return PointContainer.fromUint32Array(uint32Array, width, height); + } +} diff --git a/node_modules/image-q/src/utils/progressTracker.ts b/node_modules/image-q/src/utils/progressTracker.ts new file mode 100644 index 00000000..3aa0023f --- /dev/null +++ b/node_modules/image-q/src/utils/progressTracker.ts @@ -0,0 +1,31 @@ +export class ProgressTracker { + static readonly steps = 100; + + progress: number; + + private _step: number; + private _range: number; + private _last: number; + private _progressRange: number; + + constructor(valueRange: number, progressRange: number) { + this._range = valueRange; + this._progressRange = progressRange; + this._step = Math.max(1, (this._range / (ProgressTracker.steps + 1)) | 0); + this._last = -this._step; + this.progress = 0; + } + + shouldNotify(current: number) { + if (current - this._last >= this._step) { + this._last = current; + this.progress = Math.min( + (this._progressRange * this._last) / this._range, + this._progressRange, + ); + return true; + } + + return false; + } +} diff --git a/node_modules/is-function/LICENSE b/node_modules/is-function/LICENSE new file mode 100644 index 00000000..0b4aed18 --- /dev/null +++ b/node_modules/is-function/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Stephen Sugden + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-function/README.md b/node_modules/is-function/README.md new file mode 100644 index 00000000..0a67128c --- /dev/null +++ b/node_modules/is-function/README.md @@ -0,0 +1,23 @@ +# is-function + +[![browser support](https://ci.testling.com/grncdr/js-is-function.png)](https://ci.testling.com/grncdr/js-is-function) + +Is that thing a function? Use this module to find out. + +## API + +### module.exports = function isFunction(fn) -> Boolean + +Return `true` if `fn` is a function, otherwise `false`. + +## Why not typeof fn === 'function' + +Because certain old browsers misreport the type of `RegExp` objects as functions. + +## Acknowledgements + +I stole this from https://github.com/ljharb/object-keys + +## License + +MIT diff --git a/node_modules/is-function/index.js b/node_modules/is-function/index.js new file mode 100644 index 00000000..3e648978 --- /dev/null +++ b/node_modules/is-function/index.js @@ -0,0 +1,18 @@ +module.exports = isFunction + +var toString = Object.prototype.toString + +function isFunction (fn) { + if (!fn) { + return false + } + var string = toString.call(fn) + return string === '[object Function]' || + (typeof fn === 'function' && string !== '[object RegExp]') || + (typeof window !== 'undefined' && + // IE8 and below + (fn === window.setTimeout || + fn === window.alert || + fn === window.confirm || + fn === window.prompt)) +}; diff --git a/node_modules/is-function/package.json b/node_modules/is-function/package.json new file mode 100644 index 00000000..a8357edf --- /dev/null +++ b/node_modules/is-function/package.json @@ -0,0 +1,43 @@ +{ + "name": "is-function", + "version": "1.0.2", + "description": "is that thing a function? Use this module to find out", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "~2.3.2" + }, + "scripts": { + "test": "tape test.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/grncdr/js-is-function.git" + }, + "homepage": "https://github.com/grncdr/js-is-function", + "keywords": [ + "polyfill", + "is-function", + "ie6" + ], + "author": "Stephen Sugden ", + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + } +} diff --git a/node_modules/is-function/test.js b/node_modules/is-function/test.js new file mode 100644 index 00000000..b3ac5e46 --- /dev/null +++ b/node_modules/is-function/test.js @@ -0,0 +1,37 @@ +var test = require('tape') +var isFunction = require('./index.js') + +test('isFunction', function (t) { + t.ok(!isFunction(), 'undefined is not a function') + t.ok(!isFunction(null), 'null is not a function') + t.ok(!isFunction(''), 'string is not a function') + t.ok(!isFunction(/a/), 'regex is not a function') + t.ok(!isFunction(true), 'true is not a function') + t.ok(!isFunction(false), 'false is not a function') + t.ok(!isFunction(NaN), 'NaN is not a function') + t.ok(!isFunction(42), '42 is not a function') + t.ok(isFunction(function () {}), 'function is a function') + t.ok(isFunction(setTimeout), 'setTimeout is a function') + t.end() +}) + +if (typeof window !== 'undefined') { + test('browser quirks', function (t) { + t.plan(2) + + t.ok(isFunction(window.alert), 'alert is a function') + + window.testRegExpFromIframe = function (regexp) { + t.ok(!isFunction(regexp)) + } + + var iframe = document.createElement('iframe') + document.body.appendChild(iframe) + + iframe.contentWindow.document.write([ + "" + ].join("\n")); + }) +} diff --git a/node_modules/isomorphic-fetch/.editorconfig b/node_modules/isomorphic-fetch/.editorconfig new file mode 100644 index 00000000..7bfa0f2d --- /dev/null +++ b/node_modules/isomorphic-fetch/.editorconfig @@ -0,0 +1,12 @@ +root=true + +[*] +end_of_line = lf +insert_final_newline = true + +[*.js] +indent_style = tab + +[*.json] +indent_style = space +indent_size = 2 diff --git a/node_modules/isomorphic-fetch/.jshintrc b/node_modules/isomorphic-fetch/.jshintrc new file mode 100644 index 00000000..3686db75 --- /dev/null +++ b/node_modules/isomorphic-fetch/.jshintrc @@ -0,0 +1,5 @@ +{ + "node": true, + "browser": true, + "predef": ["describe", "it", "before"] +} diff --git a/node_modules/isomorphic-fetch/.travis.yml b/node_modules/isomorphic-fetch/.travis.yml new file mode 100644 index 00000000..6024a563 --- /dev/null +++ b/node_modules/isomorphic-fetch/.travis.yml @@ -0,0 +1,4 @@ +sudo: false +language: node_js +node_js: + - 14 diff --git a/node_modules/isomorphic-fetch/LICENSE b/node_modules/isomorphic-fetch/LICENSE new file mode 100644 index 00000000..2385aa96 --- /dev/null +++ b/node_modules/isomorphic-fetch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Matt Andrews + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/isomorphic-fetch/README.md b/node_modules/isomorphic-fetch/README.md new file mode 100644 index 00000000..8f7d690b --- /dev/null +++ b/node_modules/isomorphic-fetch/README.md @@ -0,0 +1,57 @@ +isomorphic-fetch [![Build Status](https://travis-ci.org/matthew-andrews/isomorphic-fetch.svg?branch=master)](https://travis-ci.org/matthew-andrews/isomorphic-fetch) +================ + +Fetch for node and Browserify. Built on top of [GitHub's WHATWG Fetch polyfill](https://github.com/github/fetch). + +## Warnings + +- This adds `fetch` as a global so that its API is consistent between client and server. + +For [ease-of-maintenance and backward-compatibility reasons][why polyfill], this library will always be a polyfill. As a "safe" alternative, which does not modify the global, consider [fetch-ponyfill][]. + +[why polyfill]: https://github.com/matthew-andrews/isomorphic-fetch/issues/31#issuecomment-149668361 +[fetch-ponyfill]: https://github.com/qubyte/fetch-ponyfill + +## Why Use Isomorphic Fetch + +The Fetch API is currently [not implemented consistently](http://caniuse.com/#search=fetch) across browsers. This module will enable you to use `fetch` in your Node code in a cross-browser compliant fashion. The Fetch API is part of the Web platform API defined by the standards bodies WHATWG and W3C. + +## Installation + +### NPM + +```sh +npm install --save isomorphic-fetch +``` + +### Bower + +```sh +bower install --save isomorphic-fetch +``` + +## Usage + +```js +require('isomorphic-fetch'); + +fetch('//offline-news-api.herokuapp.com/stories') + .then(function(response) { + if (response.status >= 400) { + throw new Error("Bad response from server"); + } + return response.json(); + }) + .then(function(stories) { + console.log(stories); + }); +``` + +## License + +All open source code released by FT Labs is licenced under the MIT licence. Based on [the fine work by](https://github.com/github/fetch/pull/31) **[jxck](https://github.com/Jxck)**. + +## Alternatives + +- [cross-fetch](https://github.com/lquixada/cross-fetch#why-not-isomorphic-fetch) +- Using [node-fetch](https://github.com/node-fetch/node-fetch) and the [Fetch polyfill](https://github.com/github/fetch) directly (or from [polyfill.io](https://polyfill.io), or relying on [the browser's implementation of the Fetch API](https://caniuse.com/fetch)). diff --git a/node_modules/isomorphic-fetch/bower.json b/node_modules/isomorphic-fetch/bower.json new file mode 100644 index 00000000..599b3e52 --- /dev/null +++ b/node_modules/isomorphic-fetch/bower.json @@ -0,0 +1,7 @@ +{ + "name": "isomorphic-fetch", + "main": ["fetch-bower.js"], + "dependencies": { + "fetch": "github/fetch#^3.4.1" + } +} diff --git a/node_modules/isomorphic-fetch/fetch-bower.js b/node_modules/isomorphic-fetch/fetch-bower.js new file mode 100644 index 00000000..557a2fe4 --- /dev/null +++ b/node_modules/isomorphic-fetch/fetch-bower.js @@ -0,0 +1 @@ +module.exports = require('fetch'); diff --git a/node_modules/isomorphic-fetch/fetch-npm-browserify.js b/node_modules/isomorphic-fetch/fetch-npm-browserify.js new file mode 100644 index 00000000..7f16e231 --- /dev/null +++ b/node_modules/isomorphic-fetch/fetch-npm-browserify.js @@ -0,0 +1,6 @@ +// the whatwg-fetch polyfill installs the fetch() function +// on the global object (window or self) +// +// Return that as the export for use in Webpack, Browserify etc. +require('whatwg-fetch'); +module.exports = self.fetch.bind(self); diff --git a/node_modules/isomorphic-fetch/fetch-npm-node.js b/node_modules/isomorphic-fetch/fetch-npm-node.js new file mode 100644 index 00000000..bbd3dd1d --- /dev/null +++ b/node_modules/isomorphic-fetch/fetch-npm-node.js @@ -0,0 +1,16 @@ +"use strict"; + +var realFetch = require('node-fetch'); +module.exports = function(url, options) { + if (/^\/\//.test(url)) { + url = 'https:' + url; + } + return realFetch.call(this, url, options); +}; + +if (!global.fetch) { + global.fetch = module.exports; + global.Response = realFetch.Response; + global.Headers = realFetch.Headers; + global.Request = realFetch.Request; +} diff --git a/node_modules/isomorphic-fetch/package.json b/node_modules/isomorphic-fetch/package.json new file mode 100644 index 00000000..bb3215f2 --- /dev/null +++ b/node_modules/isomorphic-fetch/package.json @@ -0,0 +1,32 @@ +{ + "name": "isomorphic-fetch", + "version": "3.0.0", + "description": "Isomorphic WHATWG Fetch API, for Node & Browserify", + "browser": "fetch-npm-browserify.js", + "main": "fetch-npm-node.js", + "scripts": { + "files": "find . -name '*.js' ! -path './node_modules/*' ! -path './bower_components/*'", + "test": "jshint `npm run -s files` && lintspaces -i js-comments -e .editorconfig `npm run -s files` && mocha" + }, + "repository": { + "type": "git", + "url": "https://github.com/matthew-andrews/isomorphic-fetch.git" + }, + "author": "Matt Andrews ", + "license": "MIT", + "bugs": { + "url": "https://github.com/matthew-andrews/isomorphic-fetch/issues" + }, + "homepage": "https://github.com/matthew-andrews/isomorphic-fetch/issues", + "dependencies": { + "node-fetch": "^2.6.1", + "whatwg-fetch": "^3.4.1" + }, + "devDependencies": { + "chai": "^4.2.0", + "jshint": "^2.5.11", + "lintspaces-cli": "^0.7.1", + "mocha": "^8.1.3", + "nock": "^13.0.4" + } +} diff --git a/node_modules/isomorphic-fetch/test/api.test.js b/node_modules/isomorphic-fetch/test/api.test.js new file mode 100644 index 00000000..5a34803e --- /dev/null +++ b/node_modules/isomorphic-fetch/test/api.test.js @@ -0,0 +1,50 @@ +/*global fetch*/ +"use strict"; + +require('../fetch-npm-node'); +var expect = require('chai').expect; +var nock = require('nock'); +var good = 'hello world. 你好世界。'; +var bad = 'good bye cruel world. 再见残酷的世界。'; + +function responseToText(response) { + if (response.status >= 400) throw new Error("Bad server response"); + return response.text(); +} + +describe('fetch', function() { + + before(function() { + nock('https://mattandre.ws') + .get('/succeed.txt') + .reply(200, good); + nock('https://mattandre.ws') + .get('/fail.txt') + .reply(404, bad); + }); + + it('should be defined', function() { + expect(fetch).to.be.a('function'); + }); + + it('should facilitate the making of requests', function(done) { + fetch('//mattandre.ws/succeed.txt') + .then(responseToText) + .then(function(data) { + expect(data).to.equal(good); + done(); + }) + .catch(done); + }); + + it('should do the right thing with bad requests', function(done) { + fetch('//mattandre.ws/fail.txt') + .then(responseToText) + .catch(function(err) { + expect(err.toString()).to.equal("Error: Bad server response"); + done(); + }) + .catch(done); + }); + +}); diff --git a/node_modules/jimp/LICENSE b/node_modules/jimp/LICENSE new file mode 100644 index 00000000..baa5d485 --- /dev/null +++ b/node_modules/jimp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Oliver Moran + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jimp/README.md b/node_modules/jimp/README.md new file mode 100644 index 00000000..c05199e3 --- /dev/null +++ b/node_modules/jimp/README.md @@ -0,0 +1,779 @@ +
+ +

Jimp

+

JavaScript Image Manipulation Program

+
+ +The "JavaScript Image Manipulation Program" :-) + +An image processing library for Node written entirely in JavaScript, with zero native dependencies. + +The default jimp configuration. + +Supported types: + +- `@jimp/jpeg` +- `@jimp/png` +- `@jimp/bmp` +- `@jimp/tiff` +- `@jimp/gif` + +## Installation + +`npm install --save jimp` + +Example usage (Promise will never resolve if callback is passed): + +```js +var Jimp = require("jimp"); + +// open a file called "lenna.png" +Jimp.read("lenna.png", (err, lenna) => { + if (err) throw err; + lenna + .resize(256, 256) // resize + .quality(60) // set JPEG quality + .greyscale() // set greyscale + .write("lena-small-bw.jpg"); // save +}); +``` + +Using promises: + +```js +Jimp.read("lenna.png") + .then((lenna) => { + return lenna + .resize(256, 256) // resize + .quality(60) // set JPEG quality + .greyscale() // set greyscale + .write("lena-small-bw.jpg"); // save + }) + .catch((err) => { + console.error(err); + }); +``` + +## TypeScript Usage + +If you're using this library with TypeScript the method of importing slightly differs from JavaScript. Instead of using require, you must import it with ES6 default import scheme + +```ts +import Jimp from "jimp"; +``` + +This requires setting the `allowSyntheticDefaultImports` compiler option to `true` in your `tsconfig` + +**Note 1**: `esModuleInterop` implicitly sets `allowSyntheticDefaultImports` to `true` + +**Note 2**: `allowSyntheticDefaultImports` nor `esModuleInterop` change the runtime behavior of your code at all. They are just flags that tells TypeScript you need the compatibility they offer. + +## Module Build + +If you're using a web bundles (webpack, rollup, parcel) you can benefit from using the `module` build of jimp. Using the module build will allow your bundler to understand your code better and exclude things you aren't using. + +```js +import Jimp from "jimp/es"; +``` + +## Basic usage + +The static `Jimp.read` method takes the path to a file, URL, dimensions, a Jimp instance or a buffer and returns a Promise: + +```js +Jimp.read("./path/to/image.jpg") + .then((image) => { + // Do stuff with the image. + }) + .catch((err) => { + // Handle an exception. + }); + +Jimp.read("http://www.example.com/path/to/lenna.jpg") + .then((image) => { + // Do stuff with the image. + }) + .catch((err) => { + // Handle an exception. + }); + +Jimp.read(jimpInstance) + .then((image) => { + // Do stuff with the image. + }) + .catch((err) => { + // Handle an exception. + }); + +Jimp.read(buffer) + .then((image) => { + // Do stuff with the image. + }) + .catch((err) => { + // Handle an exception. + }); +``` + +In some cases, you need to pass additional parameters with an image's URL. You can pass an object to the `Jimp.read` method: + +```js +Jimp.read({ + url: 'http://www.example.com/path/to/lenna.jpg', // Required! + headers: {}, + ... +}) + .then(image => { + // Do stuff with the image. + }) + .catch(err => { + // Handle an exception. + }); +``` + +Jimp uses [phin](https://github.com/ethanent/phin) as its HTTP client. Phin uses [`http.request(options[, callback])`](https://nodejs.org/dist/latest-v8.x/docs/api/http.html#http_http_request_options_callback) or [`https.request(options[, callback])`](https://nodejs.org/dist/latest-v8.x/docs/api/https.html#https_https_request_options_callback) methods for making HTTP requests. Phin parses a `url` with the `url.parse(...)` method and passes it with all the other parameters as an `options` to the [`http.request(options[, callback])`](https://nodejs.org/dist/latest-v8.x/docs/api/http.html#http_http_request_options_callback) or [`https.request(options[, callback])`](https://nodejs.org/dist/latest-v8.x/docs/api/https.html#https_https_request_options_callback) methods. + +Briefly speaking, you can pass any options from [`http.request(options[, callback])`](https://nodejs.org/dist/latest-v8.x/docs/api/http.html#http_http_request_options_callback), [`https.request(options[, callback])`](https://nodejs.org/dist/latest-v8.x/docs/api/https.html#https_https_request_options_callback) or even [`tls.connect(options[, callback])`](https://nodejs.org/dist/latest-v8.x/docs/api/tls.html#tls_tls_connect_options_callback). + +Phin parses a `url` and combines it with any options you want. This behavior can be very useful when you need to pass some additional `headers`. Also, you can pass `rejectUnauthorized: false` if you don't require an SSL certificate to be valid (it helps to prevent `unable to verify the first certificate` error). + +The convenience method `Jimp.create` also exists. It is just a wrapper around `Jimp.read`. + +### Custom Constructor + +You might want to initialize jimp in so custom way. To do this Jimp exposes the static function `appendConstructorOption`. The appended constructor options run after all the defaults. + +To define a custom constructor provide a name for it, a function to call to determine if the arguments provided to jimp match your constructor, and a function called where you can construct the image however you want. + +```js +Jimp.appendConstructorOption( + "Name of Option", + (args) => arg.hasSomeCustomThing, + function (resolve, reject, args) { + this.bitmap = customParser(args); + resolve(); + } +); +``` + +If you don't want to handle parsing the bitmap. For example if you want to do some sort of authentication for URL request. Jimp exposes `parseBitmap` so you can fall back to jimp to do the heavy lifting. + +Parse bitmap takes the raw image data in a Buffer, a path (optional), and a node style callback. + +```js +Jimp.appendConstructorOption( + "Custom Url", + (options) => options.url, + function (resolve, reject, options) { + phin(options, (err, res) => { + if (err) { + return reject(err); + } + + this.parseBitmap(res.body, options.url, (err) => { + if (err) { + return reject(err); + } + + resolve(); + }); + }); + } +); +``` + +### Methods + +Once the promise is fulfilled, the following methods can be called on the image: + +```js +/* Resize */ +image.contain( w, h[, alignBits || mode, mode] ); // scale the image to the given width and height, some parts of the image may be letter boxed +image.cover( w, h[, alignBits || mode, mode] ); // scale the image to the given width and height, some parts of the image may be clipped +image.resize( w, h[, mode] ); // resize the image. Jimp.AUTO can be passed as one of the values. +image.scale( f[, mode] ); // scale the image by the factor f +image.scaleToFit( w, h[, mode] ); // scale the image to the largest size that fits inside the given width and height + +// An optional resize mode can be passed with all resize methods. + +/* Crop */ +image.autocrop([tolerance, frames]); // automatically crop same-color borders from image (if any), frames must be a Boolean +image.autocrop(options); // automatically crop same-color borders from image (if any), options may contain tolerance, cropOnlyFrames, cropSymmetric, leaveBorder +image.crop( x, y, w, h ); // crop to the given region + +/* Composing */ +image.blit( src, x, y, [srcx, srcy, srcw, srch] ); + // blit the image with another Jimp image at x, y, optionally cropped. +image.composite( src, x, y, [{ mode, opacitySource, opacityDest }] ); // composites another Jimp image over this image at x, y +image.mask( src, x, y ); // masks the image with another Jimp image at x, y using average pixel value +image.convolute( kernel ); // applies a convolution kernel matrix to the image or a region + +/* Flip and rotate */ +image.flip( horz, vert ); // flip the image horizontally or vertically +image.mirror( horz, vert ); // an alias for flip +image.rotate( deg[, mode] ); // rotate the image counter-clockwise by a number of degrees. Optionally, a resize mode can be passed. If `false` is passed as the second parameter, the image width and height will not be resized. + +/* Colour */ +image.brightness( val ); // adjust the brighness by a value -1 to +1 +image.contrast( val ); // adjust the contrast by a value -1 to +1 +image.dither565(); // ordered dithering of the image and reduce color space to 16-bits (RGB565) +image.greyscale(); // remove colour from the image +image.invert(); // invert the image colours +image.normalize(); // normalize the channels in an image + +/* Alpha channel */ +image.hasAlpha(); // determines if an image contains opaque pixels +image.fade( f ); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image +image.opacity( f ); // multiply the alpha channel by each pixel by the factor f, 0 - 1 +image.opaque(); // set the alpha channel on every pixel to fully opaque +image.background( hex ); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and + +/* Blurs */ +image.gaussian( r ); // Gaussian blur the image by r pixels (VERY slow) +image.blur( r ); // fast blur the image by r pixels + +/* Effects */ +image.posterize( n ); // apply a posterization effect with n level +image.sepia(); // apply a sepia wash to the image +image.pixelate( size[, x, y, w, h ]); // apply a pixelation effect to the image or a region + +/* 3D */ +image.displace( map, offset ); // displaces the image pixels based on the provided displacement map. Useful for making stereoscopic 3D images. +``` + +Some of these methods are irreversible, so it can be useful to perform them on a clone of the original image: + +```js +image.clone(); // returns a clone of the image +``` + +(Contributions of more methods are welcome!) + +### Resize modes + +The default resizing algorithm uses a bilinear method as follows: + +```js +image.resize(250, 250); // resize the image to 250 x 250 +image.resize(Jimp.AUTO, 250); // resize the height to 250 and scale the width accordingly +image.resize(250, Jimp.AUTO); // resize the width to 250 and scale the height accordingly +``` + +Optionally, the following constants can be passed to choose a particular resizing algorithm: + +```js +Jimp.RESIZE_NEAREST_NEIGHBOR; +Jimp.RESIZE_BILINEAR; +Jimp.RESIZE_BICUBIC; +Jimp.RESIZE_HERMITE; +Jimp.RESIZE_BEZIER; +``` + +For example: + +```js +image.resize(250, 250, Jimp.RESIZE_BEZIER); +``` + +### Align modes + +The following constants can be passed to the `image.cover`, `image.contain` and `image.print` methods: + +```js +Jimp.HORIZONTAL_ALIGN_LEFT; +Jimp.HORIZONTAL_ALIGN_CENTER; +Jimp.HORIZONTAL_ALIGN_RIGHT; + +Jimp.VERTICAL_ALIGN_TOP; +Jimp.VERTICAL_ALIGN_MIDDLE; +Jimp.VERTICAL_ALIGN_BOTTOM; +``` + +Where the align mode changes the position of the associated axis as described in the table below. + +| Align Mode | Axis Point | +| ------------------------------ | ----------------------------------------------- | +| `Jimp.HORIZONTAL_ALIGN_LEFT` | Positions the x-axis at the left of the image | +| `Jimp.HORIZONTAL_ALIGN_CENTER` | Positions the x-axis at the center of the image | +| `Jimp.HORIZONTAL_ALIGN_RIGHT` | Positions the x-axis at the right of the image | +| `Jimp.VERTICAL_ALIGN_TOP` | Positions the y-axis at the top of the image | +| `Jimp.VERTICAL_ALIGN_MIDDLE` | Positions the y-axis at the center of the image | +| `Jimp.VERTICAL_ALIGN_BOTTOM` | Positions the y-axis at the bottom of the image | + +For example: + +```js +image.contain(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP); +``` + +Default align modes for `image.cover` and `image.contain` are: + +```js +Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE; +``` + +Default align modes for `image.print` are: + +```js +{ + alignmentX: Jimp.HORIZONTAL_ALIGN_LEFT, + alignmentY: Jimp.VERTICAL_ALIGN_TOP +} +``` + +### Compositing and blend modes + +The following modes can be used for compositing two images together. mode defaults to Jimp.BLEND_SOURCE_OVER. + +```js +Jimp.BLEND_SOURCE_OVER; +Jimp.BLEND_DESTINATION_OVER; +Jimp.BLEND_MULTIPLY; +Jimp.BLEND_ADD; +Jimp.BLEND_SCREEN; +Jimp.BLEND_OVERLAY; +Jimp.BLEND_DARKEN; +Jimp.BLEND_LIGHTEN; +Jimp.BLEND_HARDLIGHT; +Jimp.BLEND_DIFFERENCE; +Jimp.BLEND_EXCLUSION; +``` + +```js +image.composite(srcImage, 100, 0, { + mode: Jimp.BLEND_MULTIPLY, + opacitySource: 0.5, + opacityDest: 0.9, +}); +``` + +### Writing text + +Jimp supports basic typography using BMFont format (.fnt) even ones in different languages! Just find a bitmap font that is suitable [bitmap fonts](https://en.wikipedia.org/wiki/Bitmap_fonts): + +```js +Jimp.loadFont(pathOrURL).then((font) => { + // load font from .fnt file + image.print(font, x, y, message); // print a message on an image. message can be a any type + image.print(font, x, y, message, maxWidth); // print a message on an image with text wrapped at maxWidth +}); +``` + +Alignment modes are supported by replacing the `str` argument with an object containing `text`, `alignmentX` and `alignmentY`. `alignmentX` defaults to `Jimp.HORIZONTAL_ALIGN_LEFT` and `alignmentY` defaults to `Jimp.VERTICAL_ALIGN_TOP`. + +```js +Jimp.loadFont(pathOrURL).then((font) => { + image.print( + font, + x, + y, + { + text: "Hello world!", + alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, + alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, + }, + maxWidth, + maxHeight + ); // prints 'Hello world!' on an image, middle and center-aligned, when x = 0 and y = 0 +}); +``` + +```js +Jimp.loadFont(path, cb); // using a callback pattern +``` + +BMFont fonts are raster based and fixed in size and colour. Jimp comes with a set of fonts that can be used on images: + +```js +Jimp.FONT_SANS_8_BLACK; // Open Sans, 8px, black +Jimp.FONT_SANS_10_BLACK; // Open Sans, 10px, black +Jimp.FONT_SANS_12_BLACK; // Open Sans, 12px, black +Jimp.FONT_SANS_14_BLACK; // Open Sans, 14px, black +Jimp.FONT_SANS_16_BLACK; // Open Sans, 16px, black +Jimp.FONT_SANS_32_BLACK; // Open Sans, 32px, black +Jimp.FONT_SANS_64_BLACK; // Open Sans, 64px, black +Jimp.FONT_SANS_128_BLACK; // Open Sans, 128px, black + +Jimp.FONT_SANS_8_WHITE; // Open Sans, 8px, white +Jimp.FONT_SANS_16_WHITE; // Open Sans, 16px, white +Jimp.FONT_SANS_32_WHITE; // Open Sans, 32px, white +Jimp.FONT_SANS_64_WHITE; // Open Sans, 64px, white +Jimp.FONT_SANS_128_WHITE; // Open Sans, 128px, white +``` + +These can be used as follows: + +```js +Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then((font) => { + image.print(font, 10, 10, "Hello world!"); +}); +``` + +#### Measuring text + +If you need to do calculations on where to place your text jimp provides two methods that measure how wide and how tall a piece of text will be. You can use these methods to lay out multiple pieces of text in relation to each other + +```js +Jimp.measureText(await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK), "Some string"); // width of text +Jimp.measureTextHeight( + await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK), + "Some string", + 100 +); // height of text +``` + +#### Staggering Text + +If you need to stagger text position along the x or y-axis the print method also returns the final coordinates as an argument to the callback. + +```js +Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then((font) => { + image.print( + font, + 10, + 10, + "Hello world that wraps!", + 50, + (err, image, { x, y }) => { + image.print(font, x, y + 20, "More text on another line", 50); + } + ); +}); +``` + +Online tools are also available to convert TTF fonts to BMFont format. They can be used to create color font or sprite packs. + +:star: [Littera](http://kvazars.com/littera/) + +:star: [Hiero](https://libgdx.com/wiki/tools/hiero) + +## Writing to files and buffers + +### Writing to files + +The image can be written to disk in PNG, JPEG or BMP format (based on the save path extension or if no extension is provided the original image's MIME type which, if not available, defaults to PNG) using: + +```js +image.write(path, cb); // Node-style callback will be fired when write is successful +image.writeAsync(path); // Returns Promise +``` + +The original extension for an image (or "png") can accessed as using `image.getExtension()`. The following will save an image using its original format: + +```js +var file = "new_name." + image.getExtension(); +//or +var file = "new_name"; // with no extension +image.write(file); +``` + +### Writing to Buffers + +A PNG, JPEG or BMP binary Buffer of an image (e.g. for storage in a database) can be generated using: + +```js +image.getBuffer(mime, cb); // Node-style callback will be fired with result +image.getBufferAsync(mime); // Returns Promise +``` + +For convenience, supported MIME types are available as static properties: + +```js +Jimp.MIME_PNG; // "image/png" +Jimp.MIME_JPEG; // "image/jpeg" +Jimp.MIME_BMP; // "image/bmp" +``` + +If `Jimp.AUTO` is passed as the MIME type then the original MIME type for the image (or "image/png") will be used. Alternatively, `image.getMIME()` will return the original MIME type of the image (or "image/png"). + +### Data URI + +A Base64 data URI can be generated in the same way as a Buffer, using: + +```js +image.getBase64(mime, cb); // Node-style callback will be fired with result +image.getBase64Async(mime); // Returns Promise +``` + +### PNG and JPEG quality + +The quality of JPEGs can be set with: + +```js +image.quality(n); // set the quality of saved JPEG, 0 - 100 +``` + +The format of PNGs can be set with: + +```js +image.rgba(bool); // set whether PNGs are saved as RGBA (true, default) or RGB (false) +image.filterType(number); // set the filter type for the saved PNG +image.deflateLevel(number); // set the deflate level for the saved PNG +Jimp.deflateStrategy(number); // set the deflate for the saved PNG (0-3) +``` + +For convenience, supported filter types are available as static properties: + +```js +Jimp.PNG_FILTER_AUTO; // -1 +Jimp.PNG_FILTER_NONE; // 0 +Jimp.PNG_FILTER_SUB; // 1 +Jimp.PNG_FILTER_UP; // 2 +Jimp.PNG_FILTER_AVERAGE; // 3 +Jimp.PNG_FILTER_PATH; // 4 +``` + +## Advanced usage + +### Colour manipulation + +Jimp supports advanced colour manipulation using a single method as follows: + +```js +image.color([ + { apply: "hue", params: [-90] }, + { apply: "lighten", params: [50] }, + { apply: "xor", params: ["#06D"] }, +]); +``` + +The method supports the following modifiers: + +| Modifier | Description | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **lighten** {amount} | Lighten the color a given amount, from 0 to 100. Providing 100 will always return white (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **brighten** {amount} | Brighten the color a given amount, from 0 to 100 (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **darken** {amount} | Darken the color a given amount, from 0 to 100. Providing 100 will always return black (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **desaturate** {amount} | Desaturate the color a given amount, from 0 to 100. Providing 100 will is the same as calling greyscale (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **saturate** {amount} | Saturate the color a given amount, from 0 to 100 (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **greyscale** {amount} | Completely desaturates a color into greyscale (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **spin** {degree} | Spin the hue a given amount, from -360 to 360. Calling with 0, 360, or -360 will do nothing - since it sets the hue back to what it was before. (works through [TinyColor](https://github.com/bgrins/TinyColor)) | +| **hue** {degree} | Alias for **spin** | +| **mix** {color, amount} | Mixes colors by their RGB component values. Amount is opacity of overlaying color | +| **tint** {amount} | Same as applying **mix** with white color | +| **shade** {amount} | Same as applying **mix** with black color | +| **xor** {color} | Treats the two colors as bitfields and applies an XOR operation to the red, green, and blue components | +| **red** {amount} | Modify Red component by a given amount | +| **green** {amount} | Modify Green component by a given amount | +| **blue** {amount} | Modify Blue component by a given amount | + +### Convolution matrix + +Sum neighbor pixels weighted by the kernel matrix. You can find a nice explanation with examples at [GIMP's Convolution Matrix plugin](https://docs.gimp.org/2.6/en/plug-in-convmatrix.html) + +Implement emboss effect: + +```js +image.convolute([ + [-2, -1, 0], + [-1, 1, 1], + [0, 1, 2], +]); +``` + +### Low-level manipulation + +Jimp enables low-level manipulation of images in memory through the bitmap property of each Jimp object: + +```js +image.bitmap.data; // a Buffer of the raw bitmap data +image.bitmap.width; // the width of the image +image.bitmap.height; // the height of the image +``` + +This data can be manipulated directly, but remember: garbage in, garbage out. + +A helper method is available to scan a region of the bitmap: + +```js +image.scan(x, y, w, h, f); // scan a given region of the bitmap and call the function f on every pixel +``` + +Example usage: + +```js +image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) { + // x, y is the position of this pixel on the image + // idx is the position start position of this rgba tuple in the bitmap Buffer + // this is the image + + var red = this.bitmap.data[idx + 0]; + var green = this.bitmap.data[idx + 1]; + var blue = this.bitmap.data[idx + 2]; + var alpha = this.bitmap.data[idx + 3]; + + // rgba values run from 0 - 255 + // e.g. this.bitmap.data[idx] = 0; // removes red from this pixel +}); +``` + +If you need to do something with the image at the end of the scan: + +```js +image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) { + // do your stuff.. + + if (x == image.bitmap.width - 1 && y == image.bitmap.height - 1) { + // image scan finished, do your stuff + } +}); +``` + +It's possible to make an iterator scan with a `for ... of`, if you want to `break` the scan before it reaches the end, but note, that this iterator has a huge performance implication: + +```js +for (const { x, y, idx, image } of image.scanIterator( + 0, + 0, + image.bitmap.width, + image.bitmap.height +)) { +} +``` + +A helper to locate a particular pixel within the raw bitmap buffer: + +```js +image.getPixelIndex(x, y); // returns the index within image.bitmap.data +``` + +One of the following may be optionally passed as a third parameter to indicate a strategy for x, y positions that are outside of boundaries of the image: + +```js +Jimp.EDGE_EXTEND = 1; +Jimp.EDGE_WRAP = 2; +Jimp.EDGE_CROP = 3; +``` + +Alternatively, you can manipulate individual pixels using the following these functions: + +```js +image.getPixelColor(x, y); // returns the colour of that pixel e.g. 0xFFFFFFFF +image.setPixelColor(hex, x, y); // sets the colour of that pixel +``` + +Two static helper functions exist to convert RGBA values into single integer (hex) values: + +```js +Jimp.rgbaToInt(r, g, b, a); // e.g. converts 255, 255, 255, 255 to 0xFFFFFFFF +Jimp.intToRGBA(hex); // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255} +``` + +You can convert a css color (Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to its hexadecimal equivalent: + +```js +Jimp.cssColorToHex(cssColor); // e.g. converts #FF00FF to 0xFF00FFFF +``` + +### Creating new images + +If you want to begin with an empty Jimp image, you can call the Jimp constructor passing the width and height of the image to create and a Node-style callback: + +```js +new Jimp(256, 256, (err, image) => { + // this image is 256 x 256, every pixel is set to 0x00000000 +}); +``` + +You can optionally set the pixel colour as follows: + +```js +new Jimp(256, 256, 0xff0000ff, (err, image) => { + // this image is 256 x 256, every pixel is set to 0xFF0000FF +}); +``` + +Or you can use a css color format: + +```js +new Jimp(256, 256, "#FF00FF", (err, image) => { + // this image is 256 x 256, every pixel is set to #FF00FF +}); +``` + +You can also initialize a new Jimp image with a raw image buffer: + +```js +new Jimp({ data: buffer, width: 1280, height: 768 }, (err, image) => { + // this image is 1280 x 768, pixels are loaded from the given buffer. +}); +``` + +This can be useful for interoperating with other image processing libraries. `buffer` is expected to be four-channel (rgba) image data. + +## Comparing images + +To generate a [perceptual hash](https://en.wikipedia.org/wiki/Perceptual_hashing) of a Jimp image, based on the [pHash](http://phash.org/) algorithm, use: + +```js +image.hash(); // aHgG4GgoFjA +``` + +By default the hash is returned as base 64. The hash can be returned at another base by passing a number from 2 to 64 to the method: + +```js +image.hash(2); // 1010101011010000101010000100101010010000011001001001010011100100 +``` + +There are 18,446,744,073,709,551,615 unique hashes. The hamming distance between the binary representation of these hashes can be used to find similar-looking images. + +To calculate the hamming distance between two Jimp images based on their perceptual hash use: + +```js +Jimp.distance(image1, image2); // returns a number 0-1, where 0 means the two images are perceived to be identical +``` + +Jimp also allows the diffing of two Jimp images using [PixelMatch](https://github.com/mapbox/pixelmatch) as follows: + +```js +var diff = Jimp.diff(image1, image2, threshold); // threshold ranges 0-1 (default: 0.1) +diff.image; // a Jimp image showing differences +diff.percent; // the proportion of different pixels (0-1), where 0 means the images are pixel identical +``` + +Using a mix of hamming distance and pixel diffing to compare images, the following code has a 99% success rate of detecting the same image from a random sample (with 1% false positives). The test this figure is drawn from attempts to match each image from a sample of 120 PNGs against 120 corresponding JPEGs saved at a quality setting of 60. + +```js +var distance = Jimp.distance(png, jpeg); // perceived distance +var diff = Jimp.diff(png, jpeg); // pixel difference + +if (distance < 0.15 || diff.percent < 0.15) { + // images match +} else { + // not a match +} +``` + +You can also calculate the raw pHash (no padding or custom base). You can then use this in `distanceFromHash` to calculate the hash distance from a loaded image. + +```js +const hash1 = image1.pHash(); +const hash2 = image2.pHash(); + +image2.distanceFromHash(hash1); +Jimp.compareHashes(hash1, hash2); // same result as above +``` + +## Chaining or callbacks + +Most instance methods can be chained together, for example as follows: + +```js +Jimp.read("lenna.png").then((image) => { + image.greyscale().scale(0.5).write("lena-half-bw.png"); +}); +``` + +Alternatively, methods can be passed Node-style callbacks: + +```js +Jimp.read("lenna.png").then((image) => { + image.greyscale((err, image) => { + image.scale(0.5, (err, image) => { + image.write("lena-half-bw.png"); + }); + }); +}); +``` + +The Node-style callback pattern allows Jimp to be used with frameworks that expect or build on the Node-style callback pattern. diff --git a/node_modules/jimp/browser/README.md b/node_modules/jimp/browser/README.md new file mode 100644 index 00000000..9cc92c47 --- /dev/null +++ b/node_modules/jimp/browser/README.md @@ -0,0 +1,67 @@ +# Jimp ... in a browser + +Browser support for Jimp was added by Phil Seaton. This enabled Jimp to be used in [Electron](http://electron.atom.io/) applications as well as web browsers. + +Example usage: + +```html + + +``` + +See the [main documentation](https://github.com/jimp-dev/jimp) for the full API documenatinon. + +## WebWorkers + +For better performance, it recommended that Jimp methods are run on a separate thread using [`WebWorkers`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers). The following shows how using two files (`index.html` and `jimp-worker.js`): + +```js +// index.html + +var worker = new Worker("jimp-worker.js"); +worker.onmessage = function (e) { + // append a new img element using the base 64 image + var img = document.createElement("img"); + img.setAttribute("src", e.data); + document.body.appendChild(img); +}; +worker.postMessage("lenna.png"); // message the worker thread +``` + +```js +// jimp-worker.js + +importScripts("jimp.min.js"); + +self.addEventListener("message", function (e) { + Jimp.read(e.data).then(function (lenna) { + lenna + .resize(256, 256) // resize + .quality(60) // set JPEG quality + .greyscale() // set greyscale + .getBase64(Jimp.MIME_JPEG, function (err, src) { + self.postMessage(src); // message the main thread + }); + }); +}); +``` + +## License + +Jimp is licensed under the MIT license. diff --git a/node_modules/jimp/browser/examples/dice.png b/node_modules/jimp/browser/examples/dice.png new file mode 100644 index 00000000..b28653fb Binary files /dev/null and b/node_modules/jimp/browser/examples/dice.png differ diff --git a/node_modules/jimp/browser/examples/example1.html b/node_modules/jimp/browser/examples/example1.html new file mode 100644 index 00000000..ed0b301b --- /dev/null +++ b/node_modules/jimp/browser/examples/example1.html @@ -0,0 +1,25 @@ + + + + Jimp browser example 1 + + +

Demonstrates loading a local file using Jimp on the main thread

+ + + + diff --git a/node_modules/jimp/browser/examples/example2.html b/node_modules/jimp/browser/examples/example2.html new file mode 100644 index 00000000..b2448a09 --- /dev/null +++ b/node_modules/jimp/browser/examples/example2.html @@ -0,0 +1,20 @@ + + + + Jimp browser example 2 + + +

+ Demonstrates loading a relative file using Jimp on a WebWorker thread +

+ + + diff --git a/node_modules/jimp/browser/examples/example3.html b/node_modules/jimp/browser/examples/example3.html new file mode 100644 index 00000000..eec88c48 --- /dev/null +++ b/node_modules/jimp/browser/examples/example3.html @@ -0,0 +1,31 @@ + + + + Jimp browser example 3 + + +

Demonstrates loading a local file using Jimp on a WebWorker thread

+

+ + + diff --git a/node_modules/jimp/browser/examples/example4.html b/node_modules/jimp/browser/examples/example4.html new file mode 100644 index 00000000..d9f922e5 --- /dev/null +++ b/node_modules/jimp/browser/examples/example4.html @@ -0,0 +1,74 @@ + + + + Jimp browser example 4 + + +

Demonstrates how to write a text over an image

+ + + + +
+ +
+ +
+
+
+
+ + + diff --git a/node_modules/jimp/browser/examples/jimp-worker.js b/node_modules/jimp/browser/examples/jimp-worker.js new file mode 100644 index 00000000..bf3dd37f --- /dev/null +++ b/node_modules/jimp/browser/examples/jimp-worker.js @@ -0,0 +1,18 @@ +/* eslint-env worker */ +/* global Jimp */ + +importScripts("../lib/jimp.js"); + +self.addEventListener("message", (e) => { + Jimp.read(e.data).then((lenna) => { + lenna + .resize(256, Jimp.AUTO) // resize + .quality(60) // set JPEG quality + .greyscale() // set greyscale + .getBase64(Jimp.AUTO, (err, src) => { + if (err) throw err; + self.postMessage(src); + self.close(); + }); + }); +}); diff --git a/node_modules/jimp/browser/examples/lenna.png b/node_modules/jimp/browser/examples/lenna.png new file mode 100644 index 00000000..59ef68aa Binary files /dev/null and b/node_modules/jimp/browser/examples/lenna.png differ diff --git a/node_modules/jimp/browser/examples/test.html b/node_modules/jimp/browser/examples/test.html new file mode 100644 index 00000000..d5bfd24f --- /dev/null +++ b/node_modules/jimp/browser/examples/test.html @@ -0,0 +1,49 @@ + + + + Jimp browser example 1 + + + + + + + diff --git a/node_modules/jimp/browser/lib/jimp.js b/node_modules/jimp/browser/lib/jimp.js new file mode 100644 index 00000000..e8ebe6ec --- /dev/null +++ b/node_modules/jimp/browser/lib/jimp.js @@ -0,0 +1,3 @@ +/*! For license information please see jimp.js.LICENSE.txt */ +(()=>{var __webpack_modules__={236:(t,e,r)=>{var i=r(4618);function n(t,e){var r=new i(t,e);return function(t){return r.convert(t)}}n.BIN="01",n.OCT="01234567",n.DEC="0123456789",n.HEX="0123456789abcdef",t.exports=n},4618:t=>{"use strict";function e(t,e){if(!(t&&e&&t.length&&e.length))throw new Error("Bad alphabet");this.srcAlphabet=t,this.dstAlphabet=e}e.prototype.convert=function(t){var e,r,i,n={},a=this.srcAlphabet.length,o=this.dstAlphabet.length,s=t.length,h="string"==typeof t?"":[];if(!this.isValid(t))throw new Error('Number "'+t+'" contains of non-alphabetic digits ('+this.srcAlphabet+")");if(this.srcAlphabet===this.dstAlphabet)return t;for(e=0;e=o?(n[i++]=parseInt(r/o,10),r%=o):i>0&&(n[i++]=0);s=i,h=this.dstAlphabet.slice(r,r+1).concat(h)}while(0!==i);return h},e.prototype.isValid=function(t){for(var e=0;e{"use strict";e.byteLength=function(t){var e=h(t),r=e[0],i=e[1];return 3*(r+i)/4-i},e.toByteArray=function(t){var e,r,a=h(t),o=a[0],s=a[1],l=new n(function(t,e,r){return 3*(e+r)/4-r}(0,o,s)),f=0,u=s>0?o-4:o;for(r=0;r>16&255,l[f++]=e>>8&255,l[f++]=255&e;return 2===s&&(e=i[t.charCodeAt(r)]<<2|i[t.charCodeAt(r+1)]>>4,l[f++]=255&e),1===s&&(e=i[t.charCodeAt(r)]<<10|i[t.charCodeAt(r+1)]<<4|i[t.charCodeAt(r+2)]>>2,l[f++]=e>>8&255,l[f++]=255&e),l},e.fromByteArray=function(t){for(var e,i=t.length,n=i%3,a=[],o=16383,s=0,h=i-n;sh?h:s+o));return 1===n?(e=t[i-1],a.push(r[e>>2]+r[e<<4&63]+"==")):2===n&&(e=(t[i-2]<<8)+t[i-1],a.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"=")),a.join("")};for(var r=[],i=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,s=a.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function l(t,e,i){for(var n,a,o=[],s=e;s>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},486:(t,e,r)=>{var i=r(5433),n=r(1651);t.exports={encode:i,decode:n}},1651:(t,e,r)=>{var i=r(8834).lW;function n(t,e){if(this.pos=0,this.buffer=t,this.is_with_alpha=!!e,this.bottom_up=!0,this.flag=this.buffer.toString("utf-8",0,this.pos+=2),"BM"!=this.flag)throw new Error("Invalid BMP File");this.parseHeader(),this.parseRGBA()}n.prototype.parseHeader=function(){if(this.fileSize=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.reserved=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.offset=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.headerSize=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.width=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.height=this.buffer.readInt32LE(this.pos),this.pos+=4,this.planes=this.buffer.readUInt16LE(this.pos),this.pos+=2,this.bitPP=this.buffer.readUInt16LE(this.pos),this.pos+=2,this.compress=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.rawSize=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.hr=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.vr=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.colors=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.importantColors=this.buffer.readUInt32LE(this.pos),this.pos+=4,16===this.bitPP&&this.is_with_alpha&&(this.bitPP=15),this.bitPP<15){var t=0===this.colors?1<=0?this.height-1:-this.height;for(r=this.height-1;r>=0;r--){for(var i=this.bottom_up?r:this.height-1-r,n=0;n>7-s&1];this.data[o+4*s]=0,this.data[o+4*s+1]=h.blue,this.data[o+4*s+2]=h.green,this.data[o+4*s+3]=h.red}0!=e&&(this.pos+=4-e)}},n.prototype.bit4=function(){if(2==this.compress){this.data.fill(255);for(var t=0,e=this.bottom_up?this.height-1:0,r=!1;t>4),1&h&&h+1>1&1)&&this.pos++}}else for(h=0;h>4),r=!r}function l(e){var r=this.palette[e];this.data[t]=0,this.data[t+1]=r.blue,this.data[t+2]=r.green,this.data[t+3]=r.red,t+=4}}else{var f=Math.ceil(this.width/2),u=f%4;for(o=this.height-1;o>=0;o--){var c=this.bottom_up?o:this.height-1-o;for(a=0;a>4,p=15&n,m=this.palette[d];if(this.data[t]=0,this.data[t+1]=m.blue,this.data[t+2]=m.green,this.data[t+3]=m.red,2*a+1>=this.width)break;m=this.palette[p],this.data[t+4]=0,this.data[t+4+1]=m.blue,this.data[t+4+2]=m.green,this.data[t+4+3]=m.red}0!=u&&(this.pos+=4-u)}}},n.prototype.bit8=function(){if(1==this.compress){this.data.fill(255);for(var t=0,e=this.bottom_up?this.height-1:0;t=0;a--){var f=this.bottom_up?a:this.height-1-a;for(n=0;n=0;r--){for(var i=this.bottom_up?r:this.height-1-r,n=0;n>5&e)/e*255|0,h=(a>>10&e)/e*255|0,l=a>>15?255:0,f=i*this.width*4+4*n;this.data[f]=l,this.data[f+1]=o,this.data[f+2]=s,this.data[f+3]=h}this.pos+=t}},n.prototype.bit16=function(){var t=this.width%2*2;this.maskRed=31744,this.maskGreen=992,this.maskBlue=31,this.mask0=0,3==this.compress&&(this.maskRed=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.maskGreen=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.maskBlue=this.buffer.readUInt32LE(this.pos),this.pos+=4,this.mask0=this.buffer.readUInt32LE(this.pos),this.pos+=4);for(var e=[0,0,0],r=0;r<16;r++)this.maskRed>>r&1&&e[0]++,this.maskGreen>>r&1&&e[1]++,this.maskBlue>>r&1&&e[2]++;e[1]+=e[0],e[2]+=e[1],e[0]=8-e[0],e[1]-=8,e[2]-=8;for(var i=this.height-1;i>=0;i--){for(var n=this.bottom_up?i:this.height-1-i,a=0;a>e[1],l=(o&this.maskRed)>>e[2],f=n*this.width*4+4*a;this.data[f]=0,this.data[f+1]=s,this.data[f+2]=h,this.data[f+3]=l}this.pos+=t}},n.prototype.bit24=function(){for(var t=this.height-1;t>=0;t--){for(var e=this.bottom_up?t:this.height-1-t,r=0;r=0;t--)for(var e=this.bottom_up?t:this.height-1-t,r=0;r=0;t--)for(e=this.bottom_up?t:this.height-1-t,r=0;r{var i=r(8834).lW;function n(t){this.buffer=t.data,this.width=t.width,this.height=t.height,this.extraBytes=this.width%4,this.rgbSize=this.height*(3*this.width+this.extraBytes),this.headerInfoSize=40,this.data=[],this.flag="BM",this.reserved=0,this.offset=54,this.fileSize=this.rgbSize+this.offset,this.planes=1,this.bitPP=24,this.compress=0,this.hr=0,this.vr=0,this.colors=0,this.importantColors=0}n.prototype.encode=function(){var t=new i(this.offset+this.rgbSize);this.pos=0,t.write(this.flag,this.pos,2),this.pos+=2,t.writeUInt32LE(this.fileSize,this.pos),this.pos+=4,t.writeUInt32LE(this.reserved,this.pos),this.pos+=4,t.writeUInt32LE(this.offset,this.pos),this.pos+=4,t.writeUInt32LE(this.headerInfoSize,this.pos),this.pos+=4,t.writeUInt32LE(this.width,this.pos),this.pos+=4,t.writeInt32LE(-this.height,this.pos),this.pos+=4,t.writeUInt16LE(this.planes,this.pos),this.pos+=2,t.writeUInt16LE(this.bitPP,this.pos),this.pos+=2,t.writeUInt32LE(this.compress,this.pos),this.pos+=4,t.writeUInt32LE(this.rgbSize,this.pos),this.pos+=4,t.writeUInt32LE(this.hr,this.pos),this.pos+=4,t.writeUInt32LE(this.vr,this.pos),this.pos+=4,t.writeUInt32LE(this.colors,this.pos),this.pos+=4,t.writeUInt32LE(this.importantColors,this.pos),this.pos+=4;for(var e=0,r=3*this.width+this.extraBytes,n=0;n0){var s=this.pos+n*r+3*this.width;t.fill(0,s,s+this.extraBytes)}}return t},t.exports=function(t,e){return void 0===e&&(e=100),{data:new n(t).encode(),width:t.width,height:t.height}}},5137:(t,e,r)=>{var i=r(8834).lW;t.exports=function(t,e){if(i.isBuffer(t)&&i.isBuffer(e)){if("function"==typeof t.equals)return t.equals(e);if(t.length!==e.length)return!1;for(var r=0;r{"use strict";var i=r(5766),n=r(4181);e.lW=s,e.h2=50;var a=2147483647;function o(t){if(t>a)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=s.prototype,e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return f(t)}return h(t,e,r)}function h(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=0|d(t,e),i=o(r),n=i.write(t,e);return n!==r&&(i=i.slice(0,n)),i}(t,e);if(ArrayBuffer.isView(t))return u(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(F(t,ArrayBuffer)||t&&F(t.buffer,ArrayBuffer))return function(t,e,r){if(e<0||t.byteLength=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|t}function d(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||F(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return z(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return D(t).length;default:if(n)return i?-1:z(t).length;e=(""+e).toLowerCase(),n=!0}}function p(t,e,r){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return B(this,e,r);case"utf8":case"utf-8":return S(this,e,r);case"ascii":return A(this,e,r);case"latin1":case"binary":return I(this,e,r);case"base64":return k(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,r);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}function m(t,e,r){var i=t[e];t[e]=t[r],t[r]=i}function g(t,e,r,i,n){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),j(r=+r)&&(r=n?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(n)return-1;r=t.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof e&&(e=s.from(e,i)),s.isBuffer(e))return 0===e.length?-1:b(t,e,r,i,n);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,i,n);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,i,n){var a,o=1,s=t.length,h=e.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(t.length<2||e.length<2)return-1;o=2,s/=2,h/=2,r/=2}function l(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(n){var f=-1;for(a=r;as&&(r=s-h),a=r;a>=0;a--){for(var u=!0,c=0;cn&&(i=n):i=n;var a=e.length;i>a/2&&(i=a/2);for(var o=0;o>8,n=r%256,a.push(n),a.push(i);return a}(e,t.length-r),t,r,i)}function k(t,e,r){return 0===e&&r===t.length?i.fromByteArray(t):i.fromByteArray(t.slice(e,r))}function S(t,e,r){r=Math.min(t.length,r);for(var i=[],n=e;n239?4:l>223?3:l>191?2:1;if(n+u<=r)switch(u){case 1:l<128&&(f=l);break;case 2:128==(192&(a=t[n+1]))&&(h=(31&l)<<6|63&a)>127&&(f=h);break;case 3:a=t[n+1],o=t[n+2],128==(192&a)&&128==(192&o)&&(h=(15&l)<<12|(63&a)<<6|63&o)>2047&&(h<55296||h>57343)&&(f=h);break;case 4:a=t[n+1],o=t[n+2],s=t[n+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(h=(15&l)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&h<1114112&&(f=h)}null===f?(f=65533,u=1):f>65535&&(f-=65536,i.push(f>>>10&1023|55296),f=56320|1023&f),i.push(f),n+=u}return function(t){var e=t.length;if(e<=M)return String.fromCharCode.apply(String,t);for(var r="",i=0;ir&&(t+=" ... "),""},s.prototype.compare=function(t,e,r,i,n){if(F(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),e<0||r>t.length||i<0||n>this.length)throw new RangeError("out of range index");if(i>=n&&e>=r)return 0;if(i>=n)return-1;if(e>=r)return 1;if(this===t)return 0;for(var a=(n>>>=0)-(i>>>=0),o=(r>>>=0)-(e>>>=0),h=Math.min(a,o),l=this.slice(i,n),f=t.slice(e,r),u=0;u>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-e;if((void 0===r||r>n)&&(r=n),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var a=!1;;)switch(i){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return y(this,t,e,r);case"ascii":return w(this,t,e,r);case"latin1":case"binary":return v(this,t,e,r);case"base64":return x(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var M=4096;function A(t,e,r){var i="";r=Math.min(t.length,r);for(var n=e;nn)&&(r=n);for(var a="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function P(t,e,r,i,n,a){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||et.length)throw new RangeError("Index out of range")}function O(t,e,r,i,n,a){if(r+i>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(t,e,r,i,a){return e=+e,r>>>=0,a||O(t,0,r,4),n.write(t,e,r,i,23,4),r+4}function C(t,e,r,i,a){return e=+e,r>>>=0,a||O(t,0,r,8),n.write(t,e,r,i,52,8),r+8}s.prototype.slice=function(t,e){var r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||R(t,e,this.length);for(var i=this[t],n=1,a=0;++a>>=0,e>>>=0,r||R(t,e,this.length);for(var i=this[t+--e],n=1;e>0&&(n*=256);)i+=this[t+--e]*n;return i},s.prototype.readUInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),this[t]},s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);for(var i=this[t],n=1,a=0;++a=(n*=128)&&(i-=Math.pow(2,8*e)),i},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);for(var i=e,n=1,a=this[t+--i];i>0&&(n*=256);)a+=this[t+--i]*n;return a>=(n*=128)&&(a-=Math.pow(2,8*e)),a},s.prototype.readInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||R(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||R(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readFloatLE=function(t,e){return t>>>=0,e||R(t,4,this.length),n.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||R(t,4,this.length),n.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||R(t,8,this.length),n.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||R(t,8,this.length),n.read(this,t,!1,52,8)},s.prototype.writeUIntLE=function(t,e,r,i){t=+t,e>>>=0,r>>>=0,i||P(this,t,e,r,Math.pow(2,8*r)-1,0);var n=1,a=0;for(this[e]=255&t;++a>>=0,r>>>=0,i||P(this,t,e,r,Math.pow(2,8*r)-1,0);var n=r-1,a=1;for(this[e+n]=255&t;--n>=0&&(a*=256);)this[e+n]=t/a&255;return e+r},s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeIntLE=function(t,e,r,i){if(t=+t,e>>>=0,!i){var n=Math.pow(2,8*r-1);P(this,t,e,r,n-1,-n)}var a=0,o=1,s=0;for(this[e]=255&t;++a>0)-s&255;return e+r},s.prototype.writeIntBE=function(t,e,r,i){if(t=+t,e>>>=0,!i){var n=Math.pow(2,8*r-1);P(this,t,e,r,n-1,-n)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)t<0&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeFloatLE=function(t,e,r){return L(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return L(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return C(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return C(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,i){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e=0;--a)t[a+e]=this[a+r];else Uint8Array.prototype.set.call(t,this.subarray(r,i),e);return n},s.prototype.fill=function(t,e,r,i){if("string"==typeof t){if("string"==typeof e?(i=e,e=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!s.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var n=t.charCodeAt(0);("utf8"===i&&n<128||"latin1"===i)&&(t=n)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(a=e;a55295&&r<57344){if(!n){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===i){(e-=3)>-1&&a.push(239,191,189);continue}n=r;continue}if(r<56320){(e-=3)>-1&&a.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(e-=3)>-1&&a.push(239,191,189);if(n=null,r<128){if((e-=1)<0)break;a.push(r)}else if(r<2048){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function D(t){return i.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(U,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function N(t,e,r,i){for(var n=0;n=e.length||n>=t.length);++n)e[n+r]=t[n];return n}function F(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function j(t){return t!=t}},4181:(t,e)=>{e.read=function(t,e,r,i,n){var a,o,s=8*n-i-1,h=(1<>1,f=-7,u=r?n-1:0,c=r?-1:1,d=t[e+u];for(u+=c,a=d&(1<<-f)-1,d>>=-f,f+=s;f>0;a=256*a+t[e+u],u+=c,f-=8);for(o=a&(1<<-f)-1,a>>=-f,f+=i;f>0;o=256*o+t[e+u],u+=c,f-=8);if(0===a)a=1-l;else{if(a===h)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,i),a-=l}return(d?-1:1)*o*Math.pow(2,a-i)},e.write=function(t,e,r,i,n,a){var o,s,h,l=8*a-n-1,f=(1<>1,c=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:a-1,p=i?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),(e+=o+u>=1?c/h:c*Math.pow(2,1-u))*h>=2&&(o++,h/=2),o+u>=f?(s=0,o=f):o+u>=1?(s=(e*h-1)*Math.pow(2,n),o+=u):(s=e*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;t[r+d]=255&s,d+=p,s/=256,n-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,l-=8);t[r+d-p]|=128*m}},2699:t=>{"use strict";var e,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)};e=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:function(t){return Object.getOwnPropertyNames(t)};var n=Number.isNaN||function(t){return t!=t};function a(){a.init.call(this)}t.exports=a,t.exports.once=function(t,e){return new Promise((function(r,i){function n(r){t.removeListener(e,a),i(r)}function a(){"function"==typeof t.removeListener&&t.removeListener("error",n),r([].slice.call(arguments))}m(t,e,a,{once:!0}),"error"!==e&&function(t,e,r){"function"==typeof t.on&&m(t,"error",e,{once:!0})}(t,n)}))},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}function h(t){return void 0===t._maxListeners?a.defaultMaxListeners:t._maxListeners}function l(t,e,r,i){var n,a,o,l;if(s(r),void 0===(a=t._events)?(a=t._events=Object.create(null),t._eventsCount=0):(void 0!==a.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),a=t._events),o=a[e]),void 0===o)o=a[e]=r,++t._eventsCount;else if("function"==typeof o?o=a[e]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=h(t))>0&&o.length>n&&!o.warned){o.warned=!0;var f=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");f.name="MaxListenersExceededWarning",f.emitter=t,f.type=e,f.count=o.length,l=f,console&&console.warn&&console.warn(l)}return t}function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},n=f.bind(i);return n.listener=r,i.wrapFn=n,n}function c(t,e,r){var i=t._events;if(void 0===i)return[];var n=i[e];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(t){for(var e=new Array(t.length),r=0;r0&&(o=e[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var h=a[t];if(void 0===h)return!1;if("function"==typeof h)i(h,this,e);else{var l=h.length,f=p(h,l);for(r=0;r=0;a--)if(r[a]===e||r[a].listener===e){o=r[a].listener,n=a;break}if(n<0)return this;0===n?r.shift():function(t,e){for(;e+1=0;i--)this.removeListener(t,e[i]);return this},a.prototype.listeners=function(t){return c(this,t,!0)},a.prototype.rawListeners=function(t){return c(this,t,!1)},a.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):d.call(t,e)},a.prototype.listenerCount=d,a.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]}},6551:(t,e,r)=>{var i=r(453);t.exports={create:function(t,e){if(t instanceof(e=e||(0,eval)("this")).ArrayBuffer){var n=r(909);return new i(new n(t,0,t.byteLength,!0,e))}var a=r(3684);return new i(new a(t,0,t.length,!0))}}},3684:t=>{function e(t,e,r,i){this.buffer=t,this.offset=e||0,r="number"==typeof r?r:t.length,this.endPosition=this.offset+r,this.setBigEndian(i)}e.prototype={setBigEndian:function(t){this.bigEndian=!!t},nextUInt8:function(){var t=this.buffer.readUInt8(this.offset);return this.offset+=1,t},nextInt8:function(){var t=this.buffer.readInt8(this.offset);return this.offset+=1,t},nextUInt16:function(){var t=this.bigEndian?this.buffer.readUInt16BE(this.offset):this.buffer.readUInt16LE(this.offset);return this.offset+=2,t},nextUInt32:function(){var t=this.bigEndian?this.buffer.readUInt32BE(this.offset):this.buffer.readUInt32LE(this.offset);return this.offset+=4,t},nextInt16:function(){var t=this.bigEndian?this.buffer.readInt16BE(this.offset):this.buffer.readInt16LE(this.offset);return this.offset+=2,t},nextInt32:function(){var t=this.bigEndian?this.buffer.readInt32BE(this.offset):this.buffer.readInt32LE(this.offset);return this.offset+=4,t},nextFloat:function(){var t=this.bigEndian?this.buffer.readFloatBE(this.offset):this.buffer.readFloatLE(this.offset);return this.offset+=4,t},nextDouble:function(){var t=this.bigEndian?this.buffer.readDoubleBE(this.offset):this.buffer.readDoubleLE(this.offset);return this.offset+=8,t},nextBuffer:function(t){var e=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,e},remainingLength:function(){return this.endPosition-this.offset},nextString:function(t){var e=this.buffer.toString("utf8",this.offset,this.offset+t);return this.offset+=t,e},mark:function(){var t=this;return{openWithOffset:function(r){return r=(r||0)+this.offset,new e(t.buffer,r,t.endPosition-r,t.bigEndian)},offset:this.offset}},offsetFrom:function(t){return this.offset-t.offset},skip:function(t){this.offset+=t},branch:function(t,r){return r="number"==typeof r?r:this.endPosition-(this.offset+t),new e(this.buffer,this.offset+t,r,this.bigEndian)}},t.exports=e},565:t=>{function e(t){return parseInt(t,10)}var r=3600,i=60;function n(t,r){t=t.map(e),r=r.map(e);var i=t[0],n=t[1]-1,a=t[2],o=r[0],s=r[1],h=r[2];return Date.UTC(i,n,a,o,s,h,0)/1e3}function a(t){var a=t.substr(0,10).split("-"),o=t.substr(11,8).split(":"),s=t.substr(19,6).split(":").map(e),h=s[0]*r+s[1]*i,l=n(a,o);if("number"==typeof(l-=h)&&!isNaN(l))return l}function o(t){var e=t.split(" "),r=n(e[0].split(":"),e[1].split(":"));if("number"==typeof r&&!isNaN(r))return r}t.exports={parseDateWithSpecFormat:o,parseDateWithTimezoneFormat:a,parseExifDate:function(t){var e=19===t.length&&":"===t.charAt(4);return 25===t.length&&"T"===t.charAt(10)?a(t):e?o(t):void 0}}},909:t=>{function e(t,e,r,i,n,a){this.global=n,e=e||0,r=r||t.byteLength-e,this.arrayBuffer=t.slice(e,e+r),this.view=new n.DataView(this.arrayBuffer,0,this.arrayBuffer.byteLength),this.setBigEndian(i),this.offset=0,this.parentOffset=(a||0)+e}e.prototype={setBigEndian:function(t){this.littleEndian=!t},nextUInt8:function(){var t=this.view.getUint8(this.offset);return this.offset+=1,t},nextInt8:function(){var t=this.view.getInt8(this.offset);return this.offset+=1,t},nextUInt16:function(){var t=this.view.getUint16(this.offset,this.littleEndian);return this.offset+=2,t},nextUInt32:function(){var t=this.view.getUint32(this.offset,this.littleEndian);return this.offset+=4,t},nextInt16:function(){var t=this.view.getInt16(this.offset,this.littleEndian);return this.offset+=2,t},nextInt32:function(){var t=this.view.getInt32(this.offset,this.littleEndian);return this.offset+=4,t},nextFloat:function(){var t=this.view.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t},nextDouble:function(){var t=this.view.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t},nextBuffer:function(t){var e=this.arrayBuffer.slice(this.offset,this.offset+t);return this.offset+=t,e},remainingLength:function(){return this.arrayBuffer.byteLength-this.offset},nextString:function(t){var e=this.arrayBuffer.slice(this.offset,this.offset+t);return e=String.fromCharCode.apply(null,new this.global.Uint8Array(e)),this.offset+=t,e},mark:function(){var t=this;return{openWithOffset:function(r){return r=(r||0)+this.offset,new e(t.arrayBuffer,r,t.arrayBuffer.byteLength-r,!t.littleEndian,t.global,t.parentOffset)},offset:this.offset,getParentOffset:function(){return t.parentOffset}}},offsetFrom:function(t){return this.parentOffset+this.offset-(t.offset+t.getParentOffset())},skip:function(t){this.offset+=t},branch:function(t,r){return r="number"==typeof r?r:this.arrayBuffer.byteLength-(this.offset+t),new e(this.arrayBuffer,this.offset+t,r,!this.littleEndian,this.global,this.parentOffset)}},t.exports=e},3332:t=>{t.exports={exif:{1:"InteropIndex",2:"InteropVersion",11:"ProcessingSoftware",254:"SubfileType",255:"OldSubfileType",256:"ImageWidth",257:"ImageHeight",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",263:"Thresholding",264:"CellWidth",265:"CellLength",266:"FillOrder",269:"DocumentName",270:"ImageDescription",271:"Make",272:"Model",273:"StripOffsets",274:"Orientation",277:"SamplesPerPixel",278:"RowsPerStrip",279:"StripByteCounts",280:"MinSampleValue",281:"MaxSampleValue",282:"XResolution",283:"YResolution",284:"PlanarConfiguration",285:"PageName",286:"XPosition",287:"YPosition",288:"FreeOffsets",289:"FreeByteCounts",290:"GrayResponseUnit",291:"GrayResponseCurve",292:"T4Options",293:"T6Options",296:"ResolutionUnit",297:"PageNumber",300:"ColorResponseUnit",301:"TransferFunction",305:"Software",306:"ModifyDate",315:"Artist",316:"HostComputer",317:"Predictor",318:"WhitePoint",319:"PrimaryChromaticities",320:"ColorMap",321:"HalftoneHints",322:"TileWidth",323:"TileLength",324:"TileOffsets",325:"TileByteCounts",326:"BadFaxLines",327:"CleanFaxData",328:"ConsecutiveBadFaxLines",330:"SubIFD",332:"InkSet",333:"InkNames",334:"NumberofInks",336:"DotRange",337:"TargetPrinter",338:"ExtraSamples",339:"SampleFormat",340:"SMinSampleValue",341:"SMaxSampleValue",342:"TransferRange",343:"ClipPath",344:"XClipPathUnits",345:"YClipPathUnits",346:"Indexed",347:"JPEGTables",351:"OPIProxy",400:"GlobalParametersIFD",401:"ProfileType",402:"FaxProfile",403:"CodingMethods",404:"VersionYear",405:"ModeNumber",433:"Decode",434:"DefaultImageColor",435:"T82Options",437:"JPEGTables",512:"JPEGProc",513:"ThumbnailOffset",514:"ThumbnailLength",515:"JPEGRestartInterval",517:"JPEGLosslessPredictors",518:"JPEGPointTransforms",519:"JPEGQTables",520:"JPEGDCTables",521:"JPEGACTables",529:"YCbCrCoefficients",530:"YCbCrSubSampling",531:"YCbCrPositioning",532:"ReferenceBlackWhite",559:"StripRowCounts",700:"ApplicationNotes",999:"USPTOMiscellaneous",4096:"RelatedImageFileFormat",4097:"RelatedImageWidth",4098:"RelatedImageHeight",18246:"Rating",18247:"XP_DIP_XML",18248:"StitchInfo",18249:"RatingPercent",32781:"ImageID",32931:"WangTag1",32932:"WangAnnotation",32933:"WangTag3",32934:"WangTag4",32995:"Matteing",32996:"DataType",32997:"ImageDepth",32998:"TileDepth",33405:"Model2",33421:"CFARepeatPatternDim",33422:"CFAPattern2",33423:"BatteryLevel",33424:"KodakIFD",33432:"Copyright",33434:"ExposureTime",33437:"FNumber",33445:"MDFileTag",33446:"MDScalePixel",33447:"MDColorTable",33448:"MDLabName",33449:"MDSampleInfo",33450:"MDPrepDate",33451:"MDPrepTime",33452:"MDFileUnits",33550:"PixelScale",33589:"AdventScale",33590:"AdventRevision",33628:"UIC1Tag",33629:"UIC2Tag",33630:"UIC3Tag",33631:"UIC4Tag",33723:"IPTC-NAA",33918:"IntergraphPacketData",33919:"IntergraphFlagRegisters",33920:"IntergraphMatrix",33921:"INGRReserved",33922:"ModelTiePoint",34016:"Site",34017:"ColorSequence",34018:"IT8Header",34019:"RasterPadding",34020:"BitsPerRunLength",34021:"BitsPerExtendedRunLength",34022:"ColorTable",34023:"ImageColorIndicator",34024:"BackgroundColorIndicator",34025:"ImageColorValue",34026:"BackgroundColorValue",34027:"PixelIntensityRange",34028:"TransparencyIndicator",34029:"ColorCharacterization",34030:"HCUsage",34031:"TrapIndicator",34032:"CMYKEquivalent",34118:"SEMInfo",34152:"AFCP_IPTC",34232:"PixelMagicJBIGOptions",34264:"ModelTransform",34306:"WB_GRGBLevels",34310:"LeafData",34377:"PhotoshopSettings",34665:"ExifOffset",34675:"ICC_Profile",34687:"TIFF_FXExtensions",34688:"MultiProfiles",34689:"SharedData",34690:"T88Options",34732:"ImageLayer",34735:"GeoTiffDirectory",34736:"GeoTiffDoubleParams",34737:"GeoTiffAsciiParams",34850:"ExposureProgram",34852:"SpectralSensitivity",34853:"GPSInfo",34855:"ISO",34856:"Opto-ElectricConvFactor",34857:"Interlace",34858:"TimeZoneOffset",34859:"SelfTimerMode",34864:"SensitivityType",34865:"StandardOutputSensitivity",34866:"RecommendedExposureIndex",34867:"ISOSpeed",34868:"ISOSpeedLatitudeyyy",34869:"ISOSpeedLatitudezzz",34908:"FaxRecvParams",34909:"FaxSubAddress",34910:"FaxRecvTime",34954:"LeafSubIFD",36864:"ExifVersion",36867:"DateTimeOriginal",36868:"CreateDate",37121:"ComponentsConfiguration",37122:"CompressedBitsPerPixel",37377:"ShutterSpeedValue",37378:"ApertureValue",37379:"BrightnessValue",37380:"ExposureCompensation",37381:"MaxApertureValue",37382:"SubjectDistance",37383:"MeteringMode",37384:"LightSource",37385:"Flash",37386:"FocalLength",37387:"FlashEnergy",37388:"SpatialFrequencyResponse",37389:"Noise",37390:"FocalPlaneXResolution",37391:"FocalPlaneYResolution",37392:"FocalPlaneResolutionUnit",37393:"ImageNumber",37394:"SecurityClassification",37395:"ImageHistory",37396:"SubjectArea",37397:"ExposureIndex",37398:"TIFF-EPStandardID",37399:"SensingMethod",37434:"CIP3DataFile",37435:"CIP3Sheet",37436:"CIP3Side",37439:"StoNits",37500:"MakerNote",37510:"UserComment",37520:"SubSecTime",37521:"SubSecTimeOriginal",37522:"SubSecTimeDigitized",37679:"MSDocumentText",37680:"MSPropertySetStorage",37681:"MSDocumentTextPosition",37724:"ImageSourceData",40091:"XPTitle",40092:"XPComment",40093:"XPAuthor",40094:"XPKeywords",40095:"XPSubject",40960:"FlashpixVersion",40961:"ColorSpace",40962:"ExifImageWidth",40963:"ExifImageHeight",40964:"RelatedSoundFile",40965:"InteropOffset",41483:"FlashEnergy",41484:"SpatialFrequencyResponse",41485:"Noise",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",41489:"ImageNumber",41490:"SecurityClassification",41491:"ImageHistory",41492:"SubjectLocation",41493:"ExposureIndex",41494:"TIFF-EPStandardID",41495:"SensingMethod",41728:"FileSource",41729:"SceneType",41730:"CFAPattern",41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41988:"DigitalZoomRatio",41989:"FocalLengthIn35mmFormat",41990:"SceneCaptureType",41991:"GainControl",41992:"Contrast",41993:"Saturation",41994:"Sharpness",41995:"DeviceSettingDescription",41996:"SubjectDistanceRange",42016:"ImageUniqueID",42032:"OwnerName",42033:"SerialNumber",42034:"LensInfo",42035:"LensMake",42036:"LensModel",42037:"LensSerialNumber",42112:"GDALMetadata",42113:"GDALNoData",42240:"Gamma",44992:"ExpandSoftware",44993:"ExpandLens",44994:"ExpandFilm",44995:"ExpandFilterLens",44996:"ExpandScanner",44997:"ExpandFlashLamp",48129:"PixelFormat",48130:"Transformation",48131:"Uncompressed",48132:"ImageType",48256:"ImageWidth",48257:"ImageHeight",48258:"WidthResolution",48259:"HeightResolution",48320:"ImageOffset",48321:"ImageByteCount",48322:"AlphaOffset",48323:"AlphaByteCount",48324:"ImageDataDiscard",48325:"AlphaDataDiscard",50215:"OceScanjobDesc",50216:"OceApplicationSelector",50217:"OceIDNumber",50218:"OceImageLogic",50255:"Annotations",50341:"PrintIM",50560:"USPTOOriginalContentType",50706:"DNGVersion",50707:"DNGBackwardVersion",50708:"UniqueCameraModel",50709:"LocalizedCameraModel",50710:"CFAPlaneColor",50711:"CFALayout",50712:"LinearizationTable",50713:"BlackLevelRepeatDim",50714:"BlackLevel",50715:"BlackLevelDeltaH",50716:"BlackLevelDeltaV",50717:"WhiteLevel",50718:"DefaultScale",50719:"DefaultCropOrigin",50720:"DefaultCropSize",50721:"ColorMatrix1",50722:"ColorMatrix2",50723:"CameraCalibration1",50724:"CameraCalibration2",50725:"ReductionMatrix1",50726:"ReductionMatrix2",50727:"AnalogBalance",50728:"AsShotNeutral",50729:"AsShotWhiteXY",50730:"BaselineExposure",50731:"BaselineNoise",50732:"BaselineSharpness",50733:"BayerGreenSplit",50734:"LinearResponseLimit",50735:"CameraSerialNumber",50736:"DNGLensInfo",50737:"ChromaBlurRadius",50738:"AntiAliasStrength",50739:"ShadowScale",50740:"DNGPrivateData",50741:"MakerNoteSafety",50752:"RawImageSegmentation",50778:"CalibrationIlluminant1",50779:"CalibrationIlluminant2",50780:"BestQualityScale",50781:"RawDataUniqueID",50784:"AliasLayerMetadata",50827:"OriginalRawFileName",50828:"OriginalRawFileData",50829:"ActiveArea",50830:"MaskedAreas",50831:"AsShotICCProfile",50832:"AsShotPreProfileMatrix",50833:"CurrentICCProfile",50834:"CurrentPreProfileMatrix",50879:"ColorimetricReference",50898:"PanasonicTitle",50899:"PanasonicTitle2",50931:"CameraCalibrationSig",50932:"ProfileCalibrationSig",50933:"ProfileIFD",50934:"AsShotProfileName",50935:"NoiseReductionApplied",50936:"ProfileName",50937:"ProfileHueSatMapDims",50938:"ProfileHueSatMapData1",50939:"ProfileHueSatMapData2",50940:"ProfileToneCurve",50941:"ProfileEmbedPolicy",50942:"ProfileCopyright",50964:"ForwardMatrix1",50965:"ForwardMatrix2",50966:"PreviewApplicationName",50967:"PreviewApplicationVersion",50968:"PreviewSettingsName",50969:"PreviewSettingsDigest",50970:"PreviewColorSpace",50971:"PreviewDateTime",50972:"RawImageDigest",50973:"OriginalRawFileDigest",50974:"SubTileBlockSize",50975:"RowInterleaveFactor",50981:"ProfileLookTableDims",50982:"ProfileLookTableData",51008:"OpcodeList1",51009:"OpcodeList2",51022:"OpcodeList3",51041:"NoiseProfile",51043:"TimeCodes",51044:"FrameRate",51058:"TStop",51081:"ReelName",51089:"OriginalDefaultFinalSize",51090:"OriginalBestQualitySize",51091:"OriginalDefaultCropSize",51105:"CameraLabel",51107:"ProfileHueSatMapEncoding",51108:"ProfileLookTableEncoding",51109:"BaselineExposureOffset",51110:"DefaultBlackRender",51111:"NewRawImageDigest",51112:"RawToPreviewGain",51125:"DefaultUserCrop",59932:"Padding",59933:"OffsetSchema",65e3:"OwnerName",65001:"SerialNumber",65002:"Lens",65024:"KDC_IFD",65100:"RawFile",65101:"Converter",65102:"WhiteBalance",65105:"Exposure",65106:"Shadows",65107:"Brightness",65108:"Contrast",65109:"Saturation",65110:"Sharpness",65111:"Smoothness",65112:"MoireFilter"},gps:{0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude",5:"GPSAltitudeRef",6:"GPSAltitude",7:"GPSTimeStamp",8:"GPSSatellites",9:"GPSStatus",10:"GPSMeasureMode",11:"GPSDOP",12:"GPSSpeedRef",13:"GPSSpeed",14:"GPSTrackRef",15:"GPSTrack",16:"GPSImgDirectionRef",17:"GPSImgDirection",18:"GPSMapDatum",19:"GPSDestLatitudeRef",20:"GPSDestLatitude",21:"GPSDestLongitudeRef",22:"GPSDestLongitude",23:"GPSDestBearingRef",24:"GPSDestBearing",25:"GPSDestDistanceRef",26:"GPSDestDistance",27:"GPSProcessingMethod",28:"GPSAreaInformation",29:"GPSDateStamp",30:"GPSDifferential",31:"GPSHPositioningError"}}},592:t=>{function e(t,e){switch(t){case 1:return e.nextUInt8();case 3:case 8:return e.nextUInt16();case 4:case 9:return e.nextUInt32();case 5:return[e.nextUInt32(),e.nextUInt32()];case 6:return e.nextInt8();case 10:return[e.nextInt32(),e.nextInt32()];case 11:return e.nextFloat();case 12:return e.nextDouble();default:throw new Error("Invalid format while decoding: "+t)}}function r(t,r){var i,n,a=r.nextUInt16(),o=r.nextUInt16(),s=function(t){switch(t){case 1:case 2:case 6:case 7:return 1;case 3:case 8:return 2;case 4:case 9:case 11:return 4;case 5:case 10:case 12:return 8;default:return 0}}(o),h=r.nextUInt32(),l=s*h;if(l>4&&(r=t.openWithOffset(r.nextUInt32())),2===o){var f=(i=r.nextString(h)).indexOf("\0");-1!==f&&(i=i.substr(0,f))}else if(7===o)i=r.nextBuffer(h);else if(0!==o)for(i=[],n=0;n{t.exports={parseSections:function(t,e){var r,i;for(t.setBigEndian(!0);t.remainingLength()>0&&218!==i;){if(255!==t.nextUInt8())throw new Error("Invalid JPEG section offset");r=(i=t.nextUInt8())>=208&&i<=217||218===i?0:t.nextUInt16()-2,e(i,t.branch(0,r)),t.skip(r)}},getSizeFromSOFSection:function(t){return t.skip(1),{height:t.nextUInt16(),width:t.nextUInt16()}},getSectionName:function(t){var e,r;switch(t){case 216:e="SOI";break;case 196:e="DHT";break;case 219:e="DQT";break;case 221:e="DRI";break;case 218:e="SOS";break;case 254:e="COM";break;case 217:e="EOI";break;default:t>=224&&t<=239?(e="APP",r=t-224):t>=192&&t<=207&&196!==t&&200!==t&&204!==t?(e="SOF",r=t-192):t>=208&&t<=215&&(e="RST",r=t-208)}var i={name:e};return"number"==typeof r&&(i.index=r),i}}},453:(t,e,r)=>{var i=r(656),n=r(592),a=r(3814);function o(t,e,r,i,n,a,o){this.startMarker=t,this.tags=e,this.imageSize=r,this.thumbnailOffset=i,this.thumbnailLength=n,this.thumbnailType=a,this.app1Offset=o}function s(t){this.stream=t,this.flags={readBinaryTags:!1,resolveTagNames:!0,simplifyValues:!0,imageSize:!0,hidePointers:!0,returnTags:!0}}o.prototype={hasThumbnail:function(t){return!(!this.thumbnailOffset||!this.thumbnailLength||"string"==typeof t&&("image/jpeg"===t.toLowerCase().trim()?6!==this.thumbnailType:"image/tiff"!==t.toLowerCase().trim()||1!==this.thumbnailType))},getThumbnailOffset:function(){return this.app1Offset+6+this.thumbnailOffset},getThumbnailLength:function(){return this.thumbnailLength},getThumbnailBuffer:function(){return this._getThumbnailStream().nextBuffer(this.thumbnailLength)},_getThumbnailStream:function(){return this.startMarker.openWithOffset(this.getThumbnailOffset())},getImageSize:function(){return this.imageSize},getThumbnailSize:function(){var t,e=this._getThumbnailStream();return i.parseSections(e,(function(e,r){"SOF"===i.getSectionName(e).name&&(t=i.getSizeFromSOFSection(r))})),t}},s.prototype={enableBinaryFields:function(t){return this.flags.readBinaryTags=!!t,this},enablePointers:function(t){return this.flags.hidePointers=!t,this},enableTagNames:function(t){return this.flags.resolveTagNames=!!t,this},enableImageSize:function(t){return this.flags.imageSize=!!t,this},enableReturnTags:function(t){return this.flags.returnTags=!!t,this},enableSimpleValues:function(t){return this.flags.simplifyValues=!!t,this},parse:function(){var t,e,s,h,l,f,u,c,d,p=this.stream.mark(),m=p.openWithOffset(0),g=this.flags;return g.resolveTagNames&&(u=r(3332)),g.resolveTagNames?(t={},c=function(e){return t[e.name]},d=function(e,r){t[e.name]=r}):(t=[],c=function(e){var r;for(r=0;r{var i=r(592),n=r(565),a=[{section:i.GPSIFD,type:2,name:"GPSLatitude",refType:1,refName:"GPSLatitudeRef",posVal:"N"},{section:i.GPSIFD,type:4,name:"GPSLongitude",refType:3,refName:"GPSLongitudeRef",posVal:"E"}],o=[{section:i.SubIFD,type:306,name:"ModifyDate"},{section:i.SubIFD,type:36867,name:"DateTimeOriginal"},{section:i.SubIFD,type:36868,name:"CreateDate"},{section:i.SubIFD,type:306,name:"ModifyDate"}];t.exports={castDegreeValues:function(t,e){a.forEach((function(r){var i=t(r);if(i){var n=t({section:r.section,type:r.refType,name:r.refName})===r.posVal?1:-1,a=(i[0]+i[1]/60+i[2]/3600)*n;e(r,a)}}))},castDateValues:function(t,e){o.forEach((function(r){var i=t(r);if(i){var a=n.parseExifDate(i);void 0!==a&&e(r,a)}}))},simplifyValue:function(t,e){return Array.isArray(t)&&1===(t=t.map((function(t){return 10===e||5===e?t[0]/t[1]:t}))).length&&(t=t[0]),t}}},8789:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var Buffer=__webpack_require__(8834).lW;const Token=__webpack_require__(5010),strtok3=__webpack_require__(7378),{stringToBytes,tarHeaderChecksumMatches,uint32SyncSafeToken}=__webpack_require__(7044),supported=__webpack_require__(4078),minimumBytes=4100;async function fromStream(t){const e=await strtok3.fromStream(t);try{return await fromTokenizer(e)}finally{await e.close()}}async function fromBuffer(t){if(!(t instanceof Uint8Array||t instanceof ArrayBuffer||Buffer.isBuffer(t)))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof t}\``);const e=t instanceof Buffer?t:Buffer.from(t);if(e&&e.length>1)return fromTokenizer(strtok3.fromBuffer(e))}function _check(t,e,r){r={offset:0,...r};for(const[i,n]of e.entries())if(r.mask){if(n!==(r.mask[i]&t[i+r.offset]))return!1}else if(n!==t[i+r.offset])return!1;return!0}async function fromTokenizer(t){try{return _fromTokenizer(t)}catch(t){if(!(t instanceof strtok3.EndOfStreamError))throw t}}async function _fromTokenizer(t){let e=Buffer.alloc(minimumBytes);const r=(t,r)=>_check(e,t,r),i=(t,e)=>r(stringToBytes(t),e);if(t.fileInfo.size||(t.fileInfo.size=Number.MAX_SAFE_INTEGER),await t.peekBuffer(e,{length:12,mayBeLess:!0}),r([66,77]))return{ext:"bmp",mime:"image/bmp"};if(r([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(r([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(r([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(r([37,33]))return await t.peekBuffer(e,{length:24,mayBeLess:!0}),i("PS-Adobe-",{offset:2})&&i(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(r([31,160])||r([31,157]))return{ext:"Z",mime:"application/x-compress"};if(r([255,216,255]))return{ext:"jpg",mime:"image/jpeg"};if(r([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(r([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(r([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(i("ID3")){await t.ignore(6);const n=await t.readToken(uint32SyncSafeToken);return t.position+n>t.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await t.ignore(n),fromTokenizer(t))}if(i("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((67===e[0]||70===e[0])&&r([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(r([71,73,70]))return{ext:"gif",mime:"image/gif"};if(i("FLIF"))return{ext:"flif",mime:"image/flif"};if(i("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(i("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(i("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(i("FORM"))return{ext:"aif",mime:"audio/aiff"};if(i("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(r([80,75,3,4])){try{for(;t.position+30=0?o:e.length)}else await t.ignore(a.compressedSize)}}catch(s){if(!(s instanceof strtok3.EndOfStreamError))throw s}return{ext:"zip",mime:"application/zip"}}if(i("OggS")){await t.ignore(28);const h=Buffer.alloc(8);return await t.readBuffer(h),_check(h,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/opus"}:_check(h,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:_check(h,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:_check(h,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:_check(h,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:_check(h,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(r([80,75])&&(3===e[2]||5===e[2]||7===e[2])&&(4===e[3]||6===e[3]||8===e[3]))return{ext:"zip",mime:"application/zip"};if(i("ftyp",{offset:4})&&0!=(96&e[8])){const l=e.toString("binary",8,12).replace("\0"," ").trim();switch(l){case"avif":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return l.startsWith("3g")?l.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(i("MThd"))return{ext:"mid",mime:"audio/midi"};if(i("wOFF")&&(r([0,1,0,0],{offset:4})||i("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(i("wOF2")&&(r([0,1,0,0],{offset:4})||i("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(r([212,195,178,161])||r([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(i("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(i("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(i("fLaC"))return{ext:"flac",mime:"audio/x-flac"};if(r([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(i("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(i("%PDF")){await t.ignore(1350);const f=10485760,u=Buffer.alloc(Math.min(f,t.fileInfo.size));return await t.readBuffer(u,{mayBeLess:!0}),u.includes(Buffer.from("AIPrivateData"))?{ext:"ai",mime:"application/postscript"}:{ext:"pdf",mime:"application/pdf"}}if(r([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(r([73,73,42,0]))return i("CR",{offset:8})?{ext:"cr2",mime:"image/x-canon-cr2"}:r([28,0,254,0],{offset:8})||r([31,0,11,0],{offset:8})?{ext:"nef",mime:"image/x-nikon-nef"}:r([8,0,0,0],{offset:4})&&(r([45,0,254,0],{offset:8})||r([39,0,254,0],{offset:8}))?{ext:"dng",mime:"image/x-adobe-dng"}:(e=Buffer.alloc(24),await t.peekBuffer(e),(r([16,251,134,1],{offset:4})||r([8,0,0,0],{offset:4}))&&r([0,254,0,4,0,1,0,0,0,1,0,0,0,3,1],{offset:9})?{ext:"arw",mime:"image/x-sony-arw"}:{ext:"tif",mime:"image/tiff"});if(r([77,77,0,42]))return{ext:"tif",mime:"image/tiff"};if(i("MAC "))return{ext:"ape",mime:"audio/ape"};if(r([26,69,223,163])){async function c(){const e=await t.peekNumber(Token.UINT8);let r=128,i=0;for(;0==(e&r)&&0!==r;)++i,r>>=1;const n=Buffer.alloc(i+1);return await t.readBuffer(n),n}async function d(){const t=await c(),e=await c();e[0]^=128>>e.length-1;const r=Math.min(6,e.length);return{id:t.readUIntBE(0,t.length),len:e.readUIntBE(e.length-r,r)}}async function p(e,r){for(;r>0;){const e=await d();if(17026===e.id)return t.readToken(new Token.StringType(e.len,"utf-8"));await t.ignore(e.len),--r}}const m=await d();switch(await p(0,m.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(r([82,73,70,70])){if(r([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(r([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/vnd.wave"};if(r([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(i("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(r([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(i("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(i("MSCF")||i("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(r([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(r([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(r([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(r([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(i("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(i("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(r([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(i("IMPM"))return{ext:"it",mime:"audio/x-it"};if(i("-lh0-",{offset:2})||i("-lh1-",{offset:2})||i("-lh2-",{offset:2})||i("-lh3-",{offset:2})||i("-lh4-",{offset:2})||i("-lh5-",{offset:2})||i("-lh6-",{offset:2})||i("-lh7-",{offset:2})||i("-lzs-",{offset:2})||i("-lz4-",{offset:2})||i("-lz5-",{offset:2})||i("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(r([0,0,1,186])){if(r([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(r([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(i("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(r([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(i(""))return await t.ignore(8),"debian-binary"===await t.readToken(new Token.StringType(13,"ascii"))?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(r([137,80,78,71,13,10,26,10])){async function g(){return{length:await t.readToken(Token.INT32_BE),type:await t.readToken(new Token.StringType(4,"binary"))}}await t.ignore(8);do{const b=await g();if(b.length<0)return;switch(b.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await t.ignore(b.length+4)}}while(t.position+8=16){const x=e.readUInt32LE(12);if(x>12&&e.length>=x+16)try{const E=e.slice(16,x+16).toString();if(JSON.parse(E).files)return{ext:"asar",mime:"application/x-asar"}}catch(k){}}if(r([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(i("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(r([71],{offset:4})&&(r([71],{offset:192})||r([71],{offset:196})))return{ext:"mts",mime:"video/mp2t"};if(r([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(r([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(r([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(r([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(r([76,80],{offset:34})&&(r([0,0,1],{offset:8})||r([1,0,2],{offset:8})||r([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(r([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await t.peekBuffer(e,{length:Math.min(512,t.fileInfo.size),mayBeLess:!0}),tarHeaderChecksumMatches(e))return{ext:"tar",mime:"application/x-tar"};if(r([255,254,255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0]))return{ext:"skp",mime:"application/vnd.sketchup.skp"};if(i("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"};if(e.length>=2&&r([255,224],{offset:0,mask:[255,224]})){if(r([16],{offset:1,mask:[22]}))return r([8],{offset:1,mask:[8]}),{ext:"aac",mime:"audio/aac"};if(r([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(r([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(r([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}const stream=readableStream=>new Promise(((resolve,reject)=>{const stream=eval("require")("stream");readableStream.on("error",reject),readableStream.once("readable",(async()=>{const t=new stream.PassThrough;let e;e=stream.pipeline?stream.pipeline(readableStream,t,(()=>{})):readableStream.pipe(t);const r=readableStream.read(minimumBytes)||readableStream.read()||Buffer.alloc(0);try{const e=await fromBuffer(r);t.fileType=e}catch(t){reject(t)}resolve(e)}))})),fileType={fromStream,fromTokenizer,fromBuffer,stream};Object.defineProperty(fileType,"extensions",{get:()=>new Set(supported.extensions)}),Object.defineProperty(fileType,"mimeTypes",{get:()=>new Set(supported.mimeTypes)}),module.exports=fileType},5025:(t,e,r)=>{"use strict";const i=r(3569),n=r(8789),a={fromFile:async function(t){const e=await i.fromFile(t);try{return await n.fromTokenizer(e)}finally{await e.close()}}};Object.assign(a,n),Object.defineProperty(a,"extensions",{get:()=>n.extensions}),Object.defineProperty(a,"mimeTypes",{get:()=>n.mimeTypes}),t.exports=a},4078:t=>{"use strict";t.exports={extensions:["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf"],mimeTypes:["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/vnd.wave","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","audio/opus","video/ogg","audio/ogg","application/ogg","audio/x-flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd"]}},7044:(t,e)=>{"use strict";e.stringToBytes=t=>[...t].map((t=>t.charCodeAt(0))),e.tarHeaderChecksumMatches=(t,e=0)=>{const r=parseInt(t.toString("utf8",148,154).replace(/\0.*$/,"").trim(),8);if(isNaN(r))return!1;let i=256;for(let r=e;r127&t[e+3]|t[e+2]<<7|t[e+1]<<14|t[e]<<21,len:4}},3243:(t,e,r)=>{"use strict";var i=r(9680),n=Object.prototype.toString,a=Object.prototype.hasOwnProperty,o=function(t,e,r){for(var i=0,n=t.length;i=3&&(a=r),"[object Array]"===n.call(t)?o(t,e,a):"string"==typeof t?s(t,e,a):h(t,e,a)}},2855:(t,e)=>{"use strict";function r(t,e,r,i){for(var n=t[e++],a=1<>=h,f-=h,g!==a){if(g===o)break;for(var b=ga;)y=p[y]>>8,++_;var w=y;if(c+_+(b!==g?1:0)>i)return void console.log("Warning, gif stream longer than expected.");r[c++]=w;var v=c+=_;for(b!==g&&(r[c++]=w),y=b;_--;)y=p[y],r[--v]=255&y,y>>=8;null!==m&&s<4096&&(p[s++]=m<<8|w,s>=l+1&&h<12&&(++h,l=l<<1|1)),m=g}else s=o+1,l=(1<<(h=n+1))-1,m=null}return c!==i&&console.log("Warning, gif stream shorter than expected."),r}try{e.GifWriter=function(t,e,r,i){var n=0,a=void 0===(i=void 0===i?{}:i).loop?null:i.loop,o=void 0===i.palette?null:i.palette;if(e<=0||r<=0||e>65535||r>65535)throw new Error("Width/Height invalid.");function s(t){var e=t.length;if(e<2||e>256||e&e-1)throw new Error("Invalid code/color length, must be power of 2 and 2 .. 256.");return e}t[n++]=71,t[n++]=73,t[n++]=70,t[n++]=56,t[n++]=57,t[n++]=97;var h=0,l=0;if(null!==o){for(var f=s(o);f>>=1;)++h;if(f=1<=f)throw new Error("Background index out of range.");if(0===l)throw new Error("Background index explicitly passed as 0.")}}if(t[n++]=255&e,t[n++]=e>>8&255,t[n++]=255&r,t[n++]=r>>8&255,t[n++]=(null!==o?128:0)|h,t[n++]=l,t[n++]=0,null!==o)for(var u=0,c=o.length;u>16&255,t[n++]=d>>8&255,t[n++]=255&d}if(null!==a){if(a<0||a>65535)throw new Error("Loop count invalid.");t[n++]=33,t[n++]=255,t[n++]=11,t[n++]=78,t[n++]=69,t[n++]=84,t[n++]=83,t[n++]=67,t[n++]=65,t[n++]=80,t[n++]=69,t[n++]=50,t[n++]=46,t[n++]=48,t[n++]=3,t[n++]=1,t[n++]=255&a,t[n++]=a>>8&255,t[n++]=0}var p=!1;this.addFrame=function(e,r,i,a,h,l){if(!0===p&&(--n,p=!1),l=void 0===l?{}:l,e<0||r<0||e>65535||r>65535)throw new Error("x/y invalid.");if(i<=0||a<=0||i>65535||a>65535)throw new Error("Width/Height invalid.");if(h.length>=1;)++d;c=1<3)throw new Error("Disposal out of range.");var b=!1,_=0;if(void 0!==l.transparent&&null!==l.transparent&&(b=!0,(_=l.transparent)<0||_>=c))throw new Error("Transparent color index.");if((0!==g||b||0!==m)&&(t[n++]=33,t[n++]=249,t[n++]=4,t[n++]=g<<2|(!0===b?1:0),t[n++]=255&m,t[n++]=m>>8&255,t[n++]=_,t[n++]=0),t[n++]=44,t[n++]=255&e,t[n++]=e>>8&255,t[n++]=255&r,t[n++]=r>>8&255,t[n++]=255&i,t[n++]=i>>8&255,t[n++]=255&a,t[n++]=a>>8&255,t[n++]=!0===f?128|d-1:0,!0===f)for(var y=0,w=u.length;y>16&255,t[n++]=v>>8&255,t[n++]=255&v}return n=function(t,e,r,i){t[e++]=r;var n=e++,a=1<=r;)t[e++]=255&u,u>>=8,f-=8,e===n+256&&(t[n]=255,n=e++)}function d(t){u|=t<=8;)t[e++]=255&u,u>>=8,f-=8,e===n+256&&(t[n]=255,n=e++);4096===h?(d(a),h=s+1,l=r+1,m={}):(h>=1<>7,s=1<<1+(7&a);t[e++],t[e++];var h=null,l=null;o&&(h=e,l=s,e+=3*s);var f=!0,u=[],c=0,d=null,p=0,m=null;for(this.width=i,this.height=n;f&&e=0))throw Error("Invalid block size");if(0===I)break;e+=I}break;case 249:if(4!==t[e++]||0!==t[e+4])throw new Error("Invalid graphics extension block.");var g=t[e++];c=t[e++]|t[e++]<<8,d=t[e++],0==(1&g)&&(d=null),p=g>>2&7,e++;break;case 254:for(;;){if(!((I=t[e++])>=0))throw Error("Invalid block size");if(0===I)break;e+=I}break;default:throw new Error("Unknown graphic control label: 0x"+t[e-1].toString(16))}break;case 44:var b=t[e++]|t[e++]<<8,_=t[e++]|t[e++]<<8,y=t[e++]|t[e++]<<8,w=t[e++]|t[e++]<<8,v=t[e++],x=v>>6&1,E=1<<1+(7&v),k=h,S=l,M=!1;v>>7&&(M=!0,k=e,S=E,e+=3*E);var A=e;for(e++;;){var I;if(!((I=t[e++])>=0))throw Error("Invalid block size");if(0===I)break;e+=I}u.push({x:b,y:_,width:y,height:w,has_local_palette:M,palette_offset:k,palette_size:S,data_offset:A,data_length:e-A,transparent_index:d,interlaced:!!x,delay:c,disposal:p});break;case 59:f=!1;break;default:throw new Error("Unknown gif block: 0x"+t[e-1].toString(16))}this.numFrames=function(){return u.length},this.loopCount=function(){return m},this.frameInfo=function(t){if(t<0||t>=u.length)throw new Error("Frame index out of range.");return u[t]},this.decodeAndBlitFrameBGRA=function(e,n){var a=this.frameInfo(e),o=a.width*a.height,s=new Uint8Array(o);r(t,a.data_offset,s,o);var h=a.palette_offset,l=a.transparent_index;null===l&&(l=256);var f=a.width,u=i-f,c=f,d=4*(a.y*i+a.x),p=4*((a.y+a.height)*i+a.x),m=d,g=4*u;!0===a.interlaced&&(g+=4*i*7);for(var b=8,_=0,y=s.length;_=p&&(g=4*u+4*i*(b-1),m=d+(f+u)*(b<<1),b>>=1)),w===l)m+=4;else{var v=t[h+3*w],x=t[h+3*w+1],E=t[h+3*w+2];n[m++]=E,n[m++]=x,n[m++]=v,n[m++]=255}--c}},this.decodeAndBlitFrameRGBA=function(e,n){var a=this.frameInfo(e),o=a.width*a.height,s=new Uint8Array(o);r(t,a.data_offset,s,o);var h=a.palette_offset,l=a.transparent_index;null===l&&(l=256);var f=a.width,u=i-f,c=f,d=4*(a.y*i+a.x),p=4*((a.y+a.height)*i+a.x),m=d,g=4*u;!0===a.interlaced&&(g+=4*i*7);for(var b=8,_=0,y=s.length;_=p&&(g=4*u+4*i*(b-1),m=d+(f+u)*(b<<1),b>>=1)),w===l)m+=4;else{var v=t[h+3*w],x=t[h+3*w+1],E=t[h+3*w+2];n[m++]=v,n[m++]=x,n[m++]=E,n[m++]=255}--c}}}}catch(t){}},7604:(t,e,r)=>{"use strict";var i=r(8834).lW;class n{constructor(...t){if(0===t.length)throw new Error("constructor requires parameters");const e=t[0];if(null!==e&&"object"==typeof e)if(e instanceof n){const t=e.bitmap;this.bitmap={width:t.width,height:t.height,data:new i(t.width*t.height*4)},t.data.copy(this.bitmap.data)}else{if(!(e.width&&e.height&&e.data))throw new Error("unrecognized constructor parameters");this.bitmap=e}else{if("number"!=typeof e||"number"!=typeof t[1])throw new Error("unrecognized constructor parameters");{const r=e,n=t[1],a=t[2];this.bitmap={width:r,height:n},i.isBuffer(a)?this.bitmap.data=a:(this.bitmap.data=new i(r*n*4),"number"==typeof a&&this.fillRGBA(a))}}}blit(t,e,r,i,n,a,o){if(i+a>this.bitmap.width)throw new Error("copy exceeds width of source bitmap");if(e+a>t.bitmap.width)throw new Error("copy exceeds width of target bitmap");if(n+o>this.bitmap.height)throw new Error("copy exceeds height of source bitmap");if(r+o>t.bitmap.height)throw new Erro("copy exceeds height of target bitmap");const s=this.bitmap.data,h=t.bitmap.data,l=4*this.bitmap.width,f=4*t.bitmap.width,u=4*a;let c=n*l+4*i,d=r*f+4*e;for(;--o>=0;)s.copy(h,d,c,c+u),c+=l,d+=f;return this}fillRGBA(t){const e=this.bitmap.data,r=4*this.bitmap.height;let i=0;for(;i{const n=Math.round(.299*t[i]+.587*t[i+1]+.114*t[i+2]);t[i]=n,t[i+1]=n,t[i+2]=n})),this}reframe(t,e,r,i,a){const o=t<0?0:t,s=e<0?0:e,h=r+o>this.bitmap.width?this.bitmap.width-o:r,l=i+s>this.bitmap.height?this.bitmap.height-s:i,f=t<0?-t:0,u=e<0?-e:0;let c;if(void 0===a){if(o!==t||s!=e||h!==r||l!==i)throw new GifError("fillRGBA required for this reframing");c=new n(r,i)}else c=new n(r,i,a);return this.blit(c,f,u,o,s,h,l),this.bitmap=c.bitmap,this}scale(t){if(1===t)return;if(!Number.isInteger(t)||t<1)throw new Error("the scale must be an integer >= 1");const e=this.bitmap.width,r=this.bitmap.height,n=e*t*4,a=this.bitmap.data,o=new i(r*n*t);let s,h=0,l=0;for(let i=0;i{"use strict";class r{constructor(t,e,r){this.width=r.width,this.height=r.height,this.loops=r.loops,this.usesTransparency=r.usesTransparency,this.colorScope=r.colorScope,this.frames=e,this.buffer=t}}r.GlobalColorsPreferred=0,r.GlobalColorsOnly=1,r.LocalColorsOnly=2;class i extends Error{constructor(t){super(t),t instanceof Error&&(this.stack="Gif"+t.stack)}}e.Gif=r,e.GifError=i},6512:(t,e,r)=>{"use strict";var i=r(8834).lW;const n=r(2855),{Gif:a,GifError:o}=r(4364);function s(){const t=r(4602);return s=function(){return t},t}const{GifFrame:h}=r(5585),l=100;function f(t,e){const r=t.indexOf(e);return-1===r?null:r}function u(t,e){for(var r,i=0,n=t.length-1;i<=n;)if(t[r=Math.floor((i+n)/2)]>e)n=r-1;else{if(!(t[r]i;)i<<=1;e.length=i,e.fill(0,r)}function d(t,e){let r=t.bitmap.width*t.bitmap.height;return r=Math.ceil(r*e/8),r+=Math.ceil(r/255),l+r+768}function p(t){let e=t.indexCount,r=0;for(--e;e;)++r,e>>=1;return r>0?r:1}function m(t,e,r,n,a){if(r.interlaced)throw new o("writing interlaced GIFs is not supported");const s=function(t,e,r){const n=r.colors,a=n.length<=8?f:u,s=e.bitmap.data,h=new i(s.length/4);let l=n.length,c=0,d=0;for(;c>8&16777215;h[d]=a(n,t)}else h[d]=l;c+=4,++d}if(r.usesTransparency){if(256===l)throw new o(`Frame ${t} already has 256 colorsand so can't use transparency`)}else l=null;return{buffer:h,transparentIndex:l}}(e,r,n),h={delay:r.delayCentisecs,disposal:r.disposalMethod,transparent:s.transparentIndex};a&&(c(n),h.palette=n.colors);try{let e,n=t.getOutputBuffer(),a=t.getOutputBufferPosition(),o=!0;for(;o;)if(e=t.addFrame(r.xOffset,r.yOffset,r.bitmap.width,r.bitmap.height,s.buffer,h),o=!1,e>=n.length-1){const e=new i(1.5*n.length);n.copy(e),t.setOutputBuffer(e),t.setOutputBufferPosition(a),n=e,o=!0}return n}catch(t){throw new o(t)}}e.GifCodec=class{constructor(t={}){this._transparentRGB=null,"number"==typeof t.transparentRGB&&0!==t.transparentRGB&&(this._transparentRGBA=256*t.transparentRGB),this._testInitialBufferSize=0}decodeGif(t){try{let e;try{e=new n.GifReader(t)}catch(t){throw new o(t)}const r=e.numFrames(),i=[],s={width:e.width,height:e.height,loops:e.loopCount(),usesTransparency:!1};for(let t=0;tn.width)for(let e=0;e0)return this._testInitialBufferSize;let r=968;const i=p(t);return e.forEach((t=>{r+=d(t,i)})),r}_getSizeEstimateLocal(t,e){if(this._testInitialBufferSize>0)return this._testInitialBufferSize;let r=200;for(let i=0;i{"use strict";const i=r(7604),{GifError:n}=r(4364);class a extends i{constructor(...t){if(super(...t),t[0]instanceof a){const e=t[0];this.xOffset=e.xOffset,this.yOffset=e.yOffset,this.disposalMethod=e.disposalMethod,this.delayCentisecs=e.delayCentisecs,this.interlaced=e.interlaced}else{const e=t[t.length-1];let r={};"object"!=typeof e||e instanceof i||(r=e),this.xOffset=r.xOffset||0,this.yOffset=r.yOffset||0,this.disposalMethod=void 0!==r.disposalMethod?r.disposalMethod:a.DisposeToBackgroundColor,this.delayCentisecs=r.delayCentisecs||8,this.interlaced=r.interlaced||!1}}getPalette(){const t=new Set,e=this.bitmap.data;let r=0,i=!1;for(;r>8&16777215;t.add(i)}r+=4}const n=new Array(t.size),a=t.values();for(r=0;rt-e));let o=n.length;return i&&++o,{colors:n,usesTransparency:i,indexCount:o}}}a.DisposeToAnything=0,a.DisposeNothing=1,a.DisposeToBackgroundColor=2,a.DisposeToPrevious=3,e.GifFrame=a},4602:(t,e,r)=>{"use strict";var i=r(8834).lW;const n=r(8522),a=r(2460),o=r(7604),{GifFrame:s}=r(5585),{GifError:h}=r(4364),{GifCodec:l}=r(6512),f=[".jpg",".jpeg",".png",".bmp"],u=new l;function c(t,e,r,i,n){const o=Array.isArray(t)?t:[t];if(n){if(["FloydSteinberg","FalseFloydSteinberg","Stucki","Atkinson","Jarvis","Burkes","Sierra","TwoSierra","SierraLite"].indexOf(n.ditherAlgorithm)<0)throw new Error(`Invalid ditherAlgorithm '${n.ditherAlgorithm}'`);void 0===n.serpentine&&(n.serpentine=!0),void 0===n.minimumColorDistanceToDither&&(n.minimumColorDistanceToDither=0),void 0===n.calculateErrorLikeGIMP&&(n.calculateErrorLikeGIMP=!1)}const s=new a.distance.Euclidean,h=new a.palette[e](s,r,i);let l;l=n?new a.image.ErrorDiffusionArray(s,a.image.ErrorDiffusionArrayKernel[n.ditherAlgorithm],n.serpentine,n.minimumColorDistanceToDither,n.calculateErrorLikeGIMP):new a.image.NearestColor(s);const f=[];o.forEach((t=>{const e=t.bitmap.data,r=new ArrayBuffer(e.length),i=new Uint32Array(r);for(let t=0,r=0;t{e.push(new s(t))})),e},e.getColorInfo=function(t,e){let r=!1;const i=[];for(let e=0;e256)throw new h(`Frame ${e} uses more than 256 color indexes`);i.push(n)}if(0===e)return{usesTransparency:r,palettes:i};const n=new Set;i.forEach((t=>{t.colors.forEach((t=>{n.add(t)}))}));let a=n.size;if(r&&++a,e&&a>e)return{usesTransparency:r,palettes:i};const o=new Array(n.size),s=n.values();for(let t=0;tt-e)),{colors:o,indexCount:a,usesTransparency:r,palettes:i}},e.copyAsJimp=function(t,r){return e.shareAsJimp(t,new o(r))},e.getMaxDimensions=function(t){let e=0,r=0;return t.forEach((t=>{const i=t.xOffset+t.bitmap.width;i>e&&(e=i);const n=t.yOffset+t.bitmap.height;n>r&&(r=n)})),{maxWidth:e,maxHeight:r}},e.quantizeDekker=function(t,e,r){c(t,"NeuQuantFloat",e=e||256,0,r)},e.quantizeSorokin=function(t,e,r,i){let n;switch(e=e||256,r=r||"min-pop"){case"min-pop":n=2;break;case"top-pop":n=1;break;default:throw new Error(`Invalid quantizeSorokin histogram '${r}'`)}c(t,"RGBQuant",e,n,i)},e.quantizeWu=function(t,e,r,i){if(e=e||256,(r=r||5)<1||r>8)throw new Error("Invalid quantization quality");c(t,"WuQuant",e,r,i)},e.read=function(t,e){return e=e||u,i.isBuffer(t)?e.decodeGif(t):(r=t,new Promise(((t,e)=>{n.readFile(r,((r,i)=>r?e(r):t(i)))}))).then((t=>e.decodeGif(t)));var r},e.shareAsJimp=function(t,e){const r=new t(e.bitmap.width,e.bitmap.height,0);return r.bitmap.data=e.bitmap.data,r},e.write=function(t,e,r,i){i=i||u;const a=t.match(/\.[a-zA-Z]+$/);if(null!==a&&f.includes(a[0].toLowerCase()))throw new Error(`GIF '${t}' has an unexpected suffix`);return i.encodeGif(e,r).then((e=>function(t,e){return new Promise(((r,i)=>{n.writeFile(t,e,(t=>t?i(t):r()))}))}(t,e.buffer).then((()=>e))))}},9455:(t,e,r)=>{"use strict";const i=r(7604),{Gif:n,GifError:a}=r(4364),{GifCodec:o}=r(6512),{GifFrame:s}=r(5585),h=r(4602);t.exports={BitmapImage:i,Gif:n,GifCodec:o,GifFrame:s,GifUtil:h,GifError:a}},5048:(t,e,r)=>{var i;i="undefined"!=typeof window?window:void 0!==r.g?r.g:"undefined"!=typeof self?self:{},t.exports=i},2333:(t,e)=>{e.read=function(t,e,r,i,n){var a,o,s=8*n-i-1,h=(1<>1,f=-7,u=r?n-1:0,c=r?-1:1,d=t[e+u];for(u+=c,a=d&(1<<-f)-1,d>>=-f,f+=s;f>0;a=256*a+t[e+u],u+=c,f-=8);for(o=a&(1<<-f)-1,a>>=-f,f+=i;f>0;o=256*o+t[e+u],u+=c,f-=8);if(0===a)a=1-l;else{if(a===h)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,i),a-=l}return(d?-1:1)*o*Math.pow(2,a-i)},e.write=function(t,e,r,i,n,a){var o,s,h,l=8*a-n-1,f=(1<>1,c=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:a-1,p=i?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),(e+=o+u>=1?c/h:c*Math.pow(2,1-u))*h>=2&&(o++,h/=2),o+u>=f?(s=0,o=f):o+u>=1?(s=(e*h-1)*Math.pow(2,n),o+=u):(s=e*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;t[r+d]=255&s,d+=p,s/=256,n-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,l-=8);t[r+d-p]|=128*m}},9680:t=>{"use strict";var e=Function.prototype.toString,r=/^\s*class\b/,i=function(t){try{var i=e.call(t);return r.test(i)}catch(t){return!1}},n=Object.prototype.toString,a="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag;t.exports=function(t){if(!t)return!1;if("function"!=typeof t&&"object"!=typeof t)return!1;if("function"==typeof t&&!t.prototype)return!0;if(a)return function(t){try{return!i(t)&&(e.call(t),!0)}catch(t){return!1}}(t);if(i(t))return!1;var r=n.call(t);return"[object Function]"===r||"[object GeneratorFunction]"===r}},9748:t=>{t.exports=function(t){var r=e.call(t);return"[object Function]"===r||"function"==typeof t&&"[object RegExp]"!==r||"undefined"!=typeof window&&(t===window.setTimeout||t===window.alert||t===window.confirm||t===window.prompt)};var e=Object.prototype.toString},9307:(t,e,r)=>{r(6168),t.exports=self.fetch.bind(self)},2691:(t,e,r)=>{var i=r(706),n=r(770);t.exports={encode:i,decode:n}},770:(t,e,r)=>{var i=r(8834).lW,n=function(){"use strict";var t=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),e=4017,r=799,i=3406,n=2276,a=1567,o=3784,s=5793,h=2896;function l(){}function f(t,e){for(var r,i,n=0,a=[],o=16;o>0&&!t[o-1];)o--;a.push({children:[],index:0});var s,h=a[0];for(r=0;r0;){if(0===a.length)throw new Error("Could not recreate Huffman Table");h=a.pop()}for(h.index++,a.push(h);a.length<=r;)a.push(s={children:[],index:0}),h.children[h.index]=s.children,h=s;n++}r+10)return m--,p>>m&1;if(255==(p=e[r++])){var t=e[r++];if(t)throw new Error("unexpected marker: "+(p<<8|t).toString(16))}return m=7,p>>>7}function b(t){for(var e,r=t;null!==(e=g());){if("number"==typeof(r=r[e]))return r;if("object"!=typeof r)throw new Error("invalid huffman sequence")}return null}function _(t){for(var e=0;t>0;){var r=g();if(null===r)return;e=e<<1|r,t--}return e}function y(t){var e=_(t);return e>=1<0)v--;else for(var i=o,n=s;i<=n;){var a=b(e.huffmanTableAC),h=15&a,f=a>>4;if(0!==h)r[t[i+=f]]=y(h)*(1<>4,0===c)a<15?(v=_(a)+(1<>4;if(0!==s)r[t[a+=h]]=y(s),a++;else{if(h<15)break;a+=16}}};var P,O,L,C,U=0;for(O=1==R?n[0].blocksPerLine*n[0].blocksPerColumn:u*i.mcusPerColumn,a||(a=O);U=65488&&P<=65495))break;r+=2}return r-d}function c(t,l){var f,u,c=[],d=l.blocksPerLine,p=l.blocksPerColumn,m=d<<3,b=new Int32Array(64),_=new Uint8Array(64);function y(t,f,u){var c,d,p,m,g,b,_,y,w,v,x=l.quantizationTable,E=u;for(v=0;v<64;v++)E[v]=t[v]*x[v];for(v=0;v<8;++v){var k=8*v;0!=E[1+k]||0!=E[2+k]||0!=E[3+k]||0!=E[4+k]||0!=E[5+k]||0!=E[6+k]||0!=E[7+k]?(c=s*E[0+k]+128>>8,d=s*E[4+k]+128>>8,p=E[2+k],m=E[6+k],g=h*(E[1+k]-E[7+k])+128>>8,y=h*(E[1+k]+E[7+k])+128>>8,b=E[3+k]<<4,_=E[5+k]<<4,w=c-d+1>>1,c=c+d+1>>1,d=w,w=p*o+m*a+128>>8,p=p*a-m*o+128>>8,m=w,w=g-_+1>>1,g=g+_+1>>1,_=w,w=y+b+1>>1,b=y-b+1>>1,y=w,w=c-m+1>>1,c=c+m+1>>1,m=w,w=d-p+1>>1,d=d+p+1>>1,p=w,w=g*n+y*i+2048>>12,g=g*i-y*n+2048>>12,y=w,w=b*r+_*e+2048>>12,b=b*e-_*r+2048>>12,_=w,E[0+k]=c+y,E[7+k]=c-y,E[1+k]=d+_,E[6+k]=d-_,E[2+k]=p+b,E[5+k]=p-b,E[3+k]=m+g,E[4+k]=m-g):(w=s*E[0+k]+512>>10,E[0+k]=w,E[1+k]=w,E[2+k]=w,E[3+k]=w,E[4+k]=w,E[5+k]=w,E[6+k]=w,E[7+k]=w)}for(v=0;v<8;++v){var S=v;0!=E[8+S]||0!=E[16+S]||0!=E[24+S]||0!=E[32+S]||0!=E[40+S]||0!=E[48+S]||0!=E[56+S]?(c=s*E[0+S]+2048>>12,d=s*E[32+S]+2048>>12,p=E[16+S],m=E[48+S],g=h*(E[8+S]-E[56+S])+2048>>12,y=h*(E[8+S]+E[56+S])+2048>>12,b=E[24+S],_=E[40+S],w=c-d+1>>1,c=c+d+1>>1,d=w,w=p*o+m*a+2048>>12,p=p*a-m*o+2048>>12,m=w,w=g-_+1>>1,g=g+_+1>>1,_=w,w=y+b+1>>1,b=y-b+1>>1,y=w,w=c-m+1>>1,c=c+m+1>>1,m=w,w=d-p+1>>1,d=d+p+1>>1,p=w,w=g*n+y*i+2048>>12,g=g*i-y*n+2048>>12,y=w,w=b*r+_*e+2048>>12,b=b*e-_*r+2048>>12,_=w,E[0+S]=c+y,E[56+S]=c-y,E[8+S]=d+_,E[48+S]=d-_,E[16+S]=p+b,E[40+S]=p-b,E[24+S]=m+g,E[32+S]=m-g):(w=s*u[v+0]+8192>>14,E[0+S]=w,E[8+S]=w,E[16+S]=w,E[24+S]=w,E[32+S]=w,E[40+S]=w,E[48+S]=w,E[56+S]=w)}for(v=0;v<64;++v){var M=128+(E[v]+8>>4);f[v]=M<0?0:M>255?255:M}}g(m*p*8);for(var w=0;w255?255:t}l.prototype={load:function(t){var e=new XMLHttpRequest;e.open("GET",t,!0),e.responseType="arraybuffer",e.onload=function(){var t=new Uint8Array(e.response||e.mozResponseArrayBuffer);this.parse(t),this.onload&&this.onload()}.bind(this),e.send(null)},parse:function(e){var r=1e3*this.opts.maxResolutionInMP*1e3,i=0;function n(){var t=e[i]<<8|e[i+1];return i+=2,t}function a(t){var e,r,i=1,n=1;for(r in t.components)t.components.hasOwnProperty(r)&&(i<(e=t.components[r]).h&&(i=e.h),n>4==0)for(V=0;V<64;V++)M[t[V]]=e[i++];else{if(S>>4!=1)throw new Error("DQT: invalid table spec");for(V=0;V<64;V++)M[t[V]]=n()}m[15&S]=M}break;case 65472:case 65473:case 65474:n(),(o={}).extended=65473===w,o.progressive=65474===w,o.precision=e[i++],o.scanLines=n(),o.samplesPerLine=n(),o.components={},o.componentsOrder=[];var A=o.scanLines*o.samplesPerLine;if(A>r){var I=Math.ceil((A-r)/1e6);throw new Error(`maxResolutionInMP limit exceeded by ${I}MP`)}var B,T=e[i++];for(Z=0;Z>4,P=15&e[i+1],O=e[i+2];if(R<=0||P<=0)throw new Error("Invalid sampling factor, expected values above 0");o.componentsOrder.push(B),o.components[B]={h:R,v:P,quantizationIdx:O},i+=3}a(o),b.push(o);break;case 65476:var L=n();for(Z=2;Z>4==0?y:_)[15&C]=f(U,D)}break;case 65501:n(),s=n();break;case 65500:n(),n();break;case 65498:n();var N=e[i++],F=[];for(Z=0;Z>4],X.huffmanTableAC=_[15&j],F.push(X)}var G=e[i++],H=e[i++],W=e[i++],q=u(e,i,o,F,s,G,H,W>>4,15&W,this.opts);i+=q;break;case 65535:255!==e[i]&&i--;break;default:if(255==e[i-3]&&e[i-2]>=192&&e[i-2]<=254){i-=3;break}if(224===w||225==w){if(-1!==v)throw new Error(`first unknown JPEG marker at offset ${v.toString(16)}, second unknown JPEG marker ${w.toString(16)} at offset ${(i-1).toString(16)}`);v=i-1;const t=n();if(255===e[i+t-2]){i+=t-2;break}}throw new Error("unknown JPEG marker "+w.toString(16))}w=n()}if(1!=b.length)throw new Error("only single frame JPEGs supported");for(var Z=0;Zm){var r=Math.ceil((e-m)/1024/1024);throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${r}MB`)}p=e}return l.resetMaxMemoryUsage=function(t){p=0,m=t},l.getBytesAllocated=function(){return p},l.requestMemoryAllocation=g,l}();t.exports=function(t,e={}){var r={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512,...e},a=new Uint8Array(t),o=new n;o.opts=r,n.resetMaxMemoryUsage(1024*r.maxMemoryUsageInMB*1024),o.parse(a);var s=r.formatAsRGBA?4:3,h=o.width*o.height*s;try{n.requestMemoryAllocation(h);var l={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(h):i.alloc(h)};o.comments.length>0&&(l.comments=o.comments)}catch(t){if(t instanceof RangeError)throw new Error("Could not allocate enough memory for the image. Required: "+h);if(t instanceof ReferenceError&&"Buffer is not defined"===t.message)throw new Error("Buffer is not globally defined in this environment. Consider setting useTArray to true");throw t}return o.copyToImageData(l,r.formatAsRGBA),l}},706:(t,e,r)=>{var i=r(8834).lW;function n(t){Math.round;var e,r,n,a,o,s=Math.floor,h=new Array(64),l=new Array(64),f=new Array(64),u=new Array(64),c=new Array(65535),d=new Array(65535),p=new Array(64),m=new Array(64),g=[],b=0,_=7,y=new Array(64),w=new Array(64),v=new Array(64),x=new Array(256),E=new Array(2048),k=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],S=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],M=[0,1,2,3,4,5,6,7,8,9,10,11],A=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],I=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],B=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],T=[0,1,2,3,4,5,6,7,8,9,10,11],R=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],P=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function O(t,e){for(var r=0,i=0,n=new Array,a=1;a<=16;a++){for(var o=1;o<=t[a];o++)n[e[i]]=[],n[e[i]][0]=r,n[e[i]][1]=a,i++,r++;r*=2}return n}function L(t){for(var e=t[0],r=t[1]-1;r>=0;)e&1<>8&255),C(255&t)}function z(t,e,r,i,n){for(var a,o=n[0],s=n[240],h=function(t,e){var r,i,n,a,o,s,h,l,f,u,c=0;for(f=0;f<8;++f){r=t[c],i=t[c+1],n=t[c+2],a=t[c+3],o=t[c+4],s=t[c+5],h=t[c+6];var d=r+(l=t[c+7]),m=r-l,g=i+h,b=i-h,_=n+s,y=n-s,w=a+o,v=a-o,x=d+w,E=d-w,k=g+_,S=g-_;t[c]=x+k,t[c+4]=x-k;var M=.707106781*(S+E);t[c+2]=E+M,t[c+6]=E-M;var A=.382683433*((x=v+y)-(S=b+m)),I=.5411961*x+A,B=1.306562965*S+A,T=.707106781*(k=y+b),R=m+T,P=m-T;t[c+5]=P+I,t[c+3]=P-I,t[c+1]=R+B,t[c+7]=R-B,c+=8}for(c=0,f=0;f<8;++f){r=t[c],i=t[c+8],n=t[c+16],a=t[c+24],o=t[c+32],s=t[c+40],h=t[c+48];var O=r+(l=t[c+56]),L=r-l,C=i+h,U=i-h,z=n+s,D=n-s,N=a+o,F=a-o,j=O+N,G=O-N,H=C+z,W=C-z;t[c]=j+H,t[c+32]=j-H;var q=.707106781*(W+G);t[c+16]=G+q,t[c+48]=G-q;var Z=.382683433*((j=F+D)-(W=U+L)),Y=.5411961*j+Z,V=1.306562965*W+Z,X=.707106781*(H=D+U),J=L+X,Q=L-X;t[c+40]=Q+Y,t[c+24]=Q-Y,t[c+8]=J+V,t[c+56]=J-V,c++}for(f=0;f<64;++f)u=t[f]*e[f],p[f]=u>0?u+.5|0:u-.5|0;return p}(t,e),l=0;l<64;++l)m[k[l]]=h[l];var f=m[0]-r;r=m[0],0==f?L(i[0]):(L(i[d[a=32767+f]]),L(c[a]));for(var u=63;u>0&&0==m[u];u--);if(0==u)return L(o),r;for(var g,b=1;b<=u;){for(var _=b;0==m[b]&&b<=u;++b);var y=b-_;if(y>=16){g=y>>4;for(var w=1;w<=g;++w)L(s);y&=15}a=32767+m[b],L(n[(y<<4)+d[a]]),L(c[a]),b++}return 63!=u&&L(o),r}function D(t){t<=0&&(t=1),t>100&&(t=100),o!=t&&(function(t){for(var e=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],r=0;r<64;r++){var i=s((e[r]*t+50)/100);i<1?i=1:i>255&&(i=255),h[k[r]]=i}for(var n=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],a=0;a<64;a++){var o=s((n[a]*t+50)/100);o<1?o=1:o>255&&(o=255),l[k[a]]=o}for(var c=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],d=0,p=0;p<8;p++)for(var m=0;m<8;m++)f[d]=1/(h[k[d]]*c[p]*c[m]*8),u[d]=1/(l[k[d]]*c[p]*c[m]*8),d++}(t<50?Math.floor(5e3/t):Math.floor(200-2*t)),o=t)}this.encode=function(t,o){var s;(new Date).getTime(),o&&D(o),g=new Array,b=0,_=7,U(65496),U(65504),U(16),C(74),C(70),C(73),C(70),C(0),C(1),C(1),C(0),U(1),U(1),C(0),C(0),void 0!==(s=t.comments)&&s.constructor===Array&&s.forEach((t=>{if("string"==typeof t){U(65534);var e,r=t.length;for(U(r+2),e=0;e>3)*Y+(j=4*(7&H)),V+G>=Z&&(F-=Y*(V+1+G-Z)),m+j>=Y&&(F-=m+j-Y+4),x=W[F++],k=W[F++],O=W[F++],y[H]=(E[x]+E[k+256>>0]+E[O+512>>0]>>16)-128,w[H]=(E[x+768>>0]+E[k+1024>>0]+E[O+1280>>0]>>16)-128,v[H]=(E[x+1280>>0]+E[k+1536>>0]+E[O+1792>>0]>>16)-128;c=z(y,f,c,e,n),d=z(w,u,d,r,a),p=z(v,u,p,r,a),m+=32}V+=8}if(_>=0){var X=[];X[1]=_+1,X[0]=(1<<_+1)-1,L(X)}return U(65497),i.from(g)},(new Date).getTime(),t||(t=50),function(){for(var t=String.fromCharCode,e=0;e<256;e++)x[e]=t(e)}(),e=O(S,M),r=O(B,T),n=O(A,I),a=O(R,P),function(){for(var t=1,e=2,r=1;r<=15;r++){for(var i=t;i>0]=38470*t,E[t+512>>0]=7471*t+32768,E[t+768>>0]=-11059*t,E[t+1024>>0]=-21709*t,E[t+1280>>0]=32768*t+8421375,E[t+1536>>0]=-27439*t,E[t+1792>>0]=-5329*t}(),D(t),(new Date).getTime()}t.exports=function(t,e){return void 0===e&&(e=50),{data:new n(e).encode(t,e),width:t.width,height:t.height}}},8058:(t,e,r)=>{var i=r(8834).lW,n=r(6290),a=function(){},o=r(4398),s=r(5947),h=r(8438),l=r(5565),f=r(1960),u=self.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest;t.exports=function(t,e){e="function"==typeof e?e:a,"string"==typeof t?t={uri:t}:t||(t={}),t.binary&&(t=function(t){if(u)return f(t,{responseType:"arraybuffer"});if(void 0===self.XMLHttpRequest)throw new Error("your browser does not support XHR loading");var e=new self.XMLHttpRequest;return e.overrideMimeType("text/plain; charset=x-user-defined"),f({xhr:e},t)}(t)),n(t,(function(r,n,f){if(r)return e(r);if(!/^2/.test(n.statusCode))return e(new Error("http status code: "+n.statusCode));if(!f)return e(new Error("no body result"));var u,c,d=!1;if(u=f,"[object ArrayBuffer]"===Object.prototype.toString.call(u)){var p=new Uint8Array(f);f=i.from(p,"binary")}l(f)&&(d=!0,"string"==typeof f&&(f=i.from(f,"binary"))),d||(i.isBuffer(f)&&(f=f.toString(t.encoding)),f=f.trim());try{var m=n.headers["content-type"];c=d?h(f):/json/.test(m)||"{"===f.charAt(0)?JSON.parse(f):/xml/.test(m)||"<"===f.charAt(0)?s(f):o(f)}catch(t){e(new Error("error parsing font "+t.message)),e=a}e(null,c)}))}},5565:(t,e,r)=>{var i=r(8834).lW,n=r(5137),a=i.from([66,77,70,3]);t.exports=function(t){return"string"==typeof t?"BMF"===t.substring(0,3):t.length>4&&n(t.slice(0,4),a)}},63:(t,e)=>{"use strict";function r(t,e,r,i){for(var n=t[e++],a=1<>=h,f-=h,g!==a){if(g===o)break;for(var b=ga;)y=p[y]>>8,++_;var w=y;if(c+_+(b!==g?1:0)>i)return void console.log("Warning, gif stream longer than expected.");r[c++]=w;var v=c+=_;for(b!==g&&(r[c++]=w),y=b;_--;)y=p[y],r[--v]=255&y,y>>=8;null!==m&&s<4096&&(p[s++]=m<<8|w,s>=l+1&&h<12&&(++h,l=l<<1|1)),m=g}else s=o+1,l=(1<<(h=n+1))-1,m=null}return c!==i&&console.log("Warning, gif stream shorter than expected."),r}try{e.N=function(t){var e=0;if(71!==t[e++]||73!==t[e++]||70!==t[e++]||56!==t[e++]||56!=(t[e++]+1&253)||97!==t[e++])throw new Error("Invalid GIF 87a/89a header.");var i=t[e++]|t[e++]<<8,n=t[e++]|t[e++]<<8,a=t[e++],o=a>>7,s=1<<1+(7&a);t[e++],t[e++];var h=null,l=null;o&&(h=e,l=s,e+=3*s);var f=!0,u=[],c=0,d=null,p=0,m=null;for(this.width=i,this.height=n;f&&e=0))throw Error("Invalid block size");if(0===I)break;e+=I}break;case 249:if(4!==t[e++]||0!==t[e+4])throw new Error("Invalid graphics extension block.");var g=t[e++];c=t[e++]|t[e++]<<8,d=t[e++],0==(1&g)&&(d=null),p=g>>2&7,e++;break;case 254:for(;;){if(!((I=t[e++])>=0))throw Error("Invalid block size");if(0===I)break;e+=I}break;default:throw new Error("Unknown graphic control label: 0x"+t[e-1].toString(16))}break;case 44:var b=t[e++]|t[e++]<<8,_=t[e++]|t[e++]<<8,y=t[e++]|t[e++]<<8,w=t[e++]|t[e++]<<8,v=t[e++],x=v>>6&1,E=1<<1+(7&v),k=h,S=l,M=!1;v>>7&&(M=!0,k=e,S=E,e+=3*E);var A=e;for(e++;;){var I;if(!((I=t[e++])>=0))throw Error("Invalid block size");if(0===I)break;e+=I}u.push({x:b,y:_,width:y,height:w,has_local_palette:M,palette_offset:k,palette_size:S,data_offset:A,data_length:e-A,transparent_index:d,interlaced:!!x,delay:c,disposal:p});break;case 59:f=!1;break;default:throw new Error("Unknown gif block: 0x"+t[e-1].toString(16))}this.numFrames=function(){return u.length},this.loopCount=function(){return m},this.frameInfo=function(t){if(t<0||t>=u.length)throw new Error("Frame index out of range.");return u[t]},this.decodeAndBlitFrameBGRA=function(e,n){var a=this.frameInfo(e),o=a.width*a.height,s=new Uint8Array(o);r(t,a.data_offset,s,o);var h=a.palette_offset,l=a.transparent_index;null===l&&(l=256);var f=a.width,u=i-f,c=f,d=4*(a.y*i+a.x),p=4*((a.y+a.height)*i+a.x),m=d,g=4*u;!0===a.interlaced&&(g+=4*i*7);for(var b=8,_=0,y=s.length;_=p&&(g=4*u+4*i*(b-1),m=d+(f+u)*(b<<1),b>>=1)),w===l)m+=4;else{var v=t[h+3*w],x=t[h+3*w+1],E=t[h+3*w+2];n[m++]=E,n[m++]=x,n[m++]=v,n[m++]=255}--c}},this.decodeAndBlitFrameRGBA=function(e,n){var a=this.frameInfo(e),o=a.width*a.height,s=new Uint8Array(o);r(t,a.data_offset,s,o);var h=a.palette_offset,l=a.transparent_index;null===l&&(l=256);var f=a.width,u=i-f,c=f,d=4*(a.y*i+a.x),p=4*((a.y+a.height)*i+a.x),m=d,g=4*u;!0===a.interlaced&&(g+=4*i*7);for(var b=8,_=0,y=s.length;_=p&&(g=4*u+4*i*(b-1),m=d+(f+u)*(b<<1),b>>=1)),w===l)m+=4;else{var v=t[h+3*w],x=t[h+3*w+1],E=t[h+3*w+2];n[m++]=v,n[m++]=x,n[m++]=E,n[m++]=255}--c}}}}catch(t){}},2845:(t,e,r)=>{"use strict";var i={};(0,r(9761).assign)(i,r(9880),r(1380),r(1271)),t.exports=i},9880:(t,e,r)=>{"use strict";var i=r(5789),n=r(9761),a=r(7944),o=r(2950),s=r(744),h=Object.prototype.toString,l=0,f=-1,u=0,c=8;function d(t){if(!(this instanceof d))return new d(t);this.options=n.assign({level:f,method:c,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;var r=i.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(r!==l)throw new Error(o[r]);if(e.header&&i.deflateSetHeader(this.strm,e.header),e.dictionary){var p;if(p="string"==typeof e.dictionary?a.string2buf(e.dictionary):"[object ArrayBuffer]"===h.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,(r=i.deflateSetDictionary(this.strm,p))!==l)throw new Error(o[r]);this._dict_set=!0}}function p(t,e){var r=new d(e);if(r.push(t,!0),r.err)throw r.msg||o[r.err];return r.result}d.prototype.push=function(t,e){var r,o,s=this.strm,f=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?s.input=a.string2buf(t):"[object ArrayBuffer]"===h.call(t)?s.input=new Uint8Array(t):s.input=t,s.next_in=0,s.avail_in=s.input.length;do{if(0===s.avail_out&&(s.output=new n.Buf8(f),s.next_out=0,s.avail_out=f),1!==(r=i.deflate(s,o))&&r!==l)return this.onEnd(r),this.ended=!0,!1;0!==s.avail_out&&(0!==s.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(a.buf2binstring(n.shrinkBuf(s.output,s.next_out))):this.onData(n.shrinkBuf(s.output,s.next_out)))}while((s.avail_in>0||0===s.avail_out)&&1!==r);return 4===o?(r=i.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===l):2!==o||(this.onEnd(l),s.avail_out=0,!0)},d.prototype.onData=function(t){this.chunks.push(t)},d.prototype.onEnd=function(t){t===l&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Deflate=d,e.deflate=p,e.deflateRaw=function(t,e){return(e=e||{}).raw=!0,p(t,e)},e.gzip=function(t,e){return(e=e||{}).gzip=!0,p(t,e)}},1380:(t,e,r)=>{"use strict";var i=r(5020),n=r(9761),a=r(7944),o=r(1271),s=r(2950),h=r(744),l=r(7357),f=Object.prototype.toString;function u(t){if(!(this instanceof u))return new u(t);this.options=n.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new h,this.strm.avail_out=0;var r=i.inflateInit2(this.strm,e.windowBits);if(r!==o.Z_OK)throw new Error(s[r]);if(this.header=new l,i.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=a.string2buf(e.dictionary):"[object ArrayBuffer]"===f.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(r=i.inflateSetDictionary(this.strm,e.dictionary))!==o.Z_OK))throw new Error(s[r])}function c(t,e){var r=new u(e);if(r.push(t,!0),r.err)throw r.msg||s[r.err];return r.result}u.prototype.push=function(t,e){var r,s,h,l,u,c=this.strm,d=this.options.chunkSize,p=this.options.dictionary,m=!1;if(this.ended)return!1;s=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?c.input=a.binstring2buf(t):"[object ArrayBuffer]"===f.call(t)?c.input=new Uint8Array(t):c.input=t,c.next_in=0,c.avail_in=c.input.length;do{if(0===c.avail_out&&(c.output=new n.Buf8(d),c.next_out=0,c.avail_out=d),(r=i.inflate(c,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&p&&(r=i.inflateSetDictionary(this.strm,p)),r===o.Z_BUF_ERROR&&!0===m&&(r=o.Z_OK,m=!1),r!==o.Z_STREAM_END&&r!==o.Z_OK)return this.onEnd(r),this.ended=!0,!1;c.next_out&&(0!==c.avail_out&&r!==o.Z_STREAM_END&&(0!==c.avail_in||s!==o.Z_FINISH&&s!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(h=a.utf8border(c.output,c.next_out),l=c.next_out-h,u=a.buf2string(c.output,h),c.next_out=l,c.avail_out=d-l,l&&n.arraySet(c.output,c.output,h,l,0),this.onData(u)):this.onData(n.shrinkBuf(c.output,c.next_out)))),0===c.avail_in&&0===c.avail_out&&(m=!0)}while((c.avail_in>0||0===c.avail_out)&&r!==o.Z_STREAM_END);return r===o.Z_STREAM_END&&(s=o.Z_FINISH),s===o.Z_FINISH?(r=i.inflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===o.Z_OK):s!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),c.avail_out=0,!0)},u.prototype.onData=function(t){this.chunks.push(t)},u.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Inflate=u,e.inflate=c,e.inflateRaw=function(t,e){return(e=e||{}).raw=!0,c(t,e)},e.ungzip=c},9761:(t,e)=>{"use strict";var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var n in r)i(r,n)&&(t[n]=r[n])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,r,i,n){if(e.subarray&&t.subarray)t.set(e.subarray(r,r+i),n);else for(var a=0;a{"use strict";var i=r(9761),n=!0,a=!0;try{String.fromCharCode.apply(null,[0])}catch(t){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){a=!1}for(var o=new i.Buf8(256),s=0;s<256;s++)o[s]=s>=252?6:s>=248?5:s>=240?4:s>=224?3:s>=192?2:1;function h(t,e){if(e<65534&&(t.subarray&&a||!t.subarray&&n))return String.fromCharCode.apply(null,i.shrinkBuf(t,e));for(var r="",o=0;o>>6,e[o++]=128|63&r):r<65536?(e[o++]=224|r>>>12,e[o++]=128|r>>>6&63,e[o++]=128|63&r):(e[o++]=240|r>>>18,e[o++]=128|r>>>12&63,e[o++]=128|r>>>6&63,e[o++]=128|63&r);return e},e.buf2binstring=function(t){return h(t,t.length)},e.binstring2buf=function(t){for(var e=new i.Buf8(t.length),r=0,n=e.length;r4)l[i++]=65533,r+=a-1;else{for(n&=2===a?31:3===a?15:7;a>1&&r1?l[i++]=65533:n<65536?l[i++]=n:(n-=65536,l[i++]=55296|n>>10&1023,l[i++]=56320|1023&n)}return h(l,i)},e.utf8border=function(t,e){var r;for((e=e||t.length)>t.length&&(e=t.length),r=e-1;r>=0&&128==(192&t[r]);)r--;return r<0||0===r?e:r+o[t[r]]>e?r:e}},5562:t=>{"use strict";t.exports=function(t,e,r,i){for(var n=65535&t|0,a=t>>>16&65535|0,o=0;0!==r;){r-=o=r>2e3?2e3:r;do{a=a+(n=n+e[i++]|0)|0}while(--o);n%=65521,a%=65521}return n|a<<16|0}},1271:t=>{"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},4299:t=>{"use strict";var e=function(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}();t.exports=function(t,r,i,n){var a=e,o=n+i;t^=-1;for(var s=n;s>>8^a[255&(t^r[s])];return-1^t}},5789:(t,e,r)=>{"use strict";var i,n=r(9761),a=r(9564),o=r(5562),s=r(4299),h=r(2950),l=0,f=4,u=0,c=-2,d=-1,p=1,m=4,g=2,b=8,_=9,y=286,w=30,v=19,x=2*y+1,E=15,k=3,S=258,M=S+k+1,A=42,I=103,B=113,T=666,R=1,P=2,O=3,L=4;function C(t,e){return t.msg=h[e],e}function U(t){return(t<<1)-(t>4?9:0)}function z(t){for(var e=t.length;--e>=0;)t[e]=0}function D(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(n.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function N(t,e){a._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,D(t.strm)}function F(t,e){t.pending_buf[t.pending++]=e}function j(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function G(t,e){var r,i,n=t.max_chain_length,a=t.strstart,o=t.prev_length,s=t.nice_match,h=t.strstart>t.w_size-M?t.strstart-(t.w_size-M):0,l=t.window,f=t.w_mask,u=t.prev,c=t.strstart+S,d=l[a+o-1],p=l[a+o];t.prev_length>=t.good_match&&(n>>=2),s>t.lookahead&&(s=t.lookahead);do{if(l[(r=e)+o]===p&&l[r+o-1]===d&&l[r]===l[a]&&l[++r]===l[a+1]){a+=2,r++;do{}while(l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&ao){if(t.match_start=e,o=i,i>=s)break;d=l[a+o-1],p=l[a+o]}}}while((e=u[e&f])>h&&0!=--n);return o<=t.lookahead?o:t.lookahead}function H(t){var e,r,i,a,h,l,f,u,c,d,p=t.w_size;do{if(a=t.window_size-t.lookahead-t.strstart,t.strstart>=p+(p-M)){n.arraySet(t.window,t.window,p,p,0),t.match_start-=p,t.strstart-=p,t.block_start-=p,e=r=t.hash_size;do{i=t.head[--e],t.head[e]=i>=p?i-p:0}while(--r);e=r=p;do{i=t.prev[--e],t.prev[e]=i>=p?i-p:0}while(--r);a+=p}if(0===t.strm.avail_in)break;if(l=t.strm,f=t.window,u=t.strstart+t.lookahead,c=a,d=void 0,(d=l.avail_in)>c&&(d=c),r=0===d?0:(l.avail_in-=d,n.arraySet(f,l.input,l.next_in,d,u),1===l.state.wrap?l.adler=o(l.adler,f,d,u):2===l.state.wrap&&(l.adler=s(l.adler,f,d,u)),l.next_in+=d,l.total_in+=d,d),t.lookahead+=r,t.lookahead+t.insert>=k)for(h=t.strstart-t.insert,t.ins_h=t.window[h],t.ins_h=(t.ins_h<=k&&(t.ins_h=(t.ins_h<=k)if(i=a._tr_tally(t,t.strstart-t.match_start,t.match_length-k),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=k){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<=k&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=k-1)),t.prev_length>=k&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-k,i=a._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-k),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=(t.ins_h<15&&(s=2,i-=16),a<1||a>_||r!==b||i<8||i>15||e<0||e>9||o<0||o>m)return C(t,c);8===i&&(i=9);var h=new Y;return t.state=h,h.strm=t,h.wrap=s,h.gzhead=null,h.w_bits=i,h.w_size=1<t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(H(t),0===t.lookahead&&e===l)return R;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+r;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,N(t,!1),0===t.strm.avail_out))return R;if(t.strstart-t.block_start>=t.w_size-M&&(N(t,!1),0===t.strm.avail_out))return R}return t.insert=0,e===f?(N(t,!0),0===t.strm.avail_out?O:L):(t.strstart>t.block_start&&(N(t,!1),t.strm.avail_out),R)})),new Z(4,4,8,4,W),new Z(4,5,16,8,W),new Z(4,6,32,32,W),new Z(4,4,16,16,q),new Z(8,16,32,32,q),new Z(8,16,128,128,q),new Z(8,32,128,256,q),new Z(32,128,258,1024,q),new Z(32,258,258,4096,q)],e.deflateInit=function(t,e){return J(t,e,b,15,8,0)},e.deflateInit2=J,e.deflateReset=X,e.deflateResetKeep=V,e.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?c:(t.state.gzhead=e,u):c},e.deflate=function(t,e){var r,n,o,h;if(!t||!t.state||e>5||e<0)return t?C(t,c):c;if(n=t.state,!t.output||!t.input&&0!==t.avail_in||n.status===T&&e!==f)return C(t,0===t.avail_out?-5:c);if(n.strm=t,r=n.last_flush,n.last_flush=e,n.status===A)if(2===n.wrap)t.adler=0,F(n,31),F(n,139),F(n,8),n.gzhead?(F(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),F(n,255&n.gzhead.time),F(n,n.gzhead.time>>8&255),F(n,n.gzhead.time>>16&255),F(n,n.gzhead.time>>24&255),F(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),F(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(F(n,255&n.gzhead.extra.length),F(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=s(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(F(n,0),F(n,0),F(n,0),F(n,0),F(n,0),F(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),F(n,3),n.status=B);else{var d=b+(n.w_bits-8<<4)<<8;d|=(n.strategy>=2||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(d|=32),d+=31-d%31,n.status=B,j(n,d),0!==n.strstart&&(j(n,t.adler>>>16),j(n,65535&t.adler)),t.adler=1}if(69===n.status)if(n.gzhead.extra){for(o=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>o&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),D(t),o=n.pending,n.pending!==n.pending_buf_size));)F(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>o&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),D(t),o=n.pending,n.pending===n.pending_buf_size)){h=1;break}h=n.gzindexo&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),0===h&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),D(t),o=n.pending,n.pending===n.pending_buf_size)){h=1;break}h=n.gzindexo&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),0===h&&(n.status=I)}else n.status=I;if(n.status===I&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&D(t),n.pending+2<=n.pending_buf_size&&(F(n,255&t.adler),F(n,t.adler>>8&255),t.adler=0,n.status=B)):n.status=B),0!==n.pending){if(D(t),0===t.avail_out)return n.last_flush=-1,u}else if(0===t.avail_in&&U(e)<=U(r)&&e!==f)return C(t,-5);if(n.status===T&&0!==t.avail_in)return C(t,-5);if(0!==t.avail_in||0!==n.lookahead||e!==l&&n.status!==T){var p=2===n.strategy?function(t,e){for(var r;;){if(0===t.lookahead&&(H(t),0===t.lookahead)){if(e===l)return R;break}if(t.match_length=0,r=a._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(N(t,!1),0===t.strm.avail_out))return R}return t.insert=0,e===f?(N(t,!0),0===t.strm.avail_out?O:L):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?R:P}(n,e):3===n.strategy?function(t,e){for(var r,i,n,o,s=t.window;;){if(t.lookahead<=S){if(H(t),t.lookahead<=S&&e===l)return R;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=k&&t.strstart>0&&(i=s[n=t.strstart-1])===s[++n]&&i===s[++n]&&i===s[++n]){o=t.strstart+S;do{}while(i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=k?(r=a._tr_tally(t,1,t.match_length-k),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=a._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(N(t,!1),0===t.strm.avail_out))return R}return t.insert=0,e===f?(N(t,!0),0===t.strm.avail_out?O:L):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?R:P}(n,e):i[n.level].func(n,e);if(p!==O&&p!==L||(n.status=T),p===R||p===O)return 0===t.avail_out&&(n.last_flush=-1),u;if(p===P&&(1===e?a._tr_align(n):5!==e&&(a._tr_stored_block(n,0,0,!1),3===e&&(z(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),D(t),0===t.avail_out))return n.last_flush=-1,u}return e!==f?u:n.wrap<=0?1:(2===n.wrap?(F(n,255&t.adler),F(n,t.adler>>8&255),F(n,t.adler>>16&255),F(n,t.adler>>24&255),F(n,255&t.total_in),F(n,t.total_in>>8&255),F(n,t.total_in>>16&255),F(n,t.total_in>>24&255)):(j(n,t.adler>>>16),j(n,65535&t.adler)),D(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?u:1)},e.deflateEnd=function(t){var e;return t&&t.state?(e=t.state.status)!==A&&69!==e&&73!==e&&91!==e&&e!==I&&e!==B&&e!==T?C(t,c):(t.state=null,e===B?C(t,-3):u):c},e.deflateSetDictionary=function(t,e){var r,i,a,s,h,l,f,d,p=e.length;if(!t||!t.state)return c;if(2===(s=(r=t.state).wrap)||1===s&&r.status!==A||r.lookahead)return c;for(1===s&&(t.adler=o(t.adler,e,p,0)),r.wrap=0,p>=r.w_size&&(0===s&&(z(r.head),r.strstart=0,r.block_start=0,r.insert=0),d=new n.Buf8(r.w_size),n.arraySet(d,e,p-r.w_size,r.w_size,0),e=d,p=r.w_size),h=t.avail_in,l=t.next_in,f=t.input,t.avail_in=p,t.next_in=0,t.input=e,H(r);r.lookahead>=k;){i=r.strstart,a=r.lookahead-(k-1);do{r.ins_h=(r.ins_h<{"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},4980:t=>{"use strict";t.exports=function(t,e){var r,i,n,a,o,s,h,l,f,u,c,d,p,m,g,b,_,y,w,v,x,E,k,S,M;r=t.state,i=t.next_in,S=t.input,n=i+(t.avail_in-5),a=t.next_out,M=t.output,o=a-(e-t.avail_out),s=a+(t.avail_out-257),h=r.dmax,l=r.wsize,f=r.whave,u=r.wnext,c=r.window,d=r.hold,p=r.bits,m=r.lencode,g=r.distcode,b=(1<>>=w=y>>>24,p-=w,0==(w=y>>>16&255))M[a++]=65535&y;else{if(!(16&w)){if(0==(64&w)){y=m[(65535&y)+(d&(1<>>=w,p-=w),p<15&&(d+=S[i++]<>>=w=y>>>24,p-=w,!(16&(w=y>>>16&255))){if(0==(64&w)){y=g[(65535&y)+(d&(1<h){t.msg="invalid distance too far back",r.mode=30;break t}if(d>>>=w,p-=w,x>(w=a-o)){if((w=x-w)>f&&r.sane){t.msg="invalid distance too far back",r.mode=30;break t}if(E=0,k=c,0===u){if(E+=l-w,w2;)M[a++]=k[E++],M[a++]=k[E++],M[a++]=k[E++],v-=3;v&&(M[a++]=k[E++],v>1&&(M[a++]=k[E++]))}else{E=a-x;do{M[a++]=M[E++],M[a++]=M[E++],M[a++]=M[E++],v-=3}while(v>2);v&&(M[a++]=M[E++],v>1&&(M[a++]=M[E++]))}break}}break}}while(i>3,d&=(1<<(p-=v<<3))-1,t.next_in=i,t.next_out=a,t.avail_in=i{"use strict";var i=r(9761),n=r(5562),a=r(4299),o=r(4980),s=r(881),h=1,l=2,f=0,u=-2,c=1,d=12,p=30,m=852,g=592;function b(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function _(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function y(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=c,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new i.Buf32(m),e.distcode=e.distdyn=new i.Buf32(g),e.sane=1,e.back=-1,f):u}function w(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,y(t)):u}function v(t,e){var r,i;return t&&t.state?(i=t.state,e<0?(r=0,e=-e):(r=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?u:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=r,i.wbits=e,w(t))):u}function x(t,e){var r,i;return t?(i=new _,t.state=i,i.window=null,(r=v(t,e))!==f&&(t.state=null),r):u}var E,k,S=!0;function M(t){if(S){var e;for(E=new i.Buf32(512),k=new i.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(s(h,t.lens,0,288,E,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;s(l,t.lens,0,32,k,0,t.work,{bits:5}),S=!1}t.lencode=E,t.lenbits=9,t.distcode=k,t.distbits=5}function A(t,e,r,n){var a,o=t.state;return null===o.window&&(o.wsize=1<=o.wsize?(i.arraySet(o.window,e,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):((a=o.wsize-o.wnext)>n&&(a=n),i.arraySet(o.window,e,r-n,a,o.wnext),(n-=a)?(i.arraySet(o.window,e,r-n,n,0),o.wnext=n,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,r.check=a(r.check,G,2,0),x=0,E=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&x)<<8)+(x>>8))%31){t.msg="incorrect header check",r.mode=p;break}if(8!=(15&x)){t.msg="unknown compression method",r.mode=p;break}if(E-=4,z=8+(15&(x>>>=4)),0===r.wbits)r.wbits=z;else if(z>r.wbits){t.msg="invalid window size",r.mode=p;break}r.dmax=1<>8&1),512&r.flags&&(G[0]=255&x,G[1]=x>>>8&255,r.check=a(r.check,G,2,0)),x=0,E=0,r.mode=3;case 3:for(;E<32;){if(0===w)break t;w--,x+=m[_++]<>>8&255,G[2]=x>>>16&255,G[3]=x>>>24&255,r.check=a(r.check,G,4,0)),x=0,E=0,r.mode=4;case 4:for(;E<16;){if(0===w)break t;w--,x+=m[_++]<>8),512&r.flags&&(G[0]=255&x,G[1]=x>>>8&255,r.check=a(r.check,G,2,0)),x=0,E=0,r.mode=5;case 5:if(1024&r.flags){for(;E<16;){if(0===w)break t;w--,x+=m[_++]<>>8&255,r.check=a(r.check,G,2,0)),x=0,E=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&((I=r.length)>w&&(I=w),I&&(r.head&&(z=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),i.arraySet(r.head.extra,m,_,I,z)),512&r.flags&&(r.check=a(r.check,m,I,_)),w-=I,_+=I,r.length-=I),r.length))break t;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===w)break t;I=0;do{z=m[_+I++],r.head&&z&&r.length<65536&&(r.head.name+=String.fromCharCode(z))}while(z&&I>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=d;break;case 10:for(;E<32;){if(0===w)break t;w--,x+=m[_++]<>>=7&E,E-=7&E,r.mode=27;break}for(;E<3;){if(0===w)break t;w--,x+=m[_++]<>>=1)){case 0:r.mode=14;break;case 1:if(M(r),r.mode=20,6===e){x>>>=2,E-=2;break t}break;case 2:r.mode=17;break;case 3:t.msg="invalid block type",r.mode=p}x>>>=2,E-=2;break;case 14:for(x>>>=7&E,E-=7&E;E<32;){if(0===w)break t;w--,x+=m[_++]<>>16^65535)){t.msg="invalid stored block lengths",r.mode=p;break}if(r.length=65535&x,x=0,E=0,r.mode=15,6===e)break t;case 15:r.mode=16;case 16:if(I=r.length){if(I>w&&(I=w),I>v&&(I=v),0===I)break t;i.arraySet(g,m,_,I,y),w-=I,_+=I,v-=I,y+=I,r.length-=I;break}r.mode=d;break;case 17:for(;E<14;){if(0===w)break t;w--,x+=m[_++]<>>=5,E-=5,r.ndist=1+(31&x),x>>>=5,E-=5,r.ncode=4+(15&x),x>>>=4,E-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=p;break}r.have=0,r.mode=18;case 18:for(;r.have>>=3,E-=3}for(;r.have<19;)r.lens[H[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,N={bits:r.lenbits},D=s(0,r.lens,0,19,r.lencode,0,r.work,N),r.lenbits=N.bits,D){t.msg="invalid code lengths set",r.mode=p;break}r.have=0,r.mode=19;case 19:for(;r.have>>16&255,O=65535&j,!((R=j>>>24)<=E);){if(0===w)break t;w--,x+=m[_++]<>>=R,E-=R,r.lens[r.have++]=O;else{if(16===O){for(F=R+2;E>>=R,E-=R,0===r.have){t.msg="invalid bit length repeat",r.mode=p;break}z=r.lens[r.have-1],I=3+(3&x),x>>>=2,E-=2}else if(17===O){for(F=R+3;E>>=R)),x>>>=3,E-=3}else{for(F=R+7;E>>=R)),x>>>=7,E-=7}if(r.have+I>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=p;break}for(;I--;)r.lens[r.have++]=z}}if(r.mode===p)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=p;break}if(r.lenbits=9,N={bits:r.lenbits},D=s(h,r.lens,0,r.nlen,r.lencode,0,r.work,N),r.lenbits=N.bits,D){t.msg="invalid literal/lengths set",r.mode=p;break}if(r.distbits=6,r.distcode=r.distdyn,N={bits:r.distbits},D=s(l,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,N),r.distbits=N.bits,D){t.msg="invalid distances set",r.mode=p;break}if(r.mode=20,6===e)break t;case 20:r.mode=21;case 21:if(w>=6&&v>=258){t.next_out=y,t.avail_out=v,t.next_in=_,t.avail_in=w,r.hold=x,r.bits=E,o(t,S),y=t.next_out,g=t.output,v=t.avail_out,_=t.next_in,m=t.input,w=t.avail_in,x=r.hold,E=r.bits,r.mode===d&&(r.back=-1);break}for(r.back=0;P=(j=r.lencode[x&(1<>>16&255,O=65535&j,!((R=j>>>24)<=E);){if(0===w)break t;w--,x+=m[_++]<>L)])>>>16&255,O=65535&j,!(L+(R=j>>>24)<=E);){if(0===w)break t;w--,x+=m[_++]<>>=L,E-=L,r.back+=L}if(x>>>=R,E-=R,r.back+=R,r.length=O,0===P){r.mode=26;break}if(32&P){r.back=-1,r.mode=d;break}if(64&P){t.msg="invalid literal/length code",r.mode=p;break}r.extra=15&P,r.mode=22;case 22:if(r.extra){for(F=r.extra;E>>=r.extra,E-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;P=(j=r.distcode[x&(1<>>16&255,O=65535&j,!((R=j>>>24)<=E);){if(0===w)break t;w--,x+=m[_++]<>L)])>>>16&255,O=65535&j,!(L+(R=j>>>24)<=E);){if(0===w)break t;w--,x+=m[_++]<>>=L,E-=L,r.back+=L}if(x>>>=R,E-=R,r.back+=R,64&P){t.msg="invalid distance code",r.mode=p;break}r.offset=O,r.extra=15&P,r.mode=24;case 24:if(r.extra){for(F=r.extra;E>>=r.extra,E-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=p;break}r.mode=25;case 25:if(0===v)break t;if(I=S-v,r.offset>I){if((I=r.offset-I)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=p;break}I>r.wnext?(I-=r.wnext,B=r.wsize-I):B=r.wnext-I,I>r.length&&(I=r.length),T=r.window}else T=g,B=y-r.offset,I=r.length;I>v&&(I=v),v-=I,r.length-=I;do{g[y++]=T[B++]}while(--I);0===r.length&&(r.mode=21);break;case 26:if(0===v)break t;g[y++]=r.length,v--,r.mode=21;break;case 27:if(r.wrap){for(;E<32;){if(0===w)break t;w--,x|=m[_++]<{"use strict";var i=r(9761),n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],a=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],s=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(t,e,r,h,l,f,u,c){var d,p,m,g,b,_,y,w,v,x=c.bits,E=0,k=0,S=0,M=0,A=0,I=0,B=0,T=0,R=0,P=0,O=null,L=0,C=new i.Buf16(16),U=new i.Buf16(16),z=null,D=0;for(E=0;E<=15;E++)C[E]=0;for(k=0;k=1&&0===C[M];M--);if(A>M&&(A=M),0===M)return l[f++]=20971520,l[f++]=20971520,c.bits=1,0;for(S=1;S0&&(0===t||1!==M))return-1;for(U[1]=0,E=1;E<15;E++)U[E+1]=U[E]+C[E];for(k=0;k852||2===t&&R>592)return 1;for(;;){y=E-B,u[k]<_?(w=0,v=u[k]):u[k]>_?(w=z[D+u[k]],v=O[L+u[k]]):(w=96,v=0),d=1<>B)+(p-=d)]=y<<24|w<<16|v|0}while(0!==p);for(d=1<>=1;if(0!==d?(P&=d-1,P+=d):P=0,k++,0==--C[E]){if(E===M)break;E=e[r+u[k]]}if(E>A&&(P&g)!==m){for(0===B&&(B=A),b+=S,T=1<<(I=E-B);I+B852||2===t&&R>592)return 1;l[m=P&g]=A<<24|I<<16|b-f|0}}return 0!==P&&(l[b+P]=E-B<<24|64<<16|0),c.bits=A,0}},2950:t=>{"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},9564:(t,e,r)=>{"use strict";var i=r(9761);function n(t){for(var e=t.length;--e>=0;)t[e]=0}var a=0,o=256,s=o+1+29,h=30,l=19,f=2*s+1,u=15,c=16,d=256,p=16,m=17,g=18,b=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],_=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],y=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],w=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],v=new Array(2*(s+2));n(v);var x=new Array(2*h);n(x);var E=new Array(512);n(E);var k=new Array(256);n(k);var S=new Array(29);n(S);var M,A,I,B=new Array(h);function T(t,e,r,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}function R(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function P(t){return t<256?E[t]:E[256+(t>>>7)]}function O(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function L(t,e,r){t.bi_valid>c-r?(t.bi_buf|=e<>c-t.bi_valid,t.bi_valid+=r-c):(t.bi_buf|=e<>>=1,r<<=1}while(--e>0);return r>>>1}function z(t,e,r){var i,n,a=new Array(u+1),o=0;for(i=1;i<=u;i++)a[i]=o=o+r[i-1]<<1;for(n=0;n<=e;n++){var s=t[2*n+1];0!==s&&(t[2*n]=U(a[s]++,s))}}function D(t){var e;for(e=0;e8?O(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function F(t,e,r,i){var n=2*e,a=2*r;return t[n]>1;r>=1;r--)j(t,a,r);n=h;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],j(t,a,1),i=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=i,a[2*n]=a[2*r]+a[2*i],t.depth[n]=(t.depth[r]>=t.depth[i]?t.depth[r]:t.depth[i])+1,a[2*r+1]=a[2*i+1]=n,t.heap[1]=n++,j(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var r,i,n,a,o,s,h=e.dyn_tree,l=e.max_code,c=e.stat_desc.static_tree,d=e.stat_desc.has_stree,p=e.stat_desc.extra_bits,m=e.stat_desc.extra_base,g=e.stat_desc.max_length,b=0;for(a=0;a<=u;a++)t.bl_count[a]=0;for(h[2*t.heap[t.heap_max]+1]=0,r=t.heap_max+1;rg&&(a=g,b++),h[2*i+1]=a,i>l||(t.bl_count[a]++,o=0,i>=m&&(o=p[i-m]),s=h[2*i],t.opt_len+=s*(a+o),d&&(t.static_len+=s*(c[2*i+1]+o)));if(0!==b){do{for(a=g-1;0===t.bl_count[a];)a--;t.bl_count[a]--,t.bl_count[a+1]+=2,t.bl_count[g]--,b-=2}while(b>0);for(a=g;0!==a;a--)for(i=t.bl_count[a];0!==i;)(n=t.heap[--r])>l||(h[2*n+1]!==a&&(t.opt_len+=(a-h[2*n+1])*h[2*n],h[2*n+1]=a),i--)}}(t,e),z(a,l,t.bl_count)}function W(t,e,r){var i,n,a=-1,o=e[1],s=0,h=7,l=4;for(0===o&&(h=138,l=3),e[2*(r+1)+1]=65535,i=0;i<=r;i++)n=o,o=e[2*(i+1)+1],++s>=7;i0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,r=4093624447;for(e=0;e<=31;e++,r>>>=1)if(1&r&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e=3&&0===t.bl_tree[2*w[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),n=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=n&&(n=a)):n=a=r+5,r+4<=n&&-1!==e?Y(t,e,r,i):4===t.strategy||a===n?(L(t,2+(i?1:0),3),G(t,v,x)):(L(t,4+(i?1:0),3),function(t,e,r,i){var n;for(L(t,e-257,5),L(t,r-1,5),L(t,i-4,4),n=0;n>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(k[r]+o+1)]++,t.dyn_dtree[2*P(e)]++),t.last_lit===t.lit_bufsize-1},e._tr_align=function(t){L(t,2,3),C(t,d,v),function(t){16===t.bi_valid?(O(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}},744:t=>{"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},4398:t=>{function e(t,e){if(!(t=t.replace(/\t+/g," ").trim()))return null;var i=t.indexOf(" ");if(-1===i)throw new Error("no named row at line "+e);var n=t.substring(0,i);t=(t=(t=(t=t.substring(i+1)).replace(/letter=[\'\"]\S+[\'\"]/gi,"")).split("=")).map((function(t){return t.trim().match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g)}));for(var a=[],o=0;o{var e=[66,77,70];function r(t,e,r){if(r>e.length-1)return 0;var n=e.readUInt8(r++),a=e.readInt32LE(r);switch(r+=4,n){case 1:t.info=function(t,e){var r={};r.size=t.readInt16LE(e);var n=t.readUInt8(e+2);return r.smooth=n>>7&1,r.unicode=n>>6&1,r.italic=n>>5&1,r.bold=n>>4&1,n>>3&1&&(r.fixedHeight=1),r.charset=t.readUInt8(e+3)||"",r.stretchH=t.readUInt16LE(e+4),r.aa=t.readUInt8(e+6),r.padding=[t.readInt8(e+7),t.readInt8(e+8),t.readInt8(e+9),t.readInt8(e+10)],r.spacing=[t.readInt8(e+11),t.readInt8(e+12)],r.outline=t.readUInt8(e+13),r.face=function(t,e){return i(t,e).toString("utf8")}(t,e+14),r}(e,r);break;case 2:t.common=function(t,e){var r={};return r.lineHeight=t.readUInt16LE(e),r.base=t.readUInt16LE(e+2),r.scaleW=t.readUInt16LE(e+4),r.scaleH=t.readUInt16LE(e+6),r.pages=t.readUInt16LE(e+8),t.readUInt8(e+10),r.packed=0,r.alphaChnl=t.readUInt8(e+11),r.redChnl=t.readUInt8(e+12),r.greenChnl=t.readUInt8(e+13),r.blueChnl=t.readUInt8(e+14),r}(e,r);break;case 3:t.pages=function(t,e,r){for(var n=[],a=i(t,e),o=a.length+1,s=r/o,h=0;h3)throw new Error("Only supports BMFont Binary v3 (BMFont App v1.10)");for(var a={kernings:[],chars:[]},o=0;o<5;o++)n+=r(a,t,n);return a}},5947:(t,e,r)=>{var i=r(403),n=r(1596),a={scaleh:"scaleH",scalew:"scaleW",stretchh:"stretchH",lineheight:"lineHeight",alphachnl:"alphaChnl",redchnl:"redChnl",greenchnl:"greenChnl",bluechnl:"blueChnl"};function o(t){var e=function(t){for(var e=[],r=0;r element");for(var s=a.getElementsByTagName("page"),h=0;h{var e="chasrset";t.exports=function(t){for(var r in e in t&&(t.charset=t[e],delete t[e]),t)"face"!==r&&"charset"!==r&&(t[r]="padding"===r||"spacing"===r?t[r].split(",").map((function(t){return parseInt(t,10)})):parseInt(t[r],10));return t}},4655:(t,e,r)=>{var i=r(311),n=r(3243);t.exports=function(t){if(!t)return{};var e={};return n(i(t).split("\n"),(function(t){var r,n=t.indexOf(":"),a=i(t.slice(0,n)).toLowerCase(),o=i(t.slice(n+1));void 0===e[a]?e[a]=o:(r=e[a],"[object Array]"===Object.prototype.toString.call(r)?e[a].push(o):e[a]=[e[a],o])})),e}},1023:(t,e,r)=>{"use strict";var i=r(4406);function n(t){if("string"!=typeof t)throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function a(t,e){for(var r,i="",n=0,a=-1,o=0,s=0;s<=t.length;++s){if(s2){var h=i.lastIndexOf("/");if(h!==i.length-1){-1===h?(i="",n=0):n=(i=i.slice(0,h)).length-1-i.lastIndexOf("/"),a=s,o=0;continue}}else if(2===i.length||1===i.length){i="",n=0,a=s,o=0;continue}e&&(i.length>0?i+="/..":i="..",n=2)}else i.length>0?i+="/"+t.slice(a+1,s):i=t.slice(a+1,s),n=s-a-1;a=s,o=0}else 46===r&&-1!==o?++o:o=-1}return i}var o={resolve:function(){for(var t,e="",r=!1,o=arguments.length-1;o>=-1&&!r;o--){var s;o>=0?s=arguments[o]:(void 0===t&&(t=i.cwd()),s=t),n(s),0!==s.length&&(e=s+"/"+e,r=47===s.charCodeAt(0))}return e=a(e,!r),r?e.length>0?"/"+e:"/":e.length>0?e:"."},normalize:function(t){if(n(t),0===t.length)return".";var e=47===t.charCodeAt(0),r=47===t.charCodeAt(t.length-1);return 0!==(t=a(t,!e)).length||e||(t="."),t.length>0&&r&&(t+="/"),e?"/"+t:t},isAbsolute:function(t){return n(t),t.length>0&&47===t.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var t,e=0;e0&&(void 0===t?t=r:t+="/"+r)}return void 0===t?".":o.normalize(t)},relative:function(t,e){if(n(t),n(e),t===e)return"";if((t=o.resolve(t))===(e=o.resolve(e)))return"";for(var r=1;rl){if(47===e.charCodeAt(s+u))return e.slice(s+u+1);if(0===u)return e.slice(s+u)}else a>l&&(47===t.charCodeAt(r+u)?f=u:0===u&&(f=0));break}var c=t.charCodeAt(r+u);if(c!==e.charCodeAt(s+u))break;47===c&&(f=u)}var d="";for(u=r+f+1;u<=i;++u)u!==i&&47!==t.charCodeAt(u)||(0===d.length?d+="..":d+="/..");return d.length>0?d+e.slice(s+f):(s+=f,47===e.charCodeAt(s)&&++s,e.slice(s))},_makeLong:function(t){return t},dirname:function(t){if(n(t),0===t.length)return".";for(var e=t.charCodeAt(0),r=47===e,i=-1,a=!0,o=t.length-1;o>=1;--o)if(47===(e=t.charCodeAt(o))){if(!a){i=o;break}}else a=!1;return-1===i?r?"/":".":r&&1===i?"//":t.slice(0,i)},basename:function(t,e){if(void 0!==e&&"string"!=typeof e)throw new TypeError('"ext" argument must be a string');n(t);var r,i=0,a=-1,o=!0;if(void 0!==e&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";var s=e.length-1,h=-1;for(r=t.length-1;r>=0;--r){var l=t.charCodeAt(r);if(47===l){if(!o){i=r+1;break}}else-1===h&&(o=!1,h=r+1),s>=0&&(l===e.charCodeAt(s)?-1==--s&&(a=r):(s=-1,a=h))}return i===a?a=h:-1===a&&(a=t.length),t.slice(i,a)}for(r=t.length-1;r>=0;--r)if(47===t.charCodeAt(r)){if(!o){i=r+1;break}}else-1===a&&(o=!1,a=r+1);return-1===a?"":t.slice(i,a)},extname:function(t){n(t);for(var e=-1,r=0,i=-1,a=!0,o=0,s=t.length-1;s>=0;--s){var h=t.charCodeAt(s);if(47!==h)-1===i&&(a=!1,i=s+1),46===h?-1===e?e=s:1!==o&&(o=1):-1!==e&&(o=-1);else if(!a){r=s+1;break}}return-1===e||-1===i||0===o||1===o&&e===i-1&&e===r+1?"":t.slice(e,i)},format:function(t){if(null===t||"object"!=typeof t)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return function(t,e){var r=e.dir||e.root,i=e.base||(e.name||"")+(e.ext||"");return r?r===e.root?r+i:r+"/"+i:i}(0,t)},parse:function(t){n(t);var e={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return e;var r,i=t.charCodeAt(0),a=47===i;a?(e.root="/",r=1):r=0;for(var o=-1,s=0,h=-1,l=!0,f=t.length-1,u=0;f>=r;--f)if(47!==(i=t.charCodeAt(f)))-1===h&&(l=!1,h=f+1),46===i?-1===o?o=f:1!==u&&(u=1):-1!==o&&(u=-1);else if(!l){s=f+1;break}return-1===o||-1===h||0===u||1===u&&o===h-1&&o===s+1?-1!==h&&(e.base=e.name=0===s&&a?t.slice(1,h):t.slice(s,h)):(0===s&&a?(e.name=t.slice(1,o),e.base=t.slice(1,h)):(e.name=t.slice(s,o),e.base=t.slice(s,h)),e.ext=t.slice(o,h)),s>0?e.dir=t.slice(0,s-1):a&&(e.dir="/"),e},sep:"/",delimiter:":",win32:null,posix:null};o.posix=o,t.exports=o},482:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Deferred=void 0,e.Deferred=class{constructor(){this.resolve=()=>null,this.reject=()=>null,this.promise=new Promise(((t,e)=>{this.reject=e,this.resolve=t}))}}},5567:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.EndOfStreamError=e.defaultMessages=void 0,e.defaultMessages="End-Of-Stream";class r extends Error{constructor(){super(e.defaultMessages)}}e.EndOfStreamError=r},4514:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.StreamReader=e.EndOfStreamError=void 0;const i=r(5567),n=r(482);var a=r(5567);Object.defineProperty(e,"EndOfStreamError",{enumerable:!0,get:function(){return a.EndOfStreamError}}),e.StreamReader=class{constructor(t){if(this.s=t,this.deferred=null,this.endOfStream=!1,this.peekQueue=[],!t.read||!t.once)throw new Error("Expected an instance of stream.Readable");this.s.once("end",(()=>this.reject(new i.EndOfStreamError))),this.s.once("error",(t=>this.reject(t))),this.s.once("close",(()=>this.reject(new Error("Stream closed"))))}async peek(t,e,r){const i=await this.read(t,e,r);return this.peekQueue.push(t.subarray(e,e+i)),i}async read(t,e,r){if(0===r)return 0;if(0===this.peekQueue.length&&this.endOfStream)throw new i.EndOfStreamError;let n=r,a=0;for(;this.peekQueue.length>0&&n>0;){const r=this.peekQueue.pop();if(!r)throw new Error("peekData should be defined");const i=Math.min(r.length,n);t.set(r.subarray(0,i),e+a),a+=i,n-=i,i0&&!this.endOfStream;){const r=Math.min(n,1048576),i=await this.readFromStream(t,e+a,r);if(a+=i,i{this.readDeferred(i)})),i.deferred.promise}}readDeferred(t){const e=this.s.read(t.length);e?(t.buffer.set(e,t.offset),t.deferred.resolve(e.length),this.deferred=null):this.s.once("readable",(()=>{this.readDeferred(t)}))}reject(t){this.endOfStream=!0,this.deferred&&(this.deferred.reject(t),this.deferred=null)}}},4644:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.StreamReader=e.EndOfStreamError=void 0;var i=r(5567);Object.defineProperty(e,"EndOfStreamError",{enumerable:!0,get:function(){return i.EndOfStreamError}});var n=r(4514);Object.defineProperty(e,"StreamReader",{enumerable:!0,get:function(){return n.StreamReader}})},1294:t=>{"use strict";function e(t,i,n,a,o,s){for(var h,l,f,u,c=Math.max(i-1,0),d=Math.max(n-1,0),p=Math.min(i+1,a-1),m=Math.min(n+1,o-1),g=4*(n*a+i),b=0,_=0,y=0,w=0,v=0,x=c;x<=p;x++)for(var E=d;E<=m;E++)if(x!==i||E!==n){var k=r(t,t,g,4*(E*a+x),!0);if(0===k?b++:k<0?y++:k>0&&_++,b>2)return!1;s&&(kv&&(v=k,f=x,u=E))}return!s||0!==y&&0!==_&&(!e(t,h,l,a,o)&&!e(s,h,l,a,o)||!e(t,f,u,a,o)&&!e(s,f,u,a,o))}function r(t,e,r,s,h){var l=t[r+3]/255,f=e[s+3]/255,u=o(t[r+0],l),c=o(t[r+1],l),d=o(t[r+2],l),p=o(e[s+0],f),m=o(e[s+1],f),g=o(e[s+2],f),b=i(u,c,d)-i(p,m,g);if(h)return b;var _=n(u,c,d)-n(p,m,g),y=a(u,c,d)-a(p,m,g);return.5053*b*b+.299*_*_+.1957*y*y}function i(t,e,r){return.29889531*t+.58662247*e+.11448223*r}function n(t,e,r){return.59597799*t-.2741761*e-.32180189*r}function a(t,e,r){return.21147017*t-.52261711*e+.31114694*r}function o(t,e){return 255+(t-255)*e}function s(t,e,r,i,n){t[e+0]=r,t[e+1]=i,t[e+2]=n,t[e+3]=255}t.exports=function(t,n,a,h,l,f){f||(f={});for(var u=void 0===f.threshold?.1:f.threshold,c=35215*u*u,d=0,p=0;pc)f.includeAA||!e(t,m,p,h,l,n)&&!e(n,m,p,h,l,t)?(a&&s(a,g,255,0,0),d++):a&&s(a,g,255,255,0);else if(a){var b=o((void 0,void 0,void 0,void 0,w=(_=t)[(y=g)+3]/255,i(o(_[y+0],w),o(_[y+1],w),o(_[y+2],w))),.1);s(a,g,b,b,b)}}var _,y,w;return d}},9902:(t,e,r)=>{t.exports=function t(e,r,i){function n(o,s){if(!r[o]){if(!e[o]){if(a)return a(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[o]={exports:{}};e[o][0].call(l.exports,(function(t){return n(e[o][1][t]||t)}),l,l.exports,t,e,r,i)}return r[o].exports}for(var a=void 0,o=0;o=e.length)throw new Error("Ran out of data");let n=e[i];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[i+1]},function(t,e,r,i){if(i+2>=e.length)throw new Error("Ran out of data");t[r]=e[i],t[r+1]=e[i+1],t[r+2]=e[i+2],t[r+3]=255},function(t,e,r,i){if(i+3>=e.length)throw new Error("Ran out of data");t[r]=e[i],t[r+1]=e[i+1],t[r+2]=e[i+2],t[r+3]=e[i+3]}],a=[function(){},function(t,e,r,i){let n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=i},function(t,e,r){let i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[1]},function(t,e,r,i){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=i},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function o(t,e,r,i,a,o){let s=t.width,h=t.height,l=t.index;for(let t=0;t>4,r.push(u,f);break;case 2:h=3&c,l=c>>2&3,f=c>>4&3,u=c>>6&3,r.push(u,f,l,h);break;case 1:n=1&c,a=c>>1&1,o=c>>2&1,s=c>>3&1,h=c>>4&1,l=c>>5&1,f=c>>6&1,u=c>>7&1,r.push(u,f,l,h,s,o,a,n)}}return{get:function(t){for(;r.length0&&(this._paused=!1,this.emit("drain"))}.bind(this))},o.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return r=i.isBuffer(t)?t:i.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&0===this._reads.length&&(this._paused=!0),this.writable&&!this._paused},o.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(0===this._buffers.length?this._end():(this._buffers.push(null),this._process()))},o.prototype.destroySoon=o.prototype.end,o.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()},o.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))},o.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))},o.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,n=i.alloc(t.length);for(;e0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)},o.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else{if(!(this._buffered>=t.length))break;this._processRead(t)}}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}}).call(this)}).call(this,t("_process"),t("buffer").Buffer)},{_process:60,buffer:33,stream:61,util:81}],4:[function(t,e,r){"use strict";e.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}},{}],5:[function(t,e,r){"use strict";let i=[];!function(){for(let t=0;t<256;t++){let e=t;for(let t=0;t<8;t++)1&e?e=3988292384^e>>>1:e>>>=1;i[t]=e}}();let n=e.exports=function(){this._crc=-1};n.prototype.write=function(t){for(let e=0;e>>8;return!0},n.prototype.crc32=function(){return-1^this._crc},n.crc32=function(t){let e=-1;for(let r=0;r>>8;return-1^e}},{}],6:[function(t,e,r){(function(r){(function(){"use strict";let i=t("./paeth-predictor");let n={0:function(t,e,r,i,n){for(let a=0;a=a?t[e+o-a]:0,s=t[e+o]-r;i[n+o]=s}},2:function(t,e,r,i,n){for(let a=0;a0?t[e+a-r]:0,s=t[e+a]-o;i[n+a]=s}},3:function(t,e,r,i,n,a){for(let o=0;o=a?t[e+o-a]:0,h=e>0?t[e+o-r]:0,l=t[e+o]-(s+h>>1);i[n+o]=l}},4:function(t,e,r,n,a,o){for(let s=0;s=o?t[e+s-o]:0,l=e>0?t[e+s-r]:0,f=e>0&&s>=o?t[e+s-(r+o)]:0,u=t[e+s]-i(h,l,f);n[a+s]=u}}},a={0:function(t,e,r){let i=0,n=e+r;for(let r=e;r=i?t[e+a-i]:0,o=t[e+a]-r;n+=Math.abs(o)}return n},2:function(t,e,r){let i=0,n=e+r;for(let a=e;a0?t[a-r]:0,o=t[a]-n;i+=Math.abs(o)}return i},3:function(t,e,r,i){let n=0;for(let a=0;a=i?t[e+a-i]:0,s=e>0?t[e+a-r]:0,h=t[e+a]-(o+s>>1);n+=Math.abs(h)}return n},4:function(t,e,r,n){let a=0;for(let o=0;o=n?t[e+o-n]:0,h=e>0?t[e+o-r]:0,l=e>0&&o>=n?t[e+o-(r+n)]:0,f=t[e+o]-i(s,h,l);a+=Math.abs(f)}return a}};e.exports=function(t,e,i,o,s){let h;if("filterType"in o&&-1!==o.filterType){if("number"!=typeof o.filterType)throw new Error("unrecognised filter types");h=[o.filterType]}else h=[0,1,2,3,4];16===o.bitDepth&&(s*=2);let l=e*s,f=0,u=0,c=r.alloc((l+1)*i),d=h[0];for(let e=0;e1){let e=1/0;for(let r=0;rn?e[a-i]:0;e[a]=r+o}},o.prototype._unFilterType2=function(t,e,r){let i=this._lastLine;for(let n=0;nn?e[o-i]:0,l=Math.floor((h+s)/2);e[o]=r+l}},o.prototype._unFilterType4=function(t,e,r){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;sa?e[s-i]:0,f=s>a&&o?o[s-i]:0,u=n(l,h,f);e[s]=r+u}},o.prototype._reverseFilterLine=function(t){let e,i=t[0],n=this._images[this._imageIndex],a=n.byteWidth;if(0===i)e=t.slice(1,a+1);else switch(e=r.alloc(a),i){case 1:this._unFilterType1(t,e,a);break;case 2:this._unFilterType2(t,e,a);break;case 3:this._unFilterType3(t,e,a);break;case 4:this._unFilterType4(t,e,a);break;default:throw new Error("Unrecognised filter type - "+i)}this.write(e),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=e,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}}).call(this)}).call(this,t("buffer").Buffer)},{"./interlace":11,"./paeth-predictor":15,buffer:33}],10:[function(t,e,r){(function(t){(function(){"use strict";e.exports=function(e,r,i=!1){let n=r.depth,a=r.width,o=r.height,s=r.colorType,h=r.transColor,l=r.palette,f=e;return 3===s?function(t,e,r,i,n){let a=0;for(let o=0;o0&&l>0&&r.push({width:h,height:l,index:t})}return r},r.getInterlaceIterator=function(t){return function(e,r,n){let a=e%i[n].x.length,o=(e-a)/i[n].x.length*8+i[n].x[a],s=r%i[n].y.length;return 4*o+((r-s)/i[n].y.length*8+i[n].y[s])*t*4}}},{}],12:[function(t,e,r){(function(r){(function(){"use strict";let i=t("util"),n=t("stream"),a=t("./constants"),o=t("./packer"),s=e.exports=function(t){n.call(this);let e=t||{};this._packer=new o(e),this._deflate=this._packer.createDeflate(),this.readable=!0};i.inherits(s,n),s.prototype.pack=function(t,e,i,n){this.emit("data",r.from(a.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,i)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,i);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(t){this.emit("data",this._packer.packIDAT(t))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}}).call(this)}).call(this,t("buffer").Buffer)},{"./constants":4,"./packer":14,buffer:33,stream:61,util:81}],13:[function(t,e,r){(function(r){(function(){"use strict";let i=!0,n=t("zlib");n.deflateSync||(i=!1);let a=t("./constants"),o=t("./packer");e.exports=function(t,e){if(!i)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s=new o(e||{}),h=[];h.push(r.from(a.PNG_SIGNATURE)),h.push(s.packIHDR(t.width,t.height)),t.gamma&&h.push(s.packGAMA(t.gamma));let l=s.filterData(t.data,t.width,t.height),f=n.deflateSync(l,s.getDeflateOptions());if(l=null,!f||!f.length)throw new Error("bad png - invalid compressed data response");return h.push(s.packIDAT(f)),h.push(s.packIEND()),r.concat(h)}}).call(this)}).call(this,t("buffer").Buffer)},{"./constants":4,"./packer":14,buffer:33,zlib:32}],14:[function(t,e,r){(function(r){(function(){"use strict";let i=t("./constants"),n=t("./crc"),a=t("./bitpacker"),o=t("./filter-pack"),s=t("zlib"),h=e.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=null!=t.deflateLevel?t.deflateLevel:9,t.deflateStrategy=null!=t.deflateStrategy?t.deflateStrategy:3,t.inputHasAlpha=null==t.inputHasAlpha||t.inputHasAlpha,t.deflateFactory=t.deflateFactory||s.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType="number"==typeof t.colorType?t.colorType:i.COLORTYPE_COLOR_ALPHA,t.inputColorType="number"==typeof t.inputColorType?t.inputColorType:i.COLORTYPE_COLOR_ALPHA,-1===[i.COLORTYPE_GRAYSCALE,i.COLORTYPE_COLOR,i.COLORTYPE_COLOR_ALPHA,i.COLORTYPE_ALPHA].indexOf(t.colorType))throw new Error("option color type:"+t.colorType+" is not supported at present");if(-1===[i.COLORTYPE_GRAYSCALE,i.COLORTYPE_COLOR,i.COLORTYPE_COLOR_ALPHA,i.COLORTYPE_ALPHA].indexOf(t.inputColorType))throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(8!==t.bitDepth&&16!==t.bitDepth)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};h.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},h.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},h.prototype.filterData=function(t,e,r){let n=a(t,e,r,this._options),s=i.COLORTYPE_TO_BPP_MAP[this._options.colorType];return o(n,e,r,this._options,s)},h.prototype._packChunk=function(t,e){let i=e?e.length:0,a=r.alloc(i+12);return a.writeUInt32BE(i,0),a.writeUInt32BE(t,4),e&&e.copy(a,8),a.writeInt32BE(n.crc32(a.slice(4,a.length-4)),a.length-4),a},h.prototype.packGAMA=function(t){let e=r.alloc(4);return e.writeUInt32BE(Math.floor(t*i.GAMMA_DIVISION),0),this._packChunk(i.TYPE_gAMA,e)},h.prototype.packIHDR=function(t,e){let n=r.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(i.TYPE_IHDR,n)},h.prototype.packIDAT=function(t){return this._packChunk(i.TYPE_IDAT,t)},h.prototype.packIEND=function(){return this._packChunk(i.TYPE_IEND,null)}}).call(this)}).call(this,t("buffer").Buffer)},{"./bitpacker":2,"./constants":4,"./crc":5,"./filter-pack":6,buffer:33,zlib:32}],15:[function(t,e,r){"use strict";e.exports=function(t,e,r){let i=t+e-r,n=Math.abs(i-t),a=Math.abs(i-e),o=Math.abs(i-r);return n<=a&&n<=o?t:a<=o?e:r}},{}],16:[function(t,e,r){"use strict";let i=t("util"),n=t("zlib"),a=t("./chunkstream"),o=t("./filter-parse-async"),s=t("./parser"),h=t("./bitmapper"),l=t("./format-normaliser"),f=e.exports=function(t){a.call(this),this._parser=new s(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};i.inherits(f,a),f.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",(function(){}))),this.errord=!0},f.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=n.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let t=(1+(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3))*this._bitmapInfo.height,e=Math.max(t,n.Z_MIN_CHUNK);this._inflate=n.createInflate({chunkSize:e});let r=t,i=this.emit.bind(this,"error");this._inflate.on("error",(function(t){r&&i(t)})),this._filter.on("complete",this._complete.bind(this));let a=this._filter.write.bind(this._filter);this._inflate.on("data",(function(t){r&&(t.length>r&&(t=t.slice(0,r)),r-=t.length,a(t))})),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)},f.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new o(this._bitmapInfo)},f.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t},f.prototype._handlePalette=function(t){this._bitmapInfo.palette=t},f.prototype._simpleTransparency=function(){this._metaData.alpha=!0},f.prototype._headersFinished=function(){this.emit("metadata",this._metaData)},f.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))},f.prototype._complete=function(t){if(this.errord)return;let e;try{let r=h.dataToBitMap(t,this._bitmapInfo);e=l(r,this._bitmapInfo,this._options.skipRescale),r=null}catch(t){return void this._handleError(t)}this.emit("parsed",e)}},{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,util:81,zlib:32}],17:[function(t,e,r){(function(r){(function(){"use strict";let i=!0,n=t("zlib"),a=t("./sync-inflate");n.deflateSync||(i=!1);let o=t("./sync-reader"),s=t("./filter-parse-sync"),h=t("./parser"),l=t("./bitmapper"),f=t("./format-normaliser");e.exports=function(t,e){if(!i)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let u,c,d;let p=[];let m=new o(t);if(new h(e,{read:m.read.bind(m),error:function(t){u=t},metadata:function(t){c=t},gamma:function(t){d=t},palette:function(t){c.palette=t},transColor:function(t){c.transColor=t},inflateData:function(t){p.push(t)},simpleTransparency:function(){c.alpha=!0}}).start(),m.process(),u)throw u;let g,b=r.concat(p);if(p.length=0,c.interlace)g=n.inflateSync(b);else{let t=(1+(c.width*c.bpp*c.depth+7>>3))*c.height;g=a(b,{chunkSize:t,maxLength:t})}if(b=null,!g||!g.length)throw new Error("bad png - invalid inflate data response");let _=s.process(g,c);b=null;let y=l.dataToBitMap(_,c);_=null;let w=f(y,c,e.skipRescale);return c.data=w,c.gamma=d||0,c}}).call(this)}).call(this,t("buffer").Buffer)},{"./bitmapper":1,"./filter-parse-sync":8,"./format-normaliser":10,"./parser":18,"./sync-inflate":21,"./sync-reader":22,buffer:33,zlib:32}],18:[function(t,e,r){(function(r){(function(){"use strict";let i=t("./constants"),n=t("./crc"),a=e.exports=function(t,e){this._options=t,t.checkCRC=!1!==t.checkCRC,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[i.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[i.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[i.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[i.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[i.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[i.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};a.prototype.start=function(){this.read(i.PNG_SIGNATURE.length,this._parseSignature.bind(this))},a.prototype._parseSignature=function(t){let e=i.PNG_SIGNATURE;for(let r=0;rthis._palette.length)return void this.error(new Error("More transparent colors than palette size"));for(let e=0;e0?this._handleIDAT(r):this._handleChunkEnd()},a.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))},a.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}}).call(this)}).call(this,t("buffer").Buffer)},{"./constants":4,"./crc":5,buffer:33}],19:[function(t,e,r){"use strict";let i=t("./parser-sync"),n=t("./packer-sync");r.read=function(t,e){return i(t,e||{})},r.write=function(t,e){return n(t,e)}},{"./packer-sync":13,"./parser-sync":17}],20:[function(t,e,r){(function(e,i){(function(){"use strict";let n=t("util"),a=t("stream"),o=t("./parser-async"),s=t("./packer-async"),h=t("./png-sync"),l=r.PNG=function(t){a.call(this),t=t||{},this.width=0|t.width,this.height=0|t.height,this.data=this.width>0&&this.height>0?i.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new o(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new s(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};n.inherits(l,a),l.sync=h,l.prototype.pack=function(){return this.data&&this.data.length?(e.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this):(this.emit("error","No data provided"),this)},l.prototype.parse=function(t,e){if(e){let t,r;t=function(t){this.removeListener("error",r),this.data=t,e(null,this)}.bind(this),r=function(r){this.removeListener("parsed",t),e(r,null)}.bind(this),this.once("parsed",t),this.once("error",r)}return this.end(t),this},l.prototype.write=function(t){return this._parser.write(t),!0},l.prototype.end=function(t){this._parser.end(t)},l.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)},l.prototype._gamma=function(t){this.gamma=t},l.prototype._handleClose=function(){this._parser.writable||this._packer.readable||this.emit("close")},l.bitblt=function(t,e,r,i,n,a,o,s){if(i|=0,n|=0,a|=0,o|=0,s|=0,(r|=0)>t.width||i>t.height||r+n>t.width||i+a>t.height)throw new Error("bitblt reading outside image");if(o>e.width||s>e.height||o+n>e.width||s+a>e.height)throw new Error("bitblt writing outside image");for(let h=0;h=0,"have should not go down"),r>0){let t=l._buffer.slice(l._offset,l._offset+r);if(l._offset+=r,t.length>d&&(t=t.slice(0,d)),m.push(t),g+=t.length,d-=t.length,0===d)return!1}return(0===e||l._offset>=l._chunkSize)&&(c=l._chunkSize,l._offset=0,l._buffer=n.allocUnsafe(l._chunkSize)),0===e&&(p+=u-t,u=t,!0)}this.on("error",(function(t){i=t})),a(this._handle,"zlib binding closed");do{s=this._handle.writeSync(e,t,p,u,this._buffer,this._offset,c),s=s||this._writeState}while(!this._hadError&&b(s[0],s[1]));if(this._hadError)throw i;if(g>=h)throw f(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+h.toString(16)+" bytes");let _=n.concat(m,g);return f(this),_},s.inherits(l,o.Inflate),e.exports=r=u,r.Inflate=l,r.createInflate=function(t){return new l(t)},r.inflateSync=u}).call(this)}).call(this,t("_process"),t("buffer").Buffer)},{_process:60,assert:23,buffer:33,util:81,zlib:32}],22:[function(t,e,r){"use strict";let i=e.exports=function(t){this._buffer=t,this._reads=[]};i.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})},i.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(!this._buffer.length||!(this._buffer.length>=t.length||t.allowLess))break;{this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}},{}],23:[function(t,e,i){(function(r){(function(){"use strict";function i(t,e){if(t===e)return 0;for(var r=t.length,i=e.length,n=0,a=Math.min(r,i);n=0;l--)if(f[l]!==u[l])return!1;for(l=f.length-1;l>=0;l--)if(!_(t[h=f[l]],e[h],r,i))return!1;return!0}(t,e,r,o))}return r?t===e:t==e}function y(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function w(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function v(t,e,r,i){var n;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(i=r,r=null),n=function(t){var e;try{t()}catch(t){e=t}return e}(e),i=(r&&r.name?" ("+r.name+").":".")+(i?" "+i:"."),t&&!n&&g(n,r,"Missing expected exception"+i);var o="string"==typeof i,s=!t&&n&&!r;if((!t&&a.isError(n)&&o&&w(n,r)||s)&&g(n,r,"Got unwanted exception"+i),t&&n&&r&&!w(n,r)||!t&&n)throw n}u.AssertionError=function(t){this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=function(t){return p(m(t.actual),128)+" "+t.operator+" "+p(m(t.expected),128)}(this),this.generatedMessage=!0);var e=t.stackStartFunction||g;if(Error.captureStackTrace)Error.captureStackTrace(this,e);else{var r=new Error;if(r.stack){var i=r.stack,n=d(e),a=i.indexOf("\n"+n);if(a>=0){var o=i.indexOf("\n",a+1);i=i.substring(o+1)}this.stack=i}}},a.inherits(u.AssertionError,Error),u.fail=g,u.ok=b,u.equal=function(t,e,r){t!=e&&g(t,e,r,"==",u.equal)},u.notEqual=function(t,e,r){t==e&&g(t,e,r,"!=",u.notEqual)},u.deepEqual=function(t,e,r){_(t,e,!1)||g(t,e,r,"deepEqual",u.deepEqual)},u.deepStrictEqual=function(t,e,r){_(t,e,!0)||g(t,e,r,"deepStrictEqual",u.deepStrictEqual)},u.notDeepEqual=function(t,e,r){_(t,e,!1)&&g(t,e,r,"notDeepEqual",u.notDeepEqual)},u.notDeepStrictEqual=function t(e,r,i){_(e,r,!0)&&g(e,r,i,"notDeepStrictEqual",t)},u.strictEqual=function(t,e,r){t!==e&&g(t,e,r,"===",u.strictEqual)},u.notStrictEqual=function(t,e,r){t===e&&g(t,e,r,"!==",u.notStrictEqual)},u.throws=function(t,e,r){v(!0,t,e,r)},u.doesNotThrow=function(t,e,r){v(!1,t,e,r)},u.ifError=function(t){if(t)throw t};var x=Object.keys||function(t){var e=[];for(var r in t)o.call(t,r)&&e.push(r);return e}}).call(this)}).call(this,void 0!==r.g?r.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":26}],24:[function(t,e,r){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},{}],25:[function(t,e,r){e.exports=function(t){return t&&"object"==typeof t&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},{}],26:[function(t,e,i){(function(e,r){(function(){var n=/%[sdj%]/g;i.format=function(t){if(!b(t)){for(var e=[],r=0;r=a)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}})),h=i[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),p(e)?r.showHidden=e:e&&i._extend(r,e),_(r.showHidden)&&(r.showHidden=!1),_(r.depth)&&(r.depth=2),_(r.colors)&&(r.colors=!1),_(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=h),f(r,t,r.depth)}function h(t,e){var r=s.styles[e];return r?"["+s.colors[r][0]+"m"+t+"["+s.colors[r][1]+"m":t}function l(t,e){return t}function f(t,e,r){if(t.customInspect&&e&&E(e.inspect)&&e.inspect!==i.inspect&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return b(n)||(n=f(t,n,r)),n}var a=function(t,e){if(_(e))return t.stylize("undefined","undefined");if(b(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}return g(e)?t.stylize(""+e,"number"):p(e)?t.stylize(""+e,"boolean"):m(e)?t.stylize("null","null"):void 0}(t,e);if(a)return a;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),x(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return u(e);if(0===o.length){if(E(e)){var h=e.name?": "+e.name:"";return t.stylize("[Function"+h+"]","special")}if(y(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(v(e))return t.stylize(Date.prototype.toString.call(e),"date");if(x(e))return u(e)}var l,w="",k=!1,S=["{","}"];return d(e)&&(k=!0,S=["[","]"]),E(e)&&(w=" [Function"+(e.name?": "+e.name:"")+"]"),y(e)&&(w=" "+RegExp.prototype.toString.call(e)),v(e)&&(w=" "+Date.prototype.toUTCString.call(e)),x(e)&&(w=" "+u(e)),0!==o.length||k&&0!=e.length?r<0?y(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),l=k?function(t,e,r,i,n){for(var a=[],o=0,s=e.length;o60?r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}(l,w,S)):S[0]+w+S[1]}function u(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,e,r,i,n,a){var o,s,h;if((h=Object.getOwnPropertyDescriptor(e,n)||{value:e[n]}).get?s=h.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):h.set&&(s=t.stylize("[Setter]","special")),A(i,n)||(o="["+n+"]"),s||(t.seen.indexOf(h.value)<0?(s=m(r)?f(t,h.value,null):f(t,h.value,r-1)).indexOf("\n")>-1&&(s=a?s.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+s.split("\n").map((function(t){return" "+t})).join("\n")):s=t.stylize("[Circular]","special")),_(o)){if(a&&n.match(/^\d+$/))return s;(o=JSON.stringify(""+n)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+s}function d(t){return Array.isArray(t)}function p(t){return"boolean"==typeof t}function m(t){return null===t}function g(t){return"number"==typeof t}function b(t){return"string"==typeof t}function _(t){return void 0===t}function y(t){return w(t)&&"[object RegExp]"===k(t)}function w(t){return"object"==typeof t&&null!==t}function v(t){return w(t)&&"[object Date]"===k(t)}function x(t){return w(t)&&("[object Error]"===k(t)||t instanceof Error)}function E(t){return"function"==typeof t}function k(t){return Object.prototype.toString.call(t)}function S(t){return t<10?"0"+t.toString(10):t.toString(10)}i.debuglog=function(t){if(_(a)&&(a=e.env.NODE_DEBUG||""),t=t.toUpperCase(),!o[t])if(new RegExp("\\b"+t+"\\b","i").test(a)){var r=e.pid;o[t]=function(){var e=i.format.apply(i,arguments);console.error("%s %d: %s",t,r,e)}}else o[t]=function(){};return o[t]},i.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},i.isArray=d,i.isBoolean=p,i.isNull=m,i.isNullOrUndefined=function(t){return null==t},i.isNumber=g,i.isString=b,i.isSymbol=function(t){return"symbol"==typeof t},i.isUndefined=_,i.isRegExp=y,i.isObject=w,i.isDate=v,i.isError=x,i.isFunction=E,i.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},i.isBuffer=t("./support/isBuffer");var M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function A(t,e){return Object.prototype.hasOwnProperty.call(t,e)}i.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[S(t.getHours()),S(t.getMinutes()),S(t.getSeconds())].join(":"),[t.getDate(),M[t.getMonth()],e].join(" ")),i.format.apply(i,arguments))},i.inherits=t("inherits"),i._extend=function(t,e){if(!e||!w(e))return t;for(var r=Object.keys(e),i=r.length;i--;)t[r[i]]=e[r[i]];return t}}).call(this)}).call(this,t("_process"),void 0!==r.g?r.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":25,_process:60,inherits:24}],27:[function(t,e,i){(function(r){(function(){"use strict";var i=t("array-filter");e.exports=function(){return i(["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],(function(t){return"function"==typeof r[t]}))}}).call(this)}).call(this,void 0!==r.g?r.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"array-filter":28}],28:[function(t,e,r){e.exports=function(t,e,r){if(t.filter)return t.filter(e,r);if(null==t)throw new TypeError;if("function"!=typeof e)throw new TypeError;for(var n=[],a=0;a0?o-4:o;for(r=0;r>16&255,h[f++]=e>>8&255,h[f++]=255&e;return 2===s&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,h[f++]=255&e),1===s&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,h[f++]=e>>8&255,h[f++]=255&e),h},r.fromByteArray=function(t){for(var e,r=t.length,n=r%3,a=[],o=16383,s=0,h=r-n;sh?h:s+o));return 1===n?(e=t[r-1],a.push(i[e>>2]+i[e<<4&63]+"==")):2===n&&(e=(t[r-2]<<8)+t[r-1],a.push(i[e>>10]+i[e>>4&63]+i[e<<2&63]+"=")),a.join("")};for(var i=[],n=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,h=o.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,r){for(var n,a=[],o=e;o>18&63]+i[s>>12&63]+i[s>>6&63]+i[63&s]);var s;return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},{}],30:[function(t,e,r){},{}],31:[function(t,e,r){(function(e,i){(function(){"use strict";var n=t("assert"),a=t("pako/lib/zlib/zstream"),o=t("pako/lib/zlib/deflate.js"),s=t("pako/lib/zlib/inflate.js"),h=t("pako/lib/zlib/constants");for(var l in h)r[l]=h[l];r.NONE=0,r.DEFLATE=1,r.INFLATE=2,r.GZIP=3,r.GUNZIP=4,r.DEFLATERAW=5,r.INFLATERAW=6,r.UNZIP=7;function f(t){if("number"!=typeof t||tr.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=t,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}f.prototype.close=function(){this.write_in_progress?this.pending_close=!0:(this.pending_close=!1,n(this.init_done,"close before init"),n(this.mode<=r.UNZIP),this.mode===r.DEFLATE||this.mode===r.GZIP||this.mode===r.DEFLATERAW?o.deflateEnd(this.strm):this.mode!==r.INFLATE&&this.mode!==r.GUNZIP&&this.mode!==r.INFLATERAW&&this.mode!==r.UNZIP||s.inflateEnd(this.strm),this.mode=r.NONE,this.dictionary=null)},f.prototype.write=function(t,e,r,i,n,a,o){return this._write(!0,t,e,r,i,n,a,o)},f.prototype.writeSync=function(t,e,r,i,n,a,o){return this._write(!1,t,e,r,i,n,a,o)},f.prototype._write=function(t,a,o,s,h,l,f,u){if(n.equal(arguments.length,8),n(this.init_done,"write before init"),n(this.mode!==r.NONE,"already finalized"),n.equal(!1,this.write_in_progress,"write already in progress"),n.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,n.equal(!1,void 0===a,"must provide flush value"),this.write_in_progress=!0,a!==r.Z_NO_FLUSH&&a!==r.Z_PARTIAL_FLUSH&&a!==r.Z_SYNC_FLUSH&&a!==r.Z_FULL_FLUSH&&a!==r.Z_FINISH&&a!==r.Z_BLOCK)throw new Error("Invalid flush value");if(null==o&&(o=i.alloc(0),h=0,s=0),this.strm.avail_in=h,this.strm.input=o,this.strm.next_in=s,this.strm.avail_out=u,this.strm.output=l,this.strm.next_out=f,this.flush=a,!t)return this._process(),this._checkError()?this._afterSync():void 0;var c=this;return e.nextTick((function(){c._process(),c._after()})),this},f.prototype._afterSync=function(){var t=this.strm.avail_out,e=this.strm.avail_in;return this.write_in_progress=!1,[e,t]},f.prototype._process=function(){var t=null;switch(this.mode){case r.DEFLATE:case r.GZIP:case r.DEFLATERAW:this.err=o.deflate(this.strm,this.flush);break;case r.UNZIP:switch(this.strm.avail_in>0&&(t=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(null===t)break;if(31!==this.strm.input[t]){this.mode=r.INFLATE;break}if(this.gzip_id_bytes_read=1,t++,1===this.strm.avail_in)break;case 1:if(null===t)break;139===this.strm.input[t]?(this.gzip_id_bytes_read=2,this.mode=r.GUNZIP):this.mode=r.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case r.INFLATE:case r.GUNZIP:case r.INFLATERAW:for(this.err=s.inflate(this.strm,this.flush),this.err===r.Z_NEED_DICT&&this.dictionary&&(this.err=s.inflateSetDictionary(this.strm,this.dictionary),this.err===r.Z_OK?this.err=s.inflate(this.strm,this.flush):this.err===r.Z_DATA_ERROR&&(this.err=r.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===r.GUNZIP&&this.err===r.Z_STREAM_END&&0!==this.strm.next_in[0];)this.reset(),this.err=s.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}},f.prototype._checkError=function(){switch(this.err){case r.Z_OK:case r.Z_BUF_ERROR:if(0!==this.strm.avail_out&&this.flush===r.Z_FINISH)return this._error("unexpected end of file"),!1;break;case r.Z_STREAM_END:break;case r.Z_NEED_DICT:return null==this.dictionary?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0},f.prototype._after=function(){if(this._checkError()){var t=this.strm.avail_out,e=this.strm.avail_in;this.write_in_progress=!1,this.callback(e,t),this.pending_close&&this.close()}},f.prototype._error=function(t){this.strm.msg&&(t=this.strm.msg),this.onerror(t,this.err),this.write_in_progress=!1,this.pending_close&&this.close()},f.prototype.init=function(t,e,i,a,o){n(4===arguments.length||5===arguments.length,"init(windowBits, level, memLevel, strategy, [dictionary])"),n(t>=8&&t<=15,"invalid windowBits"),n(e>=-1&&e<=9,"invalid compression level"),n(i>=1&&i<=9,"invalid memlevel"),n(a===r.Z_FILTERED||a===r.Z_HUFFMAN_ONLY||a===r.Z_RLE||a===r.Z_FIXED||a===r.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(e,t,i,a,o),this._setDictionary()},f.prototype.params=function(){throw new Error("deflateParams Not supported")},f.prototype.reset=function(){this._reset(),this._setDictionary()},f.prototype._init=function(t,e,i,n,h){switch(this.level=t,this.windowBits=e,this.memLevel=i,this.strategy=n,this.flush=r.Z_NO_FLUSH,this.err=r.Z_OK,this.mode!==r.GZIP&&this.mode!==r.GUNZIP||(this.windowBits+=16),this.mode===r.UNZIP&&(this.windowBits+=32),this.mode!==r.DEFLATERAW&&this.mode!==r.INFLATERAW||(this.windowBits=-1*this.windowBits),this.strm=new a,this.mode){case r.DEFLATE:case r.GZIP:case r.DEFLATERAW:this.err=o.deflateInit2(this.strm,this.level,r.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case r.INFLATE:case r.GUNZIP:case r.INFLATERAW:case r.UNZIP:this.err=s.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==r.Z_OK&&this._error("Init error"),this.dictionary=h,this.write_in_progress=!1,this.init_done=!0},f.prototype._setDictionary=function(){if(null!=this.dictionary){switch(this.err=r.Z_OK,this.mode){case r.DEFLATE:case r.DEFLATERAW:this.err=o.deflateSetDictionary(this.strm,this.dictionary)}this.err!==r.Z_OK&&this._error("Failed to set dictionary")}},f.prototype._reset=function(){switch(this.err=r.Z_OK,this.mode){case r.DEFLATE:case r.DEFLATERAW:case r.GZIP:this.err=o.deflateReset(this.strm);break;case r.INFLATE:case r.INFLATERAW:case r.GUNZIP:this.err=s.inflateReset(this.strm)}this.err!==r.Z_OK&&this._error("Failed to reset stream")},r.Zlib=f}).call(this)}).call(this,t("_process"),t("buffer").Buffer)},{_process:60,assert:23,buffer:33,"pako/lib/zlib/constants":51,"pako/lib/zlib/deflate.js":53,"pako/lib/zlib/inflate.js":55,"pako/lib/zlib/zstream":59}],32:[function(t,e,r){(function(e){(function(){"use strict";var i=t("buffer").Buffer,n=t("stream").Transform,a=t("./binding"),o=t("util"),s=t("assert").ok,h=t("buffer").kMaxLength,l="Cannot create final Buffer. It would be larger than 0x"+h.toString(16)+" bytes";a.Z_MIN_WINDOWBITS=8,a.Z_MAX_WINDOWBITS=15,a.Z_DEFAULT_WINDOWBITS=15,a.Z_MIN_CHUNK=64,a.Z_MAX_CHUNK=1/0,a.Z_DEFAULT_CHUNK=16384,a.Z_MIN_MEMLEVEL=1,a.Z_MAX_MEMLEVEL=9,a.Z_DEFAULT_MEMLEVEL=8,a.Z_MIN_LEVEL=-1,a.Z_MAX_LEVEL=9,a.Z_DEFAULT_LEVEL=a.Z_DEFAULT_COMPRESSION;for(var f=Object.keys(a),u=0;u=h?o=new RangeError(l):e=i.concat(n,a),n=[],t.close(),r(o,e)}t.on("error",(function(e){t.removeListener("end",s),t.removeListener("readable",o),r(e)})),t.on("end",s),t.end(e),o()}function _(t,e){if("string"==typeof e&&(e=i.from(e)),!i.isBuffer(e))throw new TypeError("Not a string or buffer");var r=t._finishFlushFlag;return t._processChunk(e,r)}function y(t){if(!(this instanceof y))return new y(t);A.call(this,t,a.DEFLATE)}function w(t){if(!(this instanceof w))return new w(t);A.call(this,t,a.INFLATE)}function v(t){if(!(this instanceof v))return new v(t);A.call(this,t,a.GZIP)}function x(t){if(!(this instanceof x))return new x(t);A.call(this,t,a.GUNZIP)}function E(t){if(!(this instanceof E))return new E(t);A.call(this,t,a.DEFLATERAW)}function k(t){if(!(this instanceof k))return new k(t);A.call(this,t,a.INFLATERAW)}function S(t){if(!(this instanceof S))return new S(t);A.call(this,t,a.UNZIP)}function M(t){return t===a.Z_NO_FLUSH||t===a.Z_PARTIAL_FLUSH||t===a.Z_SYNC_FLUSH||t===a.Z_FULL_FLUSH||t===a.Z_FINISH||t===a.Z_BLOCK}function A(t,e){var o=this;if(this._opts=t=t||{},this._chunkSize=t.chunkSize||r.Z_DEFAULT_CHUNK,n.call(this,t),t.flush&&!M(t.flush))throw new Error("Invalid flush flag: "+t.flush);if(t.finishFlush&&!M(t.finishFlush))throw new Error("Invalid flush flag: "+t.finishFlush);if(this._flushFlag=t.flush||a.Z_NO_FLUSH,this._finishFlushFlag=void 0!==t.finishFlush?t.finishFlush:a.Z_FINISH,t.chunkSize&&(t.chunkSizer.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+t.chunkSize);if(t.windowBits&&(t.windowBitsr.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+t.windowBits);if(t.level&&(t.levelr.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+t.level);if(t.memLevel&&(t.memLevelr.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+t.memLevel);if(t.strategy&&t.strategy!=r.Z_FILTERED&&t.strategy!=r.Z_HUFFMAN_ONLY&&t.strategy!=r.Z_RLE&&t.strategy!=r.Z_FIXED&&t.strategy!=r.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+t.strategy);if(t.dictionary&&!i.isBuffer(t.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._handle=new a.Zlib(e);var s=this;this._hadError=!1,this._handle.onerror=function(t,e){I(s),s._hadError=!0;var i=new Error(t);i.errno=e,i.code=r.codes[e],s.emit("error",i)};var h=r.Z_DEFAULT_COMPRESSION;"number"==typeof t.level&&(h=t.level);var l=r.Z_DEFAULT_STRATEGY;"number"==typeof t.strategy&&(l=t.strategy),this._handle.init(t.windowBits||r.Z_DEFAULT_WINDOWBITS,h,t.memLevel||r.Z_DEFAULT_MEMLEVEL,l,t.dictionary),this._buffer=i.allocUnsafe(this._chunkSize),this._offset=0,this._level=h,this._strategy=l,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!o._handle},configurable:!0,enumerable:!0})}function I(t,r){r&&e.nextTick(r),t._handle&&(t._handle.close(),t._handle=null)}function B(t){t.emit("close")}Object.defineProperty(r,"codes",{enumerable:!0,value:Object.freeze(d),writable:!1}),r.Deflate=y,r.Inflate=w,r.Gzip=v,r.Gunzip=x,r.DeflateRaw=E,r.InflateRaw=k,r.Unzip=S,r.createDeflate=function(t){return new y(t)},r.createInflate=function(t){return new w(t)},r.createDeflateRaw=function(t){return new E(t)},r.createInflateRaw=function(t){return new k(t)},r.createGzip=function(t){return new v(t)},r.createGunzip=function(t){return new x(t)},r.createUnzip=function(t){return new S(t)},r.deflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new y(e),t,r)},r.deflateSync=function(t,e){return _(new y(e),t)},r.gzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new v(e),t,r)},r.gzipSync=function(t,e){return _(new v(e),t)},r.deflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new E(e),t,r)},r.deflateRawSync=function(t,e){return _(new E(e),t)},r.unzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new S(e),t,r)},r.unzipSync=function(t,e){return _(new S(e),t)},r.inflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new w(e),t,r)},r.inflateSync=function(t,e){return _(new w(e),t)},r.gunzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new x(e),t,r)},r.gunzipSync=function(t,e){return _(new x(e),t)},r.inflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new k(e),t,r)},r.inflateRawSync=function(t,e){return _(new k(e),t)},o.inherits(A,n),A.prototype.params=function(t,i,n){if(tr.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+t);if(i!=r.Z_FILTERED&&i!=r.Z_HUFFMAN_ONLY&&i!=r.Z_RLE&&i!=r.Z_FIXED&&i!=r.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+i);if(this._level!==t||this._strategy!==i){var o=this;this.flush(a.Z_SYNC_FLUSH,(function(){s(o._handle,"zlib binding closed"),o._handle.params(t,i),o._hadError||(o._level=t,o._strategy=i,n&&n())}))}else e.nextTick(n)},A.prototype.reset=function(){return s(this._handle,"zlib binding closed"),this._handle.reset()},A.prototype._flush=function(t){this._transform(i.alloc(0),"",t)},A.prototype.flush=function(t,r){var n=this,o=this._writableState;("function"==typeof t||void 0===t&&!r)&&(r=t,t=a.Z_FULL_FLUSH),o.ended?r&&e.nextTick(r):o.ending?r&&this.once("end",r):o.needDrain?r&&this.once("drain",(function(){return n.flush(t,r)})):(this._flushFlag=t,this.write(i.alloc(0),"",r))},A.prototype.close=function(t){I(this,t),e.nextTick(B,this)},A.prototype._transform=function(t,e,r){var n,o=this._writableState,s=(o.ending||o.ended)&&(!t||o.length===t.length);return null===t||i.isBuffer(t)?this._handle?(s?n=this._finishFlushFlag:(n=this._flushFlag,t.length>=o.length&&(this._flushFlag=this._opts.flush||a.Z_NO_FLUSH)),void this._processChunk(t,n,r)):r(new Error("zlib binding closed")):r(new Error("invalid input"))},A.prototype._processChunk=function(t,e,r){var n=t&&t.length,a=this._chunkSize-this._offset,o=0,f=this,u="function"==typeof r;if(!u){var c,d=[],p=0;this.on("error",(function(t){c=t})),s(this._handle,"zlib binding closed");do{var m=this._handle.writeSync(e,t,o,n,this._buffer,this._offset,a)}while(!this._hadError&&_(m[0],m[1]));if(this._hadError)throw c;if(p>=h)throw I(this),new RangeError(l);var g=i.concat(d,p);return I(this),g}s(this._handle,"zlib binding closed");var b=this._handle.write(e,t,o,n,this._buffer,this._offset,a);function _(h,l){if(this&&(this.buffer=null,this.callback=null),!f._hadError){var c=a-l;if(s(c>=0,"have should not go down"),c>0){var m=f._buffer.slice(f._offset,f._offset+c);f._offset+=c,u?f.push(m):(d.push(m),p+=m.length)}if((0===l||f._offset>=f._chunkSize)&&(a=f._chunkSize,f._offset=0,f._buffer=i.allocUnsafe(f._chunkSize)),0===l){if(o+=n-h,n=h,!u)return!0;var g=f._handle.write(e,t,o,n,f._buffer,f._offset,f._chunkSize);return g.callback=_,void(g.buffer=t)}if(!u)return!1;r()}}b.buffer=t,b.callback=_},o.inherits(y,A),o.inherits(w,A),o.inherits(v,A),o.inherits(x,A),o.inherits(E,A),o.inherits(k,A),o.inherits(S,A)}).call(this)}).call(this,t("_process"))},{"./binding":31,_process:60,assert:23,buffer:33,stream:61,util:81}],33:[function(t,e,r){(function(e){(function(){"use strict";var e=t("base64-js"),i=t("ieee754");r.Buffer=o,r.SlowBuffer=function(t){return+t!=t&&(t=0),o.alloc(+t)},r.INSPECT_MAX_BYTES=50;var n=2147483647;function a(t){if(t>n)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=o.prototype,e}function o(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return l(t)}return s(t,e,r)}function s(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!o.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=0|c(t,e),i=a(r),n=i.write(t,e);return n!==r&&(i=i.slice(0,n)),i}(t,e);if(ArrayBuffer.isView(t))return f(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(N(t,ArrayBuffer)||t&&N(t.buffer,ArrayBuffer))return function(t,e,r){if(e<0||t.byteLength=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|t}function c(t,e){if(o.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||N(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return U(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return z(t).length;default:if(n)return i?-1:U(t).length;e=(""+e).toLowerCase(),n=!0}}function d(t,e,r){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return I(this,e,r);case"utf8":case"utf-8":return k(this,e,r);case"ascii":return M(this,e,r);case"latin1":case"binary":return A(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,e,r);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}function p(t,e,r){var i=t[e];t[e]=t[r],t[r]=i}function m(t,e,r,i,n){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),F(r=+r)&&(r=n?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(n)return-1;r=t.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof e&&(e=o.from(e,i)),o.isBuffer(e))return 0===e.length?-1:g(t,e,r,i,n);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):g(t,[e],r,i,n);throw new TypeError("val must be string, number or Buffer")}function g(t,e,r,i,n){var a,o=1,s=t.length,h=e.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(t.length<2||e.length<2)return-1;o=2,s/=2,h/=2,r/=2}function l(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(n){var f=-1;for(a=r;as&&(r=s-h),a=r;a>=0;a--){for(var u=!0,c=0;cn&&(i=n):i=n;var a=e.length;i>a/2&&(i=a/2);for(var o=0;o>8,n=r%256,a.push(n),a.push(i);return a}(e,t.length-r),t,r,i)}function E(t,r,i){return 0===r&&i===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,i))}function k(t,e,r){r=Math.min(t.length,r);for(var i=[],n=e;n239?4:l>223?3:l>191?2:1;if(n+u<=r)switch(u){case 1:l<128&&(f=l);break;case 2:128==(192&(a=t[n+1]))&&(h=(31&l)<<6|63&a)>127&&(f=h);break;case 3:a=t[n+1],o=t[n+2],128==(192&a)&&128==(192&o)&&(h=(15&l)<<12|(63&a)<<6|63&o)>2047&&(h<55296||h>57343)&&(f=h);break;case 4:a=t[n+1],o=t[n+2],s=t[n+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(h=(15&l)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&h<1114112&&(f=h)}null===f?(f=65533,u=1):f>65535&&(f-=65536,i.push(f>>>10&1023|55296),f=56320|1023&f),i.push(f),n+=u}return function(t){var e=t.length;if(e<=S)return String.fromCharCode.apply(String,t);for(var r="",i=0;ie&&(t+=" ... "),""},o.prototype.compare=function(t,e,r,i,n){if(N(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),e<0||r>t.length||i<0||n>this.length)throw new RangeError("out of range index");if(i>=n&&e>=r)return 0;if(i>=n)return-1;if(e>=r)return 1;if(this===t)return 0;for(var a=(n>>>=0)-(i>>>=0),s=(r>>>=0)-(e>>>=0),h=Math.min(a,s),l=this.slice(i,n),f=t.slice(e,r),u=0;u>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-e;if((void 0===r||r>n)&&(r=n),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var a=!1;;)switch(i){case"hex":return b(this,t,e,r);case"utf8":case"utf-8":return _(this,t,e,r);case"ascii":return y(this,t,e,r);case"latin1":case"binary":return w(this,t,e,r);case"base64":return v(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),a=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var S=4096;function M(t,e,r){var i="";r=Math.min(t.length,r);for(var n=e;nn)&&(r=n);for(var a="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function R(t,e,r,i,n,a){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||et.length)throw new RangeError("Index out of range")}function P(t,e,r,i,n,a){if(r+i>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function O(t,e,r,n,a){return e=+e,r>>>=0,a||P(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function L(t,e,r,n,a){return e=+e,r>>>=0,a||P(t,0,r,8),i.write(t,e,r,n,52,8),r+8}o.prototype.slice=function(t,e){var r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||T(t,e,this.length);for(var i=this[t],n=1,a=0;++a>>=0,e>>>=0,r||T(t,e,this.length);for(var i=this[t+--e],n=1;e>0&&(n*=256);)i+=this[t+--e]*n;return i},o.prototype.readUInt8=function(t,e){return t>>>=0,e||T(t,1,this.length),this[t]},o.prototype.readUInt16LE=function(t,e){return t>>>=0,e||T(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUInt16BE=function(t,e){return t>>>=0,e||T(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUInt32LE=function(t,e){return t>>>=0,e||T(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUInt32BE=function(t,e){return t>>>=0,e||T(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||T(t,e,this.length);for(var i=this[t],n=1,a=0;++a=(n*=128)&&(i-=Math.pow(2,8*e)),i},o.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||T(t,e,this.length);for(var i=e,n=1,a=this[t+--i];i>0&&(n*=256);)a+=this[t+--i]*n;return a>=(n*=128)&&(a-=Math.pow(2,8*e)),a},o.prototype.readInt8=function(t,e){return t>>>=0,e||T(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){t>>>=0,e||T(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(t,e){t>>>=0,e||T(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(t,e){return t>>>=0,e||T(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return t>>>=0,e||T(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readFloatLE=function(t,e){return t>>>=0,e||T(t,4,this.length),i.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return t>>>=0,e||T(t,4,this.length),i.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return t>>>=0,e||T(t,8,this.length),i.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return t>>>=0,e||T(t,8,this.length),i.read(this,t,!1,52,8)},o.prototype.writeUIntLE=function(t,e,r,i){t=+t,e>>>=0,r>>>=0,i||R(this,t,e,r,Math.pow(2,8*r)-1,0);var n=1,a=0;for(this[e]=255&t;++a>>=0,r>>>=0,i||R(this,t,e,r,Math.pow(2,8*r)-1,0);var n=r-1,a=1;for(this[e+n]=255&t;--n>=0&&(a*=256);)this[e+n]=t/a&255;return e+r},o.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,1,255,0),this[e]=255&t,e+1},o.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},o.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeIntLE=function(t,e,r,i){if(t=+t,e>>>=0,!i){var n=Math.pow(2,8*r-1);R(this,t,e,r,n-1,-n)}var a=0,o=1,s=0;for(this[e]=255&t;++a>0)-s&255;return e+r},o.prototype.writeIntBE=function(t,e,r,i){if(t=+t,e>>>=0,!i){var n=Math.pow(2,8*r-1);R(this,t,e,r,n-1,-n)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)t<0&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},o.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},o.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||R(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeFloatLE=function(t,e,r){return O(this,t,e,!0,r)},o.prototype.writeFloatBE=function(t,e,r){return O(this,t,e,!1,r)},o.prototype.writeDoubleLE=function(t,e,r){return L(this,t,e,!0,r)},o.prototype.writeDoubleBE=function(t,e,r){return L(this,t,e,!1,r)},o.prototype.copy=function(t,e,r,i){if(!o.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e=0;--a)t[a+e]=this[a+r];else Uint8Array.prototype.set.call(t,this.subarray(r,i),e);return n},o.prototype.fill=function(t,e,r,i){if("string"==typeof t){if("string"==typeof e?(i=e,e=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!o.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var n=t.charCodeAt(0);("utf8"===i&&n<128||"latin1"===i)&&(t=n)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(a=e;a55295&&r<57344){if(!n){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===i){(e-=3)>-1&&a.push(239,191,189);continue}n=r;continue}if(r<56320){(e-=3)>-1&&a.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(e-=3)>-1&&a.push(239,191,189);if(n=null,r<128){if((e-=1)<0)break;a.push(r)}else if(r<2048){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function z(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(C,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function D(t,e,r,i){for(var n=0;n=e.length||n>=t.length);++n)e[n+r]=t[n];return n}function N(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function F(t){return t!=t}}).call(this)}).call(this,t("buffer").Buffer)},{"base64-js":29,buffer:33,ieee754:44}],34:[function(t,e,r){"use strict";var i,n=TypeError,a=Object.getOwnPropertyDescriptor;if(a)try{a({},"")}catch(t){a=null}var o=function(){throw new n},s=a?function(){try{return o}catch(t){try{return a(arguments,"callee").get}catch(t){return o}}}():o,h=t("has-symbols")(),l=Object.getPrototypeOf||function(t){return t.__proto__},f=i,u=i,c=i,d=i,p="undefined"==typeof Uint8Array?i:l(Uint8Array),m={"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?i:ArrayBuffer,"%ArrayBufferPrototype%":"undefined"==typeof ArrayBuffer?i:ArrayBuffer.prototype,"%ArrayIteratorPrototype%":h?l([][Symbol.iterator]()):i,"%ArrayPrototype%":Array.prototype,"%ArrayProto_entries%":Array.prototype.entries,"%ArrayProto_forEach%":Array.prototype.forEach,"%ArrayProto_keys%":Array.prototype.keys,"%ArrayProto_values%":Array.prototype.values,"%AsyncFromSyncIteratorPrototype%":i,"%AsyncFunction%":u,"%AsyncFunctionPrototype%":i,"%AsyncGenerator%":i,"%AsyncGeneratorFunction%":c,"%AsyncGeneratorPrototype%":i,"%AsyncIteratorPrototype%":d&&h&&Symbol.asyncIterator?d[Symbol.asyncIterator]():i,"%Atomics%":"undefined"==typeof Atomics?i:Atomics,"%Boolean%":Boolean,"%BooleanPrototype%":Boolean.prototype,"%DataView%":"undefined"==typeof DataView?i:DataView,"%DataViewPrototype%":"undefined"==typeof DataView?i:DataView.prototype,"%Date%":Date,"%DatePrototype%":Date.prototype,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%ErrorPrototype%":Error.prototype,"%eval%":eval,"%EvalError%":EvalError,"%EvalErrorPrototype%":EvalError.prototype,"%Float32Array%":"undefined"==typeof Float32Array?i:Float32Array,"%Float32ArrayPrototype%":"undefined"==typeof Float32Array?i:Float32Array.prototype,"%Float64Array%":"undefined"==typeof Float64Array?i:Float64Array,"%Float64ArrayPrototype%":"undefined"==typeof Float64Array?i:Float64Array.prototype,"%Function%":Function,"%FunctionPrototype%":Function.prototype,"%Generator%":i,"%GeneratorFunction%":f,"%GeneratorPrototype%":i,"%Int8Array%":"undefined"==typeof Int8Array?i:Int8Array,"%Int8ArrayPrototype%":"undefined"==typeof Int8Array?i:Int8Array.prototype,"%Int16Array%":"undefined"==typeof Int16Array?i:Int16Array,"%Int16ArrayPrototype%":"undefined"==typeof Int16Array?i:Int8Array.prototype,"%Int32Array%":"undefined"==typeof Int32Array?i:Int32Array,"%Int32ArrayPrototype%":"undefined"==typeof Int32Array?i:Int32Array.prototype,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":h?l(l([][Symbol.iterator]())):i,"%JSON%":"object"==typeof JSON?JSON:i,"%JSONParse%":"object"==typeof JSON?JSON.parse:i,"%Map%":"undefined"==typeof Map?i:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&h?l((new Map)[Symbol.iterator]()):i,"%MapPrototype%":"undefined"==typeof Map?i:Map.prototype,"%Math%":Math,"%Number%":Number,"%NumberPrototype%":Number.prototype,"%Object%":Object,"%ObjectPrototype%":Object.prototype,"%ObjProto_toString%":Object.prototype.toString,"%ObjProto_valueOf%":Object.prototype.valueOf,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?i:Promise,"%PromisePrototype%":"undefined"==typeof Promise?i:Promise.prototype,"%PromiseProto_then%":"undefined"==typeof Promise?i:Promise.prototype.then,"%Promise_all%":"undefined"==typeof Promise?i:Promise.all,"%Promise_reject%":"undefined"==typeof Promise?i:Promise.reject,"%Promise_resolve%":"undefined"==typeof Promise?i:Promise.resolve,"%Proxy%":"undefined"==typeof Proxy?i:Proxy,"%RangeError%":RangeError,"%RangeErrorPrototype%":RangeError.prototype,"%ReferenceError%":ReferenceError,"%ReferenceErrorPrototype%":ReferenceError.prototype,"%Reflect%":"undefined"==typeof Reflect?i:Reflect,"%RegExp%":RegExp,"%RegExpPrototype%":RegExp.prototype,"%Set%":"undefined"==typeof Set?i:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&h?l((new Set)[Symbol.iterator]()):i,"%SetPrototype%":"undefined"==typeof Set?i:Set.prototype,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?i:SharedArrayBuffer,"%SharedArrayBufferPrototype%":"undefined"==typeof SharedArrayBuffer?i:SharedArrayBuffer.prototype,"%String%":String,"%StringIteratorPrototype%":h?l(""[Symbol.iterator]()):i,"%StringPrototype%":String.prototype,"%Symbol%":h?Symbol:i,"%SymbolPrototype%":h?Symbol.prototype:i,"%SyntaxError%":SyntaxError,"%SyntaxErrorPrototype%":SyntaxError.prototype,"%ThrowTypeError%":s,"%TypedArray%":p,"%TypedArrayPrototype%":p?p.prototype:i,"%TypeError%":n,"%TypeErrorPrototype%":n.prototype,"%Uint8Array%":"undefined"==typeof Uint8Array?i:Uint8Array,"%Uint8ArrayPrototype%":"undefined"==typeof Uint8Array?i:Uint8Array.prototype,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?i:Uint8ClampedArray,"%Uint8ClampedArrayPrototype%":"undefined"==typeof Uint8ClampedArray?i:Uint8ClampedArray.prototype,"%Uint16Array%":"undefined"==typeof Uint16Array?i:Uint16Array,"%Uint16ArrayPrototype%":"undefined"==typeof Uint16Array?i:Uint16Array.prototype,"%Uint32Array%":"undefined"==typeof Uint32Array?i:Uint32Array,"%Uint32ArrayPrototype%":"undefined"==typeof Uint32Array?i:Uint32Array.prototype,"%URIError%":URIError,"%URIErrorPrototype%":URIError.prototype,"%WeakMap%":"undefined"==typeof WeakMap?i:WeakMap,"%WeakMapPrototype%":"undefined"==typeof WeakMap?i:WeakMap.prototype,"%WeakSet%":"undefined"==typeof WeakSet?i:WeakSet,"%WeakSetPrototype%":"undefined"==typeof WeakSet?i:WeakSet.prototype},g=t("function-bind").call(Function.call,String.prototype.replace),b=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,_=/\\(\\)?/g,y=function(t){var e=[];return g(t,b,(function(t,r,i,n){e[e.length]=i?g(n,_,"$1"):r||t})),e},w=function(t,e){if(!(t in m))throw new SyntaxError("intrinsic "+t+" does not exist!");if(void 0===m[t]&&!e)throw new n("intrinsic "+t+" exists, but is not available. Please file an issue!");return m[t]};e.exports=function(t,e){if("string"!=typeof t||0===t.length)throw new TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new TypeError('"allowMissing" argument must be a boolean');for(var r=y(t),i=w("%"+(r.length>0?r[0]:"")+"%",e),o=1;o=r.length){var s=a(i,r[o]);if(!e&&!(r[o]in i))throw new n("base intrinsic for "+t+" exists, but the property is not available.");i=s?s.get||s.value:i[r[o]]}else i=i[r[o]];return i}},{"function-bind":41,"has-symbols":42}],35:[function(t,e,r){"use strict";var i=t("function-bind"),n=t("../GetIntrinsic")("%Function%"),a=n.apply,o=n.call;e.exports=function(){return i.apply(o,arguments)},e.exports.apply=function(){return i.apply(a,arguments)}},{"../GetIntrinsic":34,"function-bind":41}],36:[function(t,e,r){"use strict";var i=t("../GetIntrinsic"),n=t("./callBind"),a=n(i("String.prototype.indexOf"));e.exports=function(t,e){var r=i(t,!!e);return"function"==typeof r&&a(t,".prototype.")?n(r):r}},{"../GetIntrinsic":34,"./callBind":35}],37:[function(t,e,r){"use strict";var i=t("../GetIntrinsic")("%Object.getOwnPropertyDescriptor%");if(i)try{i([],"length")}catch(t){i=null}e.exports=i},{"../GetIntrinsic":34}],38:[function(t,e,r){"use strict";var i,n="object"==typeof Reflect?Reflect:null,a=n&&"function"==typeof n.apply?n.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)};i=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:function(t){return Object.getOwnPropertyNames(t)};var o=Number.isNaN||function(t){return t!=t};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(t,e){return new Promise((function(r,i){function n(){void 0!==a&&t.removeListener("error",a),r([].slice.call(arguments))}var a;"error"!==e&&(a=function(r){t.removeListener(e,n),i(r)},t.once("error",a)),t.once(e,n)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var h=10;function l(t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}function f(t){return void 0===t._maxListeners?s.defaultMaxListeners:t._maxListeners}function u(t,e,r,i){var n,a,o,s;if(l(r),void 0===(a=t._events)?(a=t._events=Object.create(null),t._eventsCount=0):(void 0!==a.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),a=t._events),o=a[e]),void 0===o)o=a[e]=r,++t._eventsCount;else if("function"==typeof o?o=a[e]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=f(t))>0&&o.length>n&&!o.warned){o.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=t,h.type=e,h.count=o.length,s=h,console&&console.warn&&console.warn(s)}return t}function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},n=c.bind(i);return n.listener=r,i.wrapFn=n,n}function p(t,e,r){var i=t._events;if(void 0===i)return[];var n=i[e];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(t){for(var e=new Array(t.length),r=0;r0&&(o=e[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var h=n[t];if(void 0===h)return!1;if("function"==typeof h)a(h,this,e);else{var l=h.length,f=g(h,l);for(r=0;r=0;a--)if(r[a]===e||r[a].listener===e){o=r[a].listener,n=a;break}if(n<0)return this;0===n?r.shift():function(t,e){for(;e+1=0;i--)this.removeListener(t,e[i]);return this},s.prototype.listeners=function(t){return p(this,t,!0)},s.prototype.rawListeners=function(t){return p(this,t,!1)},s.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):m.call(t,e)},s.prototype.listenerCount=m,s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]}},{}],39:[function(t,e,r){var i=Object.prototype.hasOwnProperty,n=Object.prototype.toString;e.exports=function(t,e,r){if("[object Function]"!==n.call(e))throw new TypeError("iterator must be a function");var a=t.length;if(a===+a)for(var o=0;o>1,f=-7,u=r?n-1:0,c=r?-1:1,d=t[e+u];for(u+=c,a=d&(1<<-f)-1,d>>=-f,f+=s;f>0;a=256*a+t[e+u],u+=c,f-=8);for(o=a&(1<<-f)-1,a>>=-f,f+=i;f>0;o=256*o+t[e+u],u+=c,f-=8);if(0===a)a=1-l;else{if(a===h)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,i),a-=l}return(d?-1:1)*o*Math.pow(2,a-i)},r.write=function(t,e,r,i,n,a){var o,s,h,l=8*a-n-1,f=(1<>1,c=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:a-1,p=i?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),(e+=o+u>=1?c/h:c*Math.pow(2,1-u))*h>=2&&(o++,h/=2),o+u>=f?(s=0,o=f):o+u>=1?(s=(e*h-1)*Math.pow(2,n),o+=u):(s=e*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;t[r+d]=255&s,d+=p,s/=256,n-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,l-=8);t[r+d-p]|=128*m}},{}],45:[function(t,e,r){"function"==typeof Object.create?e.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}}},{}],46:[function(t,e,r){"use strict";var i="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,n=Object.prototype.toString,a=function(t){return!(i&&t&&"object"==typeof t&&Symbol.toStringTag in t)&&"[object Arguments]"===n.call(t)},o=function(t){return!!a(t)||null!==t&&"object"==typeof t&&"number"==typeof t.length&&t.length>=0&&"[object Array]"!==n.call(t)&&"[object Function]"===n.call(t.callee)},s=function(){return a(arguments)}();a.isLegacyArguments=o,e.exports=s?a:o},{}],47:[function(t,e,r){"use strict";var i=Object.prototype.toString,n=Function.prototype.toString,a=/^\s*(?:function)?\*/,o="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,s=Object.getPrototypeOf,h=function(){if(!o)return!1;try{return Function("return function*() {}")()}catch(t){}}(),l=h?s(h):{};e.exports=function(t){return"function"==typeof t&&(!!a.test(n.call(t))||(o?s(t)===l:"[object GeneratorFunction]"===i.call(t)))}},{}],48:[function(t,e,i){(function(r){(function(){"use strict";var i=t("foreach"),n=t("available-typed-arrays"),a=t("es-abstract/helpers/callBound"),o=a("Object.prototype.toString"),s=t("has-symbols")()&&"symbol"==typeof Symbol.toStringTag,h=n(),l=a("Array.prototype.indexOf",!0)||function(t,e){for(var r=0;r-1}return!!c&&function(t){var e=!1;return i(u,(function(r,i){if(!e)try{e=r.call(t)===i}catch(t){}})),e}(t)}}).call(this)}).call(this,void 0!==r.g?r.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"available-typed-arrays":27,"es-abstract/helpers/callBound":36,"es-abstract/helpers/getOwnPropertyDescriptor":37,foreach:39,"has-symbols":42}],49:[function(t,e,r){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}r.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var i in r)n(r,i)&&(t[i]=r[i])}}return t},r.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var a={arraySet:function(t,e,r,i,n){if(e.subarray&&t.subarray)t.set(e.subarray(r,r+i),n);else for(var a=0;a>>16&65535|0,o=0;0!==r;){r-=o=r>2e3?2e3:r;do{a=a+(n=n+e[i++]|0)|0}while(--o);n%=65521,a%=65521}return n|a<<16|0}},{}],51:[function(t,e,r){"use strict";e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],52:[function(t,e,r){"use strict";var i=function(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}();e.exports=function(t,e,r,n){var a=i,o=n+r;t^=-1;for(var s=n;s>>8^a[255&(t^e[s])];return-1^t}},{}],53:[function(t,e,r){"use strict";var i,n=t("../utils/common"),a=t("./trees"),o=t("./adler32"),s=t("./crc32"),h=t("./messages"),l=0,f=1,u=3,c=4,d=5,p=0,m=1,g=-2,b=-3,_=-5,y=-1,w=1,v=2,x=3,E=4,k=0,S=2,M=8,A=9,I=15,B=8,T=286,R=30,P=19,O=2*T+1,L=15,C=3,U=258,z=U+C+1,D=32,N=42,F=69,j=73,G=91,H=103,W=113,q=666,Z=1,Y=2,V=3,X=4,J=3;function Q(t,e){return t.msg=h[e],e}function K(t){return(t<<1)-(t>4?9:0)}function $(t){for(var e=t.length;--e>=0;)t[e]=0}function tt(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(n.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function et(t,e){a._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,tt(t.strm)}function rt(t,e){t.pending_buf[t.pending++]=e}function it(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function nt(t,e){var r,i,n=t.max_chain_length,a=t.strstart,o=t.prev_length,s=t.nice_match,h=t.strstart>t.w_size-z?t.strstart-(t.w_size-z):0,l=t.window,f=t.w_mask,u=t.prev,c=t.strstart+U,d=l[a+o-1],p=l[a+o];t.prev_length>=t.good_match&&(n>>=2),s>t.lookahead&&(s=t.lookahead);do{if(l[(r=e)+o]===p&&l[r+o-1]===d&&l[r]===l[a]&&l[++r]===l[a+1]){a+=2,r++;do{}while(l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&l[++a]===l[++r]&&ao){if(t.match_start=e,o=i,i>=s)break;d=l[a+o-1],p=l[a+o]}}}while((e=u[e&f])>h&&0!=--n);return o<=t.lookahead?o:t.lookahead}function at(t){var e,r,i,a,h,l,f,u,c,d,p=t.w_size;do{if(a=t.window_size-t.lookahead-t.strstart,t.strstart>=p+(p-z)){n.arraySet(t.window,t.window,p,p,0),t.match_start-=p,t.strstart-=p,t.block_start-=p,e=r=t.hash_size;do{i=t.head[--e],t.head[e]=i>=p?i-p:0}while(--r);e=r=p;do{i=t.prev[--e],t.prev[e]=i>=p?i-p:0}while(--r);a+=p}if(0===t.strm.avail_in)break;if(l=t.strm,f=t.window,u=t.strstart+t.lookahead,c=a,d=void 0,(d=l.avail_in)>c&&(d=c),r=0===d?0:(l.avail_in-=d,n.arraySet(f,l.input,l.next_in,d,u),1===l.state.wrap?l.adler=o(l.adler,f,d,u):2===l.state.wrap&&(l.adler=s(l.adler,f,d,u)),l.next_in+=d,l.total_in+=d,d),t.lookahead+=r,t.lookahead+t.insert>=C)for(h=t.strstart-t.insert,t.ins_h=t.window[h],t.ins_h=(t.ins_h<=C&&(t.ins_h=(t.ins_h<=C)if(i=a._tr_tally(t,t.strstart-t.match_start,t.match_length-C),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=C){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<=C&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=C-1)),t.prev_length>=C&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-C,i=a._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-C),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=(t.ins_h<15&&(s=2,i-=16),a<1||a>A||r!==M||i<8||i>15||e<0||e>9||o<0||o>E)return Q(t,g);8===i&&(i=9);var h=new lt;return t.state=h,h.strm=t,h.wrap=s,h.gzhead=null,h.w_bits=i,h.w_size=1<t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(at(t),0===t.lookahead&&e===l)return Z;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+r;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,et(t,!1),0===t.strm.avail_out))return Z;if(t.strstart-t.block_start>=t.w_size-z&&(et(t,!1),0===t.strm.avail_out))return Z}return t.insert=0,e===c?(et(t,!0),0===t.strm.avail_out?V:X):(t.strstart>t.block_start&&(et(t,!1),t.strm.avail_out),Z)})),new ht(4,4,8,4,ot),new ht(4,5,16,8,ot),new ht(4,6,32,32,ot),new ht(4,4,16,16,st),new ht(8,16,32,32,st),new ht(8,16,128,128,st),new ht(8,32,128,256,st),new ht(32,128,258,1024,st),new ht(32,258,258,4096,st)],r.deflateInit=function(t,e){return ct(t,e,M,I,B,k)},r.deflateInit2=ct,r.deflateReset=ut,r.deflateResetKeep=ft,r.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?g:(t.state.gzhead=e,p):g},r.deflate=function(t,e){var r,n,o,h;if(!t||!t.state||e>d||e<0)return t?Q(t,g):g;if(n=t.state,!t.output||!t.input&&0!==t.avail_in||n.status===q&&e!==c)return Q(t,0===t.avail_out?_:g);if(n.strm=t,r=n.last_flush,n.last_flush=e,n.status===N)if(2===n.wrap)t.adler=0,rt(n,31),rt(n,139),rt(n,8),n.gzhead?(rt(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),rt(n,255&n.gzhead.time),rt(n,n.gzhead.time>>8&255),rt(n,n.gzhead.time>>16&255),rt(n,n.gzhead.time>>24&255),rt(n,9===n.level?2:n.strategy>=v||n.level<2?4:0),rt(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(rt(n,255&n.gzhead.extra.length),rt(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=s(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=F):(rt(n,0),rt(n,0),rt(n,0),rt(n,0),rt(n,0),rt(n,9===n.level?2:n.strategy>=v||n.level<2?4:0),rt(n,J),n.status=W);else{var b=M+(n.w_bits-8<<4)<<8;b|=(n.strategy>=v||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(b|=D),b+=31-b%31,n.status=W,it(n,b),0!==n.strstart&&(it(n,t.adler>>>16),it(n,65535&t.adler)),t.adler=1}if(n.status===F)if(n.gzhead.extra){for(o=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>o&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),tt(t),o=n.pending,n.pending!==n.pending_buf_size));)rt(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>o&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=j)}else n.status=j;if(n.status===j)if(n.gzhead.name){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),tt(t),o=n.pending,n.pending===n.pending_buf_size)){h=1;break}h=n.gzindexo&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),0===h&&(n.gzindex=0,n.status=G)}else n.status=G;if(n.status===G)if(n.gzhead.comment){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),tt(t),o=n.pending,n.pending===n.pending_buf_size)){h=1;break}h=n.gzindexo&&(t.adler=s(t.adler,n.pending_buf,n.pending-o,o)),0===h&&(n.status=H)}else n.status=H;if(n.status===H&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&tt(t),n.pending+2<=n.pending_buf_size&&(rt(n,255&t.adler),rt(n,t.adler>>8&255),t.adler=0,n.status=W)):n.status=W),0!==n.pending){if(tt(t),0===t.avail_out)return n.last_flush=-1,p}else if(0===t.avail_in&&K(e)<=K(r)&&e!==c)return Q(t,_);if(n.status===q&&0!==t.avail_in)return Q(t,_);if(0!==t.avail_in||0!==n.lookahead||e!==l&&n.status!==q){var y=n.strategy===v?function(t,e){for(var r;;){if(0===t.lookahead&&(at(t),0===t.lookahead)){if(e===l)return Z;break}if(t.match_length=0,r=a._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(et(t,!1),0===t.strm.avail_out))return Z}return t.insert=0,e===c?(et(t,!0),0===t.strm.avail_out?V:X):t.last_lit&&(et(t,!1),0===t.strm.avail_out)?Z:Y}(n,e):n.strategy===x?function(t,e){for(var r,i,n,o,s=t.window;;){if(t.lookahead<=U){if(at(t),t.lookahead<=U&&e===l)return Z;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=C&&t.strstart>0&&(i=s[n=t.strstart-1])===s[++n]&&i===s[++n]&&i===s[++n]){o=t.strstart+U;do{}while(i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=C?(r=a._tr_tally(t,1,t.match_length-C),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=a._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(et(t,!1),0===t.strm.avail_out))return Z}return t.insert=0,e===c?(et(t,!0),0===t.strm.avail_out?V:X):t.last_lit&&(et(t,!1),0===t.strm.avail_out)?Z:Y}(n,e):i[n.level].func(n,e);if(y!==V&&y!==X||(n.status=q),y===Z||y===V)return 0===t.avail_out&&(n.last_flush=-1),p;if(y===Y&&(e===f?a._tr_align(n):e!==d&&(a._tr_stored_block(n,0,0,!1),e===u&&($(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),tt(t),0===t.avail_out))return n.last_flush=-1,p}return e!==c?p:n.wrap<=0?m:(2===n.wrap?(rt(n,255&t.adler),rt(n,t.adler>>8&255),rt(n,t.adler>>16&255),rt(n,t.adler>>24&255),rt(n,255&t.total_in),rt(n,t.total_in>>8&255),rt(n,t.total_in>>16&255),rt(n,t.total_in>>24&255)):(it(n,t.adler>>>16),it(n,65535&t.adler)),tt(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?p:m)},r.deflateEnd=function(t){var e;return t&&t.state?(e=t.state.status)!==N&&e!==F&&e!==j&&e!==G&&e!==H&&e!==W&&e!==q?Q(t,g):(t.state=null,e===W?Q(t,b):p):g},r.deflateSetDictionary=function(t,e){var r,i,a,s,h,l,f,u,c=e.length;if(!t||!t.state)return g;if(2===(s=(r=t.state).wrap)||1===s&&r.status!==N||r.lookahead)return g;for(1===s&&(t.adler=o(t.adler,e,c,0)),r.wrap=0,c>=r.w_size&&(0===s&&($(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new n.Buf8(r.w_size),n.arraySet(u,e,c-r.w_size,r.w_size,0),e=u,c=r.w_size),h=t.avail_in,l=t.next_in,f=t.input,t.avail_in=c,t.next_in=0,t.input=e,at(r);r.lookahead>=C;){i=r.strstart,a=r.lookahead-(C-1);do{r.ins_h=(r.ins_h<>>=w=y>>>24,p-=w,0==(w=y>>>16&255))M[a++]=65535&y;else{if(!(16&w)){if(0==(64&w)){y=m[(65535&y)+(d&(1<>>=w,p-=w),p<15&&(d+=S[i++]<>>=w=y>>>24,p-=w,!(16&(w=y>>>16&255))){if(0==(64&w)){y=g[(65535&y)+(d&(1<h){t.msg="invalid distance too far back",r.mode=30;break t}if(d>>>=w,p-=w,x>(w=a-o)){if((w=x-w)>f&&r.sane){t.msg="invalid distance too far back",r.mode=30;break t}if(E=0,k=c,0===u){if(E+=l-w,w2;)M[a++]=k[E++],M[a++]=k[E++],M[a++]=k[E++],v-=3;v&&(M[a++]=k[E++],v>1&&(M[a++]=k[E++]))}else{E=a-x;do{M[a++]=M[E++],M[a++]=M[E++],M[a++]=M[E++],v-=3}while(v>2);v&&(M[a++]=M[E++],v>1&&(M[a++]=M[E++]))}break}}break}}while(i>3,d&=(1<<(p-=v<<3))-1,t.next_in=i,t.next_out=a,t.avail_in=i>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function it(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function nt(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=x,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new i.Buf32($),e.distcode=e.distdyn=new i.Buf32(tt),e.sane=1,e.back=-1,p):b}function at(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,nt(t)):b}function ot(t,e){var r,i;return t&&t.state?(i=t.state,e<0?(r=0,e=-e):(r=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?b:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=r,i.wbits=e,at(t))):b}function st(t,e){var r,i;return t?(i=new it,t.state=i,i.window=null,(r=ot(t,e))!==p&&(t.state=null),r):b}var ht,lt,ft=!0;function ut(t){if(ft){var e;for(ht=new i.Buf32(512),lt=new i.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(s(l,t.lens,0,288,ht,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;s(f,t.lens,0,32,lt,0,t.work,{bits:5}),ft=!1}t.lencode=ht,t.lenbits=9,t.distcode=lt,t.distbits=5}function ct(t,e,r,n){var a,o=t.state;return null===o.window&&(o.wsize=1<=o.wsize?(i.arraySet(o.window,e,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):((a=o.wsize-o.wnext)>n&&(a=n),i.arraySet(o.window,e,r-n,a,o.wnext),(n-=a)?(i.arraySet(o.window,e,r-n,n,0),o.wnext=n,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,r.check=a(r.check,Mt,2,0),ot=0,st=0,r.mode=E;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&ot)<<8)+(ot>>8))%31){t.msg="incorrect header check",r.mode=Q;break}if((15&ot)!==v){t.msg="unknown compression method",r.mode=Q;break}if(st-=4,vt=8+(15&(ot>>>=4)),0===r.wbits)r.wbits=vt;else if(vt>r.wbits){t.msg="invalid window size",r.mode=Q;break}r.dmax=1<>8&1),512&r.flags&&(Mt[0]=255&ot,Mt[1]=ot>>>8&255,r.check=a(r.check,Mt,2,0)),ot=0,st=0,r.mode=k;case k:for(;st<32;){if(0===nt)break t;nt--,ot+=$[et++]<>>8&255,Mt[2]=ot>>>16&255,Mt[3]=ot>>>24&255,r.check=a(r.check,Mt,4,0)),ot=0,st=0,r.mode=S;case S:for(;st<16;){if(0===nt)break t;nt--,ot+=$[et++]<>8),512&r.flags&&(Mt[0]=255&ot,Mt[1]=ot>>>8&255,r.check=a(r.check,Mt,2,0)),ot=0,st=0,r.mode=M;case M:if(1024&r.flags){for(;st<16;){if(0===nt)break t;nt--,ot+=$[et++]<>>8&255,r.check=a(r.check,Mt,2,0)),ot=0,st=0}else r.head&&(r.head.extra=null);r.mode=A;case A:if(1024&r.flags&&((ft=r.length)>nt&&(ft=nt),ft&&(r.head&&(vt=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),i.arraySet(r.head.extra,$,et,ft,vt)),512&r.flags&&(r.check=a(r.check,$,ft,et)),nt-=ft,et+=ft,r.length-=ft),r.length))break t;r.length=0,r.mode=I;case I:if(2048&r.flags){if(0===nt)break t;ft=0;do{vt=$[et+ft++],r.head&&vt&&r.length<65536&&(r.head.name+=String.fromCharCode(vt))}while(vt&&ft>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=O;break;case R:for(;st<32;){if(0===nt)break t;nt--,ot+=$[et++]<>>=7&st,st-=7&st,r.mode=V;break}for(;st<3;){if(0===nt)break t;nt--,ot+=$[et++]<>>=1)){case 0:r.mode=C;break;case 1:if(ut(r),r.mode=j,e===d){ot>>>=2,st-=2;break t}break;case 2:r.mode=D;break;case 3:t.msg="invalid block type",r.mode=Q}ot>>>=2,st-=2;break;case C:for(ot>>>=7&st,st-=7&st;st<32;){if(0===nt)break t;nt--,ot+=$[et++]<>>16^65535)){t.msg="invalid stored block lengths",r.mode=Q;break}if(r.length=65535&ot,ot=0,st=0,r.mode=U,e===d)break t;case U:r.mode=z;case z:if(ft=r.length){if(ft>nt&&(ft=nt),ft>at&&(ft=at),0===ft)break t;i.arraySet(tt,$,et,ft,it),nt-=ft,et+=ft,at-=ft,it+=ft,r.length-=ft;break}r.mode=O;break;case D:for(;st<14;){if(0===nt)break t;nt--,ot+=$[et++]<>>=5,st-=5,r.ndist=1+(31&ot),ot>>>=5,st-=5,r.ncode=4+(15&ot),ot>>>=4,st-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=Q;break}r.have=0,r.mode=N;case N:for(;r.have>>=3,st-=3}for(;r.have<19;)r.lens[At[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,Et={bits:r.lenbits},xt=s(h,r.lens,0,19,r.lencode,0,r.work,Et),r.lenbits=Et.bits,xt){t.msg="invalid code lengths set",r.mode=Q;break}r.have=0,r.mode=F;case F:for(;r.have>>16&255,bt=65535&St,!((mt=St>>>24)<=st);){if(0===nt)break t;nt--,ot+=$[et++]<>>=mt,st-=mt,r.lens[r.have++]=bt;else{if(16===bt){for(kt=mt+2;st>>=mt,st-=mt,0===r.have){t.msg="invalid bit length repeat",r.mode=Q;break}vt=r.lens[r.have-1],ft=3+(3&ot),ot>>>=2,st-=2}else if(17===bt){for(kt=mt+3;st>>=mt)),ot>>>=3,st-=3}else{for(kt=mt+7;st>>=mt)),ot>>>=7,st-=7}if(r.have+ft>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=Q;break}for(;ft--;)r.lens[r.have++]=vt}}if(r.mode===Q)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=Q;break}if(r.lenbits=9,Et={bits:r.lenbits},xt=s(l,r.lens,0,r.nlen,r.lencode,0,r.work,Et),r.lenbits=Et.bits,xt){t.msg="invalid literal/lengths set",r.mode=Q;break}if(r.distbits=6,r.distcode=r.distdyn,Et={bits:r.distbits},xt=s(f,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,Et),r.distbits=Et.bits,xt){t.msg="invalid distances set",r.mode=Q;break}if(r.mode=j,e===d)break t;case j:r.mode=G;case G:if(nt>=6&&at>=258){t.next_out=it,t.avail_out=at,t.next_in=et,t.avail_in=nt,r.hold=ot,r.bits=st,o(t,lt),it=t.next_out,tt=t.output,at=t.avail_out,et=t.next_in,$=t.input,nt=t.avail_in,ot=r.hold,st=r.bits,r.mode===O&&(r.back=-1);break}for(r.back=0;gt=(St=r.lencode[ot&(1<>>16&255,bt=65535&St,!((mt=St>>>24)<=st);){if(0===nt)break t;nt--,ot+=$[et++]<>_t)])>>>16&255,bt=65535&St,!(_t+(mt=St>>>24)<=st);){if(0===nt)break t;nt--,ot+=$[et++]<>>=_t,st-=_t,r.back+=_t}if(ot>>>=mt,st-=mt,r.back+=mt,r.length=bt,0===gt){r.mode=Y;break}if(32>){r.back=-1,r.mode=O;break}if(64>){t.msg="invalid literal/length code",r.mode=Q;break}r.extra=15>,r.mode=H;case H:if(r.extra){for(kt=r.extra;st>>=r.extra,st-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=W;case W:for(;gt=(St=r.distcode[ot&(1<>>16&255,bt=65535&St,!((mt=St>>>24)<=st);){if(0===nt)break t;nt--,ot+=$[et++]<>_t)])>>>16&255,bt=65535&St,!(_t+(mt=St>>>24)<=st);){if(0===nt)break t;nt--,ot+=$[et++]<>>=_t,st-=_t,r.back+=_t}if(ot>>>=mt,st-=mt,r.back+=mt,64>){t.msg="invalid distance code",r.mode=Q;break}r.offset=bt,r.extra=15>,r.mode=q;case q:if(r.extra){for(kt=r.extra;st>>=r.extra,st-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=Q;break}r.mode=Z;case Z:if(0===at)break t;if(ft=lt-at,r.offset>ft){if((ft=r.offset-ft)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=Q;break}ft>r.wnext?(ft-=r.wnext,dt=r.wsize-ft):dt=r.wnext-ft,ft>r.length&&(ft=r.length),pt=r.window}else pt=tt,dt=it-r.offset,ft=r.length;ft>at&&(ft=at),at-=ft,r.length-=ft;do{tt[it++]=pt[dt++]}while(--ft);0===r.length&&(r.mode=G);break;case Y:if(0===at)break t;tt[it++]=r.length,at--,r.mode=G;break;case V:if(r.wrap){for(;st<32;){if(0===nt)break t;nt--,ot|=$[et++]<=1&&0===U[A];A--);if(I>A&&(I=A),0===A)return f[u++]=20971520,f[u++]=20971520,d.bits=1,0;for(M=1;M0&&(0===t||1!==A))return-1;for(z[1]=0,k=1;k852||2===t&&P>592)return 1;for(;;){w=k-T,c[S]y?(v=D[N+c[S]],x=L[C+c[S]]):(v=96,x=0),p=1<>T)+(m-=p)]=w<<24|v<<16|x|0}while(0!==m);for(p=1<>=1;if(0!==p?(O&=p-1,O+=p):O=0,S++,0==--U[k]){if(k===A)break;k=e[r+c[S]]}if(k>I&&(O&b)!==g){for(0===T&&(T=I),_+=M,R=1<<(B=k-T);B+T852||2===t&&P>592)return 1;f[g=O&b]=I<<24|B<<16|_-u|0}}return 0!==O&&(f[_+O]=k-T<<24|64<<16|0),d.bits=I,0}},{"../utils/common":49}],57:[function(t,e,r){"use strict";e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],58:[function(t,e,r){"use strict";var i=t("../utils/common"),n=4,a=0,o=1,s=2;function h(t){for(var e=t.length;--e>=0;)t[e]=0}var l=0,f=1,u=2,c=29,d=256,p=d+1+c,m=30,g=19,b=2*p+1,_=15,y=16,w=7,v=256,x=16,E=17,k=18,S=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],M=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],A=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],I=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],B=new Array(2*(p+2));h(B);var T=new Array(2*m);h(T);var R=new Array(512);h(R);var P=new Array(256);h(P);var O=new Array(c);h(O);var L,C,U,z=new Array(m);function D(t,e,r,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}function N(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function F(t){return t<256?R[t]:R[256+(t>>>7)]}function j(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function G(t,e,r){t.bi_valid>y-r?(t.bi_buf|=e<>y-t.bi_valid,t.bi_valid+=r-y):(t.bi_buf|=e<>>=1,r<<=1}while(--e>0);return r>>>1}function q(t,e,r){var i,n,a=new Array(_+1),o=0;for(i=1;i<=_;i++)a[i]=o=o+r[i-1]<<1;for(n=0;n<=e;n++){var s=t[2*n+1];0!==s&&(t[2*n]=W(a[s]++,s))}}function Z(t){var e;for(e=0;e8?j(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function V(t,e,r,i){var n=2*e,a=2*r;return t[n]>1;r>=1;r--)X(t,a,r);n=h;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],X(t,a,1),i=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=i,a[2*n]=a[2*r]+a[2*i],t.depth[n]=(t.depth[r]>=t.depth[i]?t.depth[r]:t.depth[i])+1,a[2*r+1]=a[2*i+1]=n,t.heap[1]=n++,X(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var r,i,n,a,o,s,h=e.dyn_tree,l=e.max_code,f=e.stat_desc.static_tree,u=e.stat_desc.has_stree,c=e.stat_desc.extra_bits,d=e.stat_desc.extra_base,p=e.stat_desc.max_length,m=0;for(a=0;a<=_;a++)t.bl_count[a]=0;for(h[2*t.heap[t.heap_max]+1]=0,r=t.heap_max+1;rp&&(a=p,m++),h[2*i+1]=a,i>l||(t.bl_count[a]++,o=0,i>=d&&(o=c[i-d]),s=h[2*i],t.opt_len+=s*(a+o),u&&(t.static_len+=s*(f[2*i+1]+o)));if(0!==m){do{for(a=p-1;0===t.bl_count[a];)a--;t.bl_count[a]--,t.bl_count[a+1]+=2,t.bl_count[p]--,m-=2}while(m>0);for(a=p;0!==a;a--)for(i=t.bl_count[a];0!==i;)(n=t.heap[--r])>l||(h[2*n+1]!==a&&(t.opt_len+=(a-h[2*n+1])*h[2*n],h[2*n+1]=a),i--)}}(t,e),q(a,l,t.bl_count)}function K(t,e,r){var i,n,a=-1,o=e[1],s=0,h=7,l=4;for(0===o&&(h=138,l=3),e[2*(r+1)+1]=65535,i=0;i<=r;i++)n=o,o=e[2*(i+1)+1],++s>=7;i0?(t.strm.data_type===s&&(t.strm.data_type=function(t){var e,r=4093624447;for(e=0;e<=31;e++,r>>>=1)if(1&r&&0!==t.dyn_ltree[2*e])return a;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return o;for(e=32;e=3&&0===t.bl_tree[2*I[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),h=t.opt_len+3+7>>>3,(l=t.static_len+3+7>>>3)<=h&&(h=l)):h=l=r+5,r+4<=h&&-1!==e?et(t,e,r,i):t.strategy===n||l===h?(G(t,(f<<1)+(i?1:0),3),J(t,B,T)):(G(t,(u<<1)+(i?1:0),3),function(t,e,r,i){var n;for(G(t,e-257,5),G(t,r-1,5),G(t,i-4,4),n=0;n>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(P[r]+d+1)]++,t.dyn_dtree[2*F(e)]++),t.last_lit===t.lit_bufsize-1},r._tr_align=function(t){G(t,f<<1,3),H(t,v,B),function(t){16===t.bi_valid?(j(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}},{"../utils/common":49}],59:[function(t,e,r){"use strict";e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],60:[function(t,e,r){var i,n,a=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function h(t){if(i===setTimeout)return setTimeout(t,0);if((i===o||!i)&&setTimeout)return i=setTimeout,setTimeout(t,0);try{return i(t,0)}catch(e){try{return i.call(null,t,0)}catch(e){return i.call(this,t,0)}}}!function(){try{i="function"==typeof setTimeout?setTimeout:o}catch(t){i=o}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(t){n=s}}();var l,f=[],u=!1,c=-1;function d(){u&&l&&(u=!1,l.length?f=l.concat(f):c=-1,f.length&&p())}function p(){if(!u){var t=h(d);u=!0;for(var e=f.length;e;){for(l=f,f=[];++c1)for(var r=1;r2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:2===r?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}return"of ".concat(e," ").concat(String(t))}n("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),n("ERR_INVALID_ARG_TYPE",(function(t,e,r){var i,n,o,s;if("string"==typeof e&&(o="not ",e.substr(!s||s<0?0:+s,o.length)===o)?(i="must not be",e=e.replace(/^not /,"")):i="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))n="The ".concat(t," ").concat(i," ").concat(a(e,"type"));else{var h=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";n='The "'.concat(t,'" ').concat(h," ").concat(i," ").concat(a(e,"type"))}return n+". Received type ".concat(typeof r)}),TypeError),n("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),n("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),n("ERR_STREAM_PREMATURE_CLOSE","Premature close"),n("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),n("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),n("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),n("ERR_STREAM_WRITE_AFTER_END","write after end"),n("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),n("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),n("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),e.exports.codes=i},{}],63:[function(t,e,r){(function(r){(function(){"use strict";var i=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};e.exports=l;var n=t("./_stream_readable"),a=t("./_stream_writable");t("inherits")(l,n);for(var o=i(a.prototype),s=0;s0)if("string"==typeof e||o.objectMode||Object.getPrototypeOf(e)===s.prototype||(e=function(t){return s.from(t)}(e)),i)o.endEmitted?x(t,new v):A(t,o,e,!0);else if(o.ended)x(t,new y);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!r?(e=o.decoder.write(e),o.objectMode||0!==e.length?A(t,o,e,!1):P(t,o)):A(t,o,e,!1)}else i||(o.reading=!1,P(t,o));return!o.ended&&(o.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=I?t=I:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function T(t){var e=t._readableState;l("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(l("emitReadable",e.flowing),e.emittedReadable=!0,r.nextTick(R,t))}function R(t){var e=t._readableState;l("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,z(t)}function P(t,e){e.readingMore||(e.readingMore=!0,r.nextTick(O,t,e))}function O(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function C(t){l("readable nexttick read 0"),t.read(0)}function U(t,e){l("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),z(t),e.flowing&&!e.reading&&t.read(0)}function z(t){var e=t._readableState;for(l("flow",e.flowing);e.flowing&&null!==t.read(););}function D(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function N(t){var e=t._readableState;l("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,r.nextTick(F,e,t))}function F(t,e){if(l("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function j(t,e){for(var r=0,i=t.length;r=e.highWaterMark:e.length>0)||e.ended))return l("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?N(this):T(this),null;if(0===(t=B(t,e))&&e.ended)return 0===e.length&&N(this),null;var i,n=e.needReadable;return l("need readable",n),(0===e.length||e.length-t0?D(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&N(this)),null!==i&&this.emit("data",i),i},S.prototype._read=function(t){x(this,new w("_read()"))},S.prototype.pipe=function(t,e){var i=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,l("pipe count=%d opts=%j",n.pipesCount,e);var o=e&&!1===e.end||t===r.stdout||t===r.stderr?g:h;function s(e,r){l("onunpipe"),e===i&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,l("cleanup"),t.removeListener("close",p),t.removeListener("finish",m),t.removeListener("drain",f),t.removeListener("error",d),t.removeListener("unpipe",s),i.removeListener("end",h),i.removeListener("end",g),i.removeListener("data",c),u=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||f())}function h(){l("onend"),t.end()}n.endEmitted?r.nextTick(o):i.once("end",o),t.on("unpipe",s);var f=function(t){return function(){var e=t._readableState;l("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&a(t,"data")&&(e.flowing=!0,z(t))}}(i);t.on("drain",f);var u=!1;function c(e){l("ondata");var r=t.write(e);l("dest.write",r),!1===r&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==j(n.pipes,t))&&!u&&(l("false write response, pause",n.awaitDrain),n.awaitDrain++),i.pause())}function d(e){l("onerror",e),g(),t.removeListener("error",d),0===a(t,"error")&&x(t,e)}function p(){t.removeListener("finish",m),g()}function m(){l("onfinish"),t.removeListener("close",p),g()}function g(){l("unpipe"),i.unpipe(t)}return i.on("data",c),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",d),t.once("close",p),t.once("finish",m),t.emit("pipe",i),n.flowing||(l("pipe resume"),i.resume()),t},S.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var i=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var a=0;a0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,l("on readable",n.length,n.reading),n.length?T(this):n.reading||r.nextTick(C,this))),i},S.prototype.addListener=S.prototype.on,S.prototype.removeListener=function(t,e){var i=o.prototype.removeListener.call(this,t,e);return"readable"===t&&r.nextTick(L,this),i},S.prototype.removeAllListeners=function(t){var e=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||r.nextTick(L,this),e},S.prototype.resume=function(){var t=this._readableState;return t.flowing||(l("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,r.nextTick(U,t,e))}(this,t)),t.paused=!1,this},S.prototype.pause=function(){return l("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(l("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},S.prototype.wrap=function(t){var e=this,r=this._readableState,i=!1;for(var n in t.on("end",(function(){if(l("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(n){l("wrapped data"),r.decoder&&(n=r.decoder.write(n)),r.objectMode&&null==n||(r.objectMode||n&&n.length)&&(e.push(n)||(i=!0,t.pause()))})),t)void 0===this[n]&&"function"==typeof t[n]&&(this[n]=function(e){return function(){return t[e].apply(t,arguments)}}(n));for(var a=0;a-1))throw new v(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(S.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(S.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),S.prototype._write=function(t,e,r){r(new m("_write()"))},S.prototype._writev=null,S.prototype.end=function(t,e,i){var n=this._writableState;return"function"==typeof t?(i=t,t=null,e=null):"function"==typeof e&&(i=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,i){e.ending=!0,P(t,e),i&&(e.finished?r.nextTick(i):t.once("finish",i)),e.ended=!0,t.writable=!1}(this,n,i),this},Object.defineProperty(S.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(S.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),S.prototype.destroy=u.destroy,S.prototype._undestroy=u.undestroy,S.prototype._destroy=function(t,e){e(t)}}).call(this)}).call(this,t("_process"),void 0!==r.g?r.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":62,"./_stream_duplex":63,"./internal/streams/destroy":70,"./internal/streams/state":74,"./internal/streams/stream":75,_process:60,buffer:33,inherits:45,"util-deprecate":78}],68:[function(t,e,r){(function(r){(function(){"use strict";var i;function n(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}var a=t("./end-of-stream"),o=Symbol("lastResolve"),s=Symbol("lastReject"),h=Symbol("error"),l=Symbol("ended"),f=Symbol("lastPromise"),u=Symbol("handlePromise"),c=Symbol("stream");function d(t,e){return{value:t,done:e}}function p(t){var e=t[o];if(null!==e){var r=t[c].read();null!==r&&(t[f]=null,t[o]=null,t[s]=null,e(d(r,!1)))}}function m(t){r.nextTick(p,t)}var g=Object.getPrototypeOf((function(){})),b=Object.setPrototypeOf((n(i={get stream(){return this[c]},next:function(){var t=this,e=this[h];if(null!==e)return Promise.reject(e);if(this[l])return Promise.resolve(d(void 0,!0));if(this[c].destroyed)return new Promise((function(e,i){r.nextTick((function(){t[h]?i(t[h]):e(d(void 0,!0))}))}));var i,n=this[f];if(n)i=new Promise(function(t,e){return function(r,i){t.then((function(){e[l]?r(d(void 0,!0)):e[u](r,i)}),i)}}(n,this));else{var a=this[c].read();if(null!==a)return Promise.resolve(d(a,!1));i=new Promise(this[u])}return this[f]=i,i}},Symbol.asyncIterator,(function(){return this})),n(i,"return",(function(){var t=this;return new Promise((function(e,r){t[c].destroy(null,(function(t){t?r(t):e(d(void 0,!0))}))}))})),i),g);e.exports=function(t){var e,r=Object.create(b,(n(e={},c,{value:t,writable:!0}),n(e,o,{value:null,writable:!0}),n(e,s,{value:null,writable:!0}),n(e,h,{value:null,writable:!0}),n(e,l,{value:t._readableState.endEmitted,writable:!0}),n(e,u,{value:function(t,e){var i=r[c].read();i?(r[f]=null,r[o]=null,r[s]=null,t(d(i,!1))):(r[o]=t,r[s]=e)},writable:!0}),e));return r[f]=null,a(t,(function(t){if(t&&"ERR_STREAM_PREMATURE_CLOSE"!==t.code){var e=r[s];return null!==e&&(r[f]=null,r[o]=null,r[s]=null,e(t)),void(r[h]=t)}var i=r[o];null!==i&&(r[f]=null,r[o]=null,r[s]=null,i(d(void 0,!0))),r[l]=!0})),t.on("readable",m.bind(null,r)),r}}).call(this)}).call(this,t("_process"))},{"./end-of-stream":71,_process:60}],69:[function(t,e,r){"use strict";function i(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,i)}return r}function n(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function a(t,e){for(var r=0;r0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return o.alloc(0);for(var e=o.allocUnsafe(t>>>0),r=this.head,i=0;r;)n=r.data,a=e,s=i,o.prototype.copy.call(n,a,s),i+=r.data.length,r=r.next;var n,a,s;return e}},{key:"consume",value:function(t,e){var r;return tn.length?n.length:t;if(a===n.length?i+=n:i+=n.slice(0,t),0==(t-=a)){a===n.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=n.slice(a));break}++r}return this.length-=r,i}},{key:"_getBuffer",value:function(t){var e=o.allocUnsafe(t),r=this.head,i=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var n=r.data,a=t>n.length?n.length:t;if(n.copy(e,e.length-t,0,a),0==(t-=a)){a===n.length?(++i,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=n.slice(a));break}++i}return this.length-=i,e}},{key:h,value:function(t,e){return s(this,function(t){for(var e=1;e0,(function(t){f||(f=t),t&&c.forEach(h),a||(c.forEach(h),u(f))}))}));return r.reduce(l)}},{"../../../errors":62,"./end-of-stream":71}],74:[function(t,e,r){"use strict";var i=t("../../../errors").codes.ERR_INVALID_OPT_VALUE;e.exports={getHighWaterMark:function(t,e,r,n){var a=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=a){if(!isFinite(a)||Math.floor(a)!==a||a<0)throw new i(n?r:"highWaterMark",a);return Math.floor(a)}return t.objectMode?16:16384}}},{"../../../errors":62}],75:[function(t,e,r){e.exports=t("events").EventEmitter},{events:38}],76:[function(t,e,r){"use strict";var i=t("safe-buffer").Buffer,n=i.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function a(t){var e;switch(this.encoding=function(t){var e=function(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(t);if("string"!=typeof e&&(i.isEncoding===n||!n(t)))throw new Error("Unknown encoding: "+t);return e||t}(t),this.encoding){case"utf16le":this.text=h,this.end=l,e=4;break;case"utf8":this.fillLast=s,e=4;break;case"base64":this.text=f,this.end=u,e=3;break;default:return this.write=c,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=i.allocUnsafe(e)}function o(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function s(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function h(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var i=r.charCodeAt(r.length-1);if(i>=55296&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function l(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function f(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function u(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function c(t){return t.toString(this.encoding)}function d(t){return t&&t.length?this.write(t):""}r.StringDecoder=a,a.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0?(n>0&&(t.lastNeed=n-1),n):--i=0?(n>0&&(t.lastNeed=n-2),n):--i=0?(n>0&&(2===n?n=0:t.lastNeed=n-3),n):0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var i=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,i),t.toString("utf8",e,i)},a.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length}},{"safe-buffer":77}],77:[function(t,e,r){var i=t("buffer"),n=i.Buffer;function a(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=i:(a(i,r),r.Buffer=o),o.prototype=Object.create(n.prototype),a(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return i.SlowBuffer(t)}},{buffer:33}],78:[function(t,e,i){(function(t){(function(){function r(e){try{if(!t.localStorage)return!1}catch(t){return!1}var r=t.localStorage[e];return null!=r&&"true"===String(r).toLowerCase()}e.exports=function(t,e){if(r("noDeprecation"))return t;var i=!1;return function(){if(!i){if(r("throwDeprecation"))throw new Error(e);r("traceDeprecation")?console.trace(e):console.warn(e),i=!0}return t.apply(this,arguments)}}}).call(this)}).call(this,void 0!==r.g?r.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(t,e,r){arguments[4][25][0].apply(r,arguments)},{dup:25}],80:[function(t,e,r){"use strict";var i=t("is-arguments"),n=t("is-generator-function"),a=t("which-typed-array"),o=t("is-typed-array");function s(t){return t.call.bind(t)}var h="undefined"!=typeof BigInt,l="undefined"!=typeof Symbol,f=s(Object.prototype.toString),u=s(Number.prototype.valueOf),c=s(String.prototype.valueOf),d=s(Boolean.prototype.valueOf);if(h)var p=s(BigInt.prototype.valueOf);if(l)var m=s(Symbol.prototype.valueOf);function g(t,e){if("object"!=typeof t)return!1;try{return e(t),!0}catch(t){return!1}}function b(t){return"[object Map]"===f(t)}function _(t){return"[object Set]"===f(t)}function y(t){return"[object WeakMap]"===f(t)}function w(t){return"[object WeakSet]"===f(t)}function v(t){return"[object ArrayBuffer]"===f(t)}function x(t){return"undefined"!=typeof ArrayBuffer&&(v.working?v(t):t instanceof ArrayBuffer)}function E(t){return"[object DataView]"===f(t)}function k(t){return"undefined"!=typeof DataView&&(E.working?E(t):t instanceof DataView)}function S(t){return"[object SharedArrayBuffer]"===f(t)}function M(t){return"undefined"!=typeof SharedArrayBuffer&&(S.working?S(t):t instanceof SharedArrayBuffer)}function A(t){return g(t,u)}function I(t){return g(t,c)}function B(t){return g(t,d)}function T(t){return h&&g(t,p)}function R(t){return l&&g(t,m)}r.isArgumentsObject=i,r.isGeneratorFunction=n,r.isTypedArray=o,r.isPromise=function(t){return"undefined"!=typeof Promise&&t instanceof Promise||null!==t&&"object"==typeof t&&"function"==typeof t.then&&"function"==typeof t.catch},r.isArrayBufferView=function(t){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):o(t)||k(t)},r.isUint8Array=function(t){return"Uint8Array"===a(t)},r.isUint8ClampedArray=function(t){return"Uint8ClampedArray"===a(t)},r.isUint16Array=function(t){return"Uint16Array"===a(t)},r.isUint32Array=function(t){return"Uint32Array"===a(t)},r.isInt8Array=function(t){return"Int8Array"===a(t)},r.isInt16Array=function(t){return"Int16Array"===a(t)},r.isInt32Array=function(t){return"Int32Array"===a(t)},r.isFloat32Array=function(t){return"Float32Array"===a(t)},r.isFloat64Array=function(t){return"Float64Array"===a(t)},r.isBigInt64Array=function(t){return"BigInt64Array"===a(t)},r.isBigUint64Array=function(t){return"BigUint64Array"===a(t)},b.working="undefined"!=typeof Map&&b(new Map),r.isMap=function(t){return"undefined"!=typeof Map&&(b.working?b(t):t instanceof Map)},_.working="undefined"!=typeof Set&&_(new Set),r.isSet=function(t){return"undefined"!=typeof Set&&(_.working?_(t):t instanceof Set)},y.working="undefined"!=typeof WeakMap&&y(new WeakMap),r.isWeakMap=function(t){return"undefined"!=typeof WeakMap&&(y.working?y(t):t instanceof WeakMap)},w.working="undefined"!=typeof WeakSet&&w(new WeakSet),r.isWeakSet=function(t){return w(t)},v.working="undefined"!=typeof ArrayBuffer&&v(new ArrayBuffer),r.isArrayBuffer=x,E.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&E(new DataView(new ArrayBuffer(1),0,1)),r.isDataView=k,S.working="undefined"!=typeof SharedArrayBuffer&&S(new SharedArrayBuffer),r.isSharedArrayBuffer=M,r.isAsyncFunction=function(t){return"[object AsyncFunction]"===f(t)},r.isMapIterator=function(t){return"[object Map Iterator]"===f(t)},r.isSetIterator=function(t){return"[object Set Iterator]"===f(t)},r.isGeneratorObject=function(t){return"[object Generator]"===f(t)},r.isWebAssemblyCompiledModule=function(t){return"[object WebAssembly.Module]"===f(t)},r.isNumberObject=A,r.isStringObject=I,r.isBooleanObject=B,r.isBigIntObject=T,r.isSymbolObject=R,r.isBoxedPrimitive=function(t){return A(t)||I(t)||B(t)||T(t)||R(t)},r.isAnyArrayBuffer=function(t){return"undefined"!=typeof Uint8Array&&(x(t)||M(t))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(t){Object.defineProperty(r,t,{enumerable:!1,value:function(){throw new Error(t+" is not supported in userland")}})}))},{"is-arguments":46,"is-generator-function":47,"is-typed-array":48,"which-typed-array":82}],81:[function(t,e,r){(function(e){(function(){var i=Object.getOwnPropertyDescriptors||function(t){for(var e=Object.keys(t),r={},i=0;i=a)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}})),s=i[r];r=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),m(e)?i.showHidden=e:e&&r._extend(i,e),y(i.showHidden)&&(i.showHidden=!1),y(i.depth)&&(i.depth=2),y(i.colors)&&(i.colors=!1),y(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=l),u(i,t,i.depth)}function l(t,e){var r=h.styles[e];return r?"["+h.colors[r][0]+"m"+t+"["+h.colors[r][1]+"m":t}function f(t,e){return t}function u(t,e,i){if(t.customInspect&&e&&k(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(i,t);return _(n)||(n=u(t,n,i)),n}var a=function(t,e){if(y(e))return t.stylize("undefined","undefined");if(_(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}return b(e)?t.stylize(""+e,"number"):m(e)?t.stylize(""+e,"boolean"):g(e)?t.stylize("null","null"):void 0}(t,e);if(a)return a;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),E(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return c(e);if(0===o.length){if(k(e)){var h=e.name?": "+e.name:"";return t.stylize("[Function"+h+"]","special")}if(w(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(x(e))return t.stylize(Date.prototype.toString.call(e),"date");if(E(e))return c(e)}var l,f="",v=!1,S=["{","}"];return p(e)&&(v=!0,S=["[","]"]),k(e)&&(f=" [Function"+(e.name?": "+e.name:"")+"]"),w(e)&&(f=" "+RegExp.prototype.toString.call(e)),x(e)&&(f=" "+Date.prototype.toUTCString.call(e)),E(e)&&(f=" "+c(e)),0!==o.length||v&&0!=e.length?i<0?w(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),l=v?function(t,e,r,i,n){for(var a=[],o=0,s=e.length;o60?r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}(l,f,S)):S[0]+f+S[1]}function c(t){return"["+Error.prototype.toString.call(t)+"]"}function d(t,e,r,i,n,a){var o,s,h;if((h=Object.getOwnPropertyDescriptor(e,n)||{value:e[n]}).get?s=h.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):h.set&&(s=t.stylize("[Setter]","special")),I(i,n)||(o="["+n+"]"),s||(t.seen.indexOf(h.value)<0?(s=g(r)?u(t,h.value,null):u(t,h.value,r-1)).indexOf("\n")>-1&&(s=a?s.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+s.split("\n").map((function(t){return" "+t})).join("\n")):s=t.stylize("[Circular]","special")),y(o)){if(a&&n.match(/^\d+$/))return s;(o=JSON.stringify(""+n)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+s}function p(t){return Array.isArray(t)}function m(t){return"boolean"==typeof t}function g(t){return null===t}function b(t){return"number"==typeof t}function _(t){return"string"==typeof t}function y(t){return void 0===t}function w(t){return v(t)&&"[object RegExp]"===S(t)}function v(t){return"object"==typeof t&&null!==t}function x(t){return v(t)&&"[object Date]"===S(t)}function E(t){return v(t)&&("[object Error]"===S(t)||t instanceof Error)}function k(t){return"function"==typeof t}function S(t){return Object.prototype.toString.call(t)}function M(t){return t<10?"0"+t.toString(10):t.toString(10)}r.debuglog=function(t){if(t=t.toUpperCase(),!a[t])if(o.test(t)){var i=e.pid;a[t]=function(){var e=r.format.apply(r,arguments);console.error("%s %d: %s",t,i,e)}}else a[t]=function(){};return a[t]},r.inspect=h,h.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},h.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.types=t("./support/types"),r.isArray=p,r.isBoolean=m,r.isNull=g,r.isNullOrUndefined=function(t){return null==t},r.isNumber=b,r.isString=_,r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=y,r.isRegExp=w,r.types.isRegExp=w,r.isObject=v,r.isDate=x,r.types.isDate=x,r.isError=E,r.types.isNativeError=E,r.isFunction=k,r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},r.isBuffer=t("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function I(t,e){return Object.prototype.hasOwnProperty.call(t,e)}r.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[M(t.getHours()),M(t.getMinutes()),M(t.getSeconds())].join(":"),[t.getDate(),A[t.getMonth()],e].join(" ")),r.format.apply(r,arguments))},r.inherits=t("inherits"),r._extend=function(t,e){if(!e||!v(e))return t;for(var r=Object.keys(e),i=r.length;i--;)t[r[i]]=e[r[i]];return t};var B="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function T(t,e){if(!t){var r=new Error("Promise was rejected with a falsy value");r.reason=t,t=r}return e(t)}r.promisify=function(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(B&&t[B]){var e;if("function"!=typeof(e=t[B]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,B,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}function e(){for(var e,r,i=new Promise((function(t,i){e=t,r=i})),n=[],a=0;a{var e=t.exports={};e.nextTick=function(){var t="undefined"!=typeof window&&window.setImmediate,e="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(t)return function(t){return window.setImmediate(t)};if(e){var r=[];return window.addEventListener("message",(function(t){var e=t.source;e!==window&&null!==e||"process-tick"!==t.data||(t.stopPropagation(),r.length>0&&r.shift()())}),!0),function(t){r.push(t),window.postMessage("process-tick","*")}}return function(t){setTimeout(t,0)}}(),e.title="browser",e.browser=!0,e.env={},e.argv=[],e.binding=function(t){throw new Error("process.binding is not supported")},e.cwd=function(){return"/"},e.chdir=function(t){throw new Error("process.chdir is not supported")}},6197:(t,e,r)=>{"use strict";var i=r(8834).lW;Object.defineProperty(e,"__esModule",{value:!0}),e.AbstractTokenizer=void 0;const n=r(4644);e.AbstractTokenizer=class{constructor(t){this.position=0,this.numBuffer=new Uint8Array(8),this.fileInfo=t||{}}async readToken(t,e=this.position){const r=i.alloc(t.len);if(await this.readBuffer(r,{position:e})e)return this.position+=e,e}return this.position+=t,t}async close(){}normalizeOptions(t,e){if(e&&void 0!==e.position&&e.position{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.BufferTokenizer=void 0;const i=r(4644),n=r(6197);class a extends n.AbstractTokenizer{constructor(t,e){super(e),this.uint8Array=t,this.fileInfo.size=this.fileInfo.size?this.fileInfo.size:t.length}async readBuffer(t,e){if(e&&e.position){if(e.position{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.fromFile=e.FileTokenizer=void 0;const i=r(6197),n=r(4644),a=r(5187);class o extends i.AbstractTokenizer{constructor(t,e){super(e),this.fd=t}async readBuffer(t,e){const r=this.normalizeOptions(t,e);this.position=r.position;const i=await a.read(this.fd,t,r.offset,r.length,r.position);if(this.position+=i.bytesRead,i.bytesRead{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.readFile=e.writeFileSync=e.writeFile=e.read=e.open=e.close=e.stat=e.createReadStream=e.pathExists=void 0;const i=r(6777);e.pathExists=i.existsSync,e.createReadStream=i.createReadStream,e.stat=async function(t){return new Promise(((e,r)=>{i.stat(t,((t,i)=>{t?r(t):e(i)}))}))},e.close=async function(t){return new Promise(((e,r)=>{i.close(t,(t=>{t?r(t):e()}))}))},e.open=async function(t,e){return new Promise(((r,n)=>{i.open(t,e,((t,e)=>{t?n(t):r(e)}))}))},e.read=async function(t,e,r,n,a){return new Promise(((o,s)=>{i.read(t,e,r,n,a,((t,e,r)=>{t?s(t):o({bytesRead:e,buffer:r})}))}))},e.writeFile=async function(t,e){return new Promise(((r,n)=>{i.writeFile(t,e,(t=>{t?n(t):r()}))}))},e.writeFileSync=function(t,e){i.writeFileSync(t,e)},e.readFile=async function(t){return new Promise(((e,r)=>{i.readFile(t,((t,i)=>{t?r(t):e(i)}))}))}},8286:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ReadStreamTokenizer=void 0;const i=r(6197),n=r(4644);class a extends i.AbstractTokenizer{constructor(t,e){super(e),this.streamReader=new n.StreamReader(t)}async getFileInfo(){return this.fileInfo}async readBuffer(t,e){const r=this.normalizeOptions(t,e),i=r.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(t,e);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(0===r.length)return 0;const a=await this.streamReader.read(t,r.offset,r.length);if(this.position+=a,(!e||!e.mayBeLess)&&a0){const n=new Uint8Array(r.length+e);return i=await this.peekBuffer(n,{mayBeLess:r.mayBeLess}),t.set(n.subarray(e),r.offset),i-e}if(e<0)throw new Error("Cannot peek from a negative offset in a stream")}if(r.length>0){try{i=await this.streamReader.peek(t,r.offset,r.length)}catch(t){if(e&&e.mayBeLess&&t instanceof n.EndOfStreamError)return 0;throw t}if(!r.mayBeLess&&i{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.fromBuffer=e.fromStream=e.EndOfStreamError=void 0;const i=r(8286),n=r(932);var a=r(4644);Object.defineProperty(e,"EndOfStreamError",{enumerable:!0,get:function(){return a.EndOfStreamError}}),e.fromStream=function(t,e){return e=e||{},new i.ReadStreamTokenizer(t,e)},e.fromBuffer=function(t,e){return new n.BufferTokenizer(t,e)}},3569:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.fromStream=e.fromBuffer=e.EndOfStreamError=e.fromFile=void 0;const i=r(5187),n=r(7378);var a=r(9425);Object.defineProperty(e,"fromFile",{enumerable:!0,get:function(){return a.fromFile}});var o=r(7378);Object.defineProperty(e,"EndOfStreamError",{enumerable:!0,get:function(){return o.EndOfStreamError}}),Object.defineProperty(e,"fromBuffer",{enumerable:!0,get:function(){return o.fromBuffer}}),e.fromStream=async function(t,e){if(e=e||{},t.path){const r=await i.stat(t.path);e.path=t.path,e.size=r.size}return n.fromStream(t,e)}},643:(t,e)=>{"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e.Ee=function(t,e,r,i,n,a){for(var o=arguments.length,h=Array(o>6?o-6:0),l=6;l3?u-3:0),d=3;d{"use strict";var i=r(8834).lW;Object.defineProperty(e,"__esModule",{value:!0}),e.AnsiStringType=e.StringType=e.BufferType=e.Uint8ArrayType=e.IgnoreType=e.Float80_LE=e.Float80_BE=e.Float64_LE=e.Float64_BE=e.Float32_LE=e.Float32_BE=e.Float16_LE=e.Float16_BE=e.INT64_BE=e.UINT64_BE=e.INT64_LE=e.UINT64_LE=e.INT32_LE=e.INT32_BE=e.INT24_BE=e.INT24_LE=e.INT16_LE=e.INT16_BE=e.INT8=e.UINT32_BE=e.UINT32_LE=e.UINT24_BE=e.UINT24_LE=e.UINT16_BE=e.UINT16_LE=e.UINT8=void 0;const n=r(2333);function a(t){return new DataView(t.buffer,t.byteOffset)}e.UINT8={len:1,get:(t,e)=>a(t).getUint8(e),put:(t,e,r)=>(a(t).setUint8(e,r),e+1)},e.UINT16_LE={len:2,get:(t,e)=>a(t).getUint16(e,!0),put:(t,e,r)=>(a(t).setUint16(e,r,!0),e+2)},e.UINT16_BE={len:2,get:(t,e)=>a(t).getUint16(e),put:(t,e,r)=>(a(t).setUint16(e,r),e+2)},e.UINT24_LE={len:3,get(t,e){const r=a(t);return r.getUint8(e)+(r.getUint16(e+1,!0)<<8)},put(t,e,r){const i=a(t);return i.setUint8(e,255&r),i.setUint16(e+1,r>>8,!0),e+3}},e.UINT24_BE={len:3,get(t,e){const r=a(t);return(r.getUint16(e)<<8)+r.getUint8(e+2)},put(t,e,r){const i=a(t);return i.setUint16(e,r>>8),i.setUint8(e+2,255&r),e+3}},e.UINT32_LE={len:4,get:(t,e)=>a(t).getUint32(e,!0),put:(t,e,r)=>(a(t).setUint32(e,r,!0),e+4)},e.UINT32_BE={len:4,get:(t,e)=>a(t).getUint32(e),put:(t,e,r)=>(a(t).setUint32(e,r),e+4)},e.INT8={len:1,get:(t,e)=>a(t).getInt8(e),put:(t,e,r)=>(a(t).setInt8(e,r),e+1)},e.INT16_BE={len:2,get:(t,e)=>a(t).getInt16(e),put:(t,e,r)=>(a(t).setInt16(e,r),e+2)},e.INT16_LE={len:2,get:(t,e)=>a(t).getInt16(e,!0),put:(t,e,r)=>(a(t).setInt16(e,r,!0),e+2)},e.INT24_LE={len:3,get(t,r){const i=e.UINT24_LE.get(t,r);return i>8388607?i-16777216:i},put(t,e,r){const i=a(t);return i.setUint8(e,255&r),i.setUint16(e+1,r>>8,!0),e+3}},e.INT24_BE={len:3,get(t,r){const i=e.UINT24_BE.get(t,r);return i>8388607?i-16777216:i},put(t,e,r){const i=a(t);return i.setUint16(e,r>>8),i.setUint8(e+2,255&r),e+3}},e.INT32_BE={len:4,get:(t,e)=>a(t).getInt32(e),put:(t,e,r)=>(a(t).setInt32(e,r),e+4)},e.INT32_LE={len:4,get:(t,e)=>a(t).getInt32(e,!0),put:(t,e,r)=>(a(t).setInt32(e,r,!0),e+4)},e.UINT64_LE={len:8,get:(t,e)=>a(t).getBigUint64(e,!0),put:(t,e,r)=>(a(t).setBigUint64(e,r,!0),e+8)},e.INT64_LE={len:8,get:(t,e)=>a(t).getBigInt64(e,!0),put:(t,e,r)=>(a(t).setBigInt64(e,r,!0),e+8)},e.UINT64_BE={len:8,get:(t,e)=>a(t).getBigUint64(e),put:(t,e,r)=>(a(t).setBigUint64(e,r),e+8)},e.INT64_BE={len:8,get:(t,e)=>a(t).getBigInt64(e),put:(t,e,r)=>(a(t).setBigInt64(e,r),e+8)},e.Float16_BE={len:2,get(t,e){return n.read(t,e,!1,10,this.len)},put(t,e,r){return n.write(t,r,e,!1,10,this.len),e+this.len}},e.Float16_LE={len:2,get(t,e){return n.read(t,e,!0,10,this.len)},put(t,e,r){return n.write(t,r,e,!0,10,this.len),e+this.len}},e.Float32_BE={len:4,get:(t,e)=>a(t).getFloat32(e),put:(t,e,r)=>(a(t).setFloat32(e,r),e+4)},e.Float32_LE={len:4,get:(t,e)=>a(t).getFloat32(e,!0),put:(t,e,r)=>(a(t).setFloat32(e,r,!0),e+4)},e.Float64_BE={len:8,get:(t,e)=>a(t).getFloat64(e),put:(t,e,r)=>(a(t).setFloat64(e,r),e+8)},e.Float64_LE={len:8,get:(t,e)=>a(t).getFloat64(e,!0),put:(t,e,r)=>(a(t).setFloat64(e,r,!0),e+8)},e.Float80_BE={len:10,get(t,e){return n.read(t,e,!1,63,this.len)},put(t,e,r){return n.write(t,r,e,!1,63,this.len),e+this.len}},e.Float80_LE={len:10,get(t,e){return n.read(t,e,!0,63,this.len)},put(t,e,r){return n.write(t,r,e,!0,63,this.len),e+this.len}},e.IgnoreType=class{constructor(t){this.len=t}get(t,e){}},e.Uint8ArrayType=class{constructor(t){this.len=t}get(t,e){return t.subarray(e,e+this.len)}},e.BufferType=class{constructor(t){this.len=t}get(t,e){return i.from(t.subarray(e,e+this.len))}},e.StringType=class{constructor(t,e){this.len=t,this.encoding=e}get(t,e){return i.from(t).toString(this.encoding,e,e+this.len)}};class o{constructor(t){this.len=t}static decode(t,e,r){let i="";for(let n=e;n>10),56320+(1023&t)))}static singleByteDecoder(t){if(o.inRange(t,0,127))return t;const e=o.windows1252[t-128];if(null===e)throw Error("invaliding encoding");return e}get(t,e=0){return o.decode(t,e,e+this.len)}}e.AnsiStringType=o,o.windows1252=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255]},311:(t,e)=>{(e=t.exports=function(t){return t.replace(/^\s*|\s*$/g,"")}).left=function(t){return t.replace(/^\s*/,"")},e.right=function(t){return t.replace(/\s*$/,"")}},9299:(t,e,r)=>{var i=r(4406);!function(){var e={};function n(){void 0===i&&console.log.apply(console,arguments)}t.exports=e,function(t,e){var r,i,a,o,s,h,l,f,u,c,d,p,m,g,b;!function(){"use strict";var e=function(){function t(t){this.message="JPEG error: "+t}return t.prototype=new Error,t.prototype.name="JpegError",t.constructor=t,t}(),r=function(){var t=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),r=4017,n=799,a=3406,o=2276,s=1567,h=3784,l=5793,f=2896;function u(t){null==t&&(t={}),null==t.w&&(t.w=-1),this.V=t.n,this.N=t.w}function c(t,e){for(var r,i,n,a=0,o=[],s=16;s>0&&!t[s-1];)s--;o.push({children:[],index:0});var h=o[0];for(r=0;r0;)h=o.pop();for(h.index++,o.push(h);o.length<=r;)o.push(n={children:[],index:0}),h.children[h.index]=n.children,h=n;a++}r+10)return T--,B>>T&1;if(255===(B=r[n++])){var t=r[n++];if(t){if(220===t&&c){var o=i(r,n+=2);if(n+=2,o>0&&o!==a.s)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",o)}else if(217===t){if(c){var s=8*O;if(s>0&&s>>7}function U(t){for(var r=t;;){switch(typeof(r=r[C()])){case"number":return r;case"object":continue}throw new e("invalid huffman sequence")}}function z(t){for(var e=0;t>0;)e=e<<1|C(),t--;return e}function D(t){if(1===t)return 1===C()?1:-1;var e=z(t);return e>=1<0)R--;else for(var i=h,n=l;i<=n;){var a=U(e.i),o=15&a,s=a>>4;if(0!==o){var f=t[i+=s];e.D[r+f]=D(o)*(1<>4,0==(n=15&a))f<15?(R=z(f)+(1<>4;if(0!==s){var l=t[a+=h];e.D[r+l]=D(s),a++}else{if(h<15)break;a+=16}}},E=1===j?o[0].P*o[0].c:M*a.R;L<=E;){var G=s?Math.min(E-L,s):E;if(G>0){for(g=0;g=65488&&x.M<=65495))break;n+=2}return n-I}function m(t,i,u){var c,d,p,m,g,b,_,y,w,v,x,E,k,S,M,A,I,B=t.$,T=t.D;if(!B)throw new e("missing required Quantization Table.");for(var R=0;R<64;R+=8)w=T[i+R],v=T[i+R+1],x=T[i+R+2],E=T[i+R+3],k=T[i+R+4],S=T[i+R+5],M=T[i+R+6],A=T[i+R+7],w*=B[R],0!=(v|x|E|k|S|M|A)?(v*=B[R+1],x*=B[R+2],E*=B[R+3],k*=B[R+4],S*=B[R+5],M*=B[R+6],A*=B[R+7],d=(c=(c=l*w+128>>8)+(d=l*k+128>>8)+1>>1)-d,I=(p=x)*h+(m=M)*s+128>>8,p=p*s-m*h+128>>8,_=(g=(g=f*(v-A)+128>>8)+(_=S<<4)+1>>1)-_,b=(y=(y=f*(v+A)+128>>8)+(b=E<<4)+1>>1)-b,m=(c=c+(m=I)+1>>1)-m,p=(d=d+p+1>>1)-p,I=g*o+y*a+2048>>12,g=g*a-y*o+2048>>12,y=I,I=b*n+_*r+2048>>12,b=b*r-_*n+2048>>12,_=I,u[R]=c+y,u[R+7]=c-y,u[R+1]=d+_,u[R+6]=d-_,u[R+2]=p+b,u[R+5]=p-b,u[R+3]=m+g,u[R+4]=m-g):(I=l*w+512>>10,u[R]=I,u[R+1]=I,u[R+2]=I,u[R+3]=I,u[R+4]=I,u[R+5]=I,u[R+6]=I,u[R+7]=I);for(var P=0;P<8;++P)w=u[P],0!=((v=u[P+8])|(x=u[P+16])|(E=u[P+24])|(k=u[P+32])|(S=u[P+40])|(M=u[P+48])|(A=u[P+56]))?(d=(c=4112+((c=l*w+2048>>12)+(d=l*k+2048>>12)+1>>1))-d,I=(p=x)*h+(m=M)*s+2048>>12,p=p*s-m*h+2048>>12,m=I,_=(g=(g=f*(v-A)+2048>>12)+(_=S)+1>>1)-_,b=(y=(y=f*(v+A)+2048>>12)+(b=E)+1>>1)-b,I=g*o+y*a+2048>>12,g=g*a-y*o+2048>>12,y=I,I=b*n+_*r+2048>>12,b=b*r-_*n+2048>>12,(w=(c=c+m+1>>1)+y)<16?w=0:w>=4080?w=255:w>>=4,(v=(d=d+p+1>>1)+(_=I))<16?v=0:v>=4080?v=255:v>>=4,(x=(p=d-p)+b)<16?x=0:x>=4080?x=255:x>>=4,(E=(m=c-m)+g)<16?E=0:E>=4080?E=255:E>>=4,(k=m-g)<16?k=0:k>=4080?k=255:k>>=4,(S=p-b)<16?S=0:S>=4080?S=255:S>>=4,(M=d-_)<16?M=0:M>=4080?M=255:M>>=4,(A=c-y)<16?A=0:A>=4080?A=255:A>>=4,T[i+P]=w,T[i+P+8]=v,T[i+P+16]=x,T[i+P+24]=E,T[i+P+32]=k,T[i+P+40]=S,T[i+P+48]=M,T[i+P+56]=A):(I=(I=l*w+8192>>14)<-2040?0:I>=2024?255:I+2056>>4,T[i+P]=I,T[i+P+8]=I,T[i+P+16]=I,T[i+P+24]=I,T[i+P+32]=I,T[i+P+40]=I,T[i+P+48]=I,T[i+P+56]=I)}function g(t,e){for(var r=e.P,i=e.c,n=new Int16Array(64),a=0;a=n)return null;var o=i(t,e);if(o>=65472&&o<=65534)return{u:null,M:o,offset:e};for(var s=i(t,a);!(s>=65472&&s<=65534);){if(++a>=n)return null;s=i(t,a)}return{u:o.toString(16),M:s,offset:a}}return u.prototype={parse(r,n){null==n&&(n={});var a,o,s=n.F,h=0,l=null,f=null,u=0;function d(){var t=i(r,h),e=(h+=2)+t-2,n=b(r,e,h);n&&n.u&&(e=n.offset);var a=r.subarray(h,e);return h+=a.length,a}function m(t){for(var e=Math.ceil(t.o/8/t.X),r=Math.ceil(t.s/8/t.B),i=0;i>4==0)for(E=0;E<64;E++)I[t[E]]=r[h++];else{if(A>>4!=1)throw new e("DQT - invalid table spec");for(E=0;E<64;E++)I[t[E]]=i(r,h),h+=2}_[15&A]=I}break;case 65472:case 65473:case 65474:if(a)throw new e("Only single frame JPEGs supported");h+=2,(a={}).G=65473===v,a.Z=65474===v,a.precision=r[h++];var B,T=i(r,h),R=0,P=0;h+=2,a.s=s||T,a.o=i(r,h),h+=2,a.W=[],a._={};var O=r[h++];for(x=0;x>4,C=15&r[h+1];R>4==0?w:y)[15&D]=c(N,j)}break;case 65501:o=i(r,h+=2),h+=2;break;case 65498:var G,H=1==++u&&!s;h+=2;var W=r[h++],q=[];for(x=0;x>4],G.i=y[15&V],q.push(G)}var X=r[h++],J=r[h++],Q=r[h++];try{var K=p(r,h,a,q,o,X,J,Q>>4,15&Q,H);h+=K}catch(t){if(t instanceof DNLMarkerError)return this.parse(r,{F:t.s});if(t instanceof EOIMarkerError)break t;throw t}break;case 65500:h+=4;break;case 65535:255!==r[h]&&h--;break;default:var $=b(r,h-2,h-3);if($&&$.u){h=$.offset;break}if(h>=r.length-1)break t;throw new e("JpegImage.parse - unknown marker: "+v.toString(16))}v=i(r,h),h+=2}for(this.width=a.o,this.height=a.s,this.g=l,this.b=f,this.W=[],x=0;x>8)+E[u+1];return w},get f(){return this.b?!!this.b.a:3===this.p?0!==this.N&&(82!==this.W[0].index||71!==this.W[1].index||66!==this.W[2].index):1===this.N},z:function(t){for(var e,r,i,n=0,a=t.length;n4)throw new e("Unsupported color mode");var o=this.Y(r,i,a);if(1===this.p&&n){for(var s=o.length,h=new Uint8ClampedArray(3*s),l=0,f=0;f3&&(r.t258=r.t258.slice(0,3)),s=r.t258?Math.min(32,r.t258[0])*r.t258.length:r.t277?r.t277[0]:1,1==h&&null!=r.t279&&r.t278&&32803==r.t262[0]&&(s=Math.round(8*r.t279[0]/(r.width*r.t278[0]))),r.t50885&&4==r.t50885[0]&&(s=3*r.t258[0]);var f=8*Math.ceil(r.width*s/8),u=r.t273;(null==u||r.t322)&&(u=r.t324);var c=r.t279;1==h&&1==u.length&&(c=[r.height*(f>>>3)]),(null==c||r.t322)&&(c=r.t325);var d=new Uint8Array(r.height*(f>>>3)),p=0;if(null!=r.t322){var m=r.t322[0],g=r.t323[0],b=Math.floor((r.width+m-1)/m),_=Math.floor((r.height+g-1)/g),y=new Uint8Array(0|Math.ceil(m*g*s/8));console.log("====",b,_);for(var w=0;w<_;w++)for(var v=0;v>>3,y=r.t278?r.t278[0]:r.height,w=Math.ceil(g*b*r.width/8);if(16==g&&!r.isLE&&null==r.t33422)for(var v=0;v>>8&255}else if(3==b)for(c=3;c>>3]>>>7-(7&e)&1;return t[1]++,r}function s(t,r){if(null==e){e={};for(var i=0;i>>=1;return t}function l(t,e){return t>>e}function f(t,e,r,i,n,a){e[r]=l(l(11*t[n]-4*t[n+a]+t[n+a+a]+4,3)+t[i],1),e[r+a]=l(l(5*t[n]+4*t[n+a]-t[n+a+a]+4,3)-t[i],1)}function u(t,e,r,i,n,a){var o=t[n-a]-t[n+a],s=t[n],h=t[i];e[r]=l(l(o+4,3)+s+h,1),e[r+a]=l(l(4-o,3)+s-h,1)}function c(t,e,r,i,n,a){e[r]=l(l(5*t[n]+4*t[n-a]-t[n-a-a]+4,3)+t[i],1),e[r+a]=l(l(11*t[n]-4*t[n-a]+t[n-a-a]+4,3)-t[i],1)}function d(t){return i[t=t<0?0:t>4095?4095:t]>>>2}return function(e,n,o,l,p){l=new Uint16Array(l.buffer);var m,g,b,_,y,w,v,x,E=Date.now(),k=t._binBE,S=n+o;for(n+=4;n>>1)*(g>>>1));for(x=new Int16Array((m>>>1)*(g>>>1)),r=new Int16Array(1024),R=0;R<1024;R++){var P=R-512,O=Math.abs(P),L=Math.floor(768*O*O*O/16581375)+O;r[R]=Math.sign(P)*L}for(i=new Uint16Array(4096),R=0;R<4096;R++){var C=R,U=65535*(Math.pow(113,C/4095)-1)/112;i[R]=Math.min(U,65535)}}var z=v[y],D=h(m,1+a[b]),N=h(g,1+a[b]);if(0==b)for(var F=0;F>>1)+j]=e[G]<<8|e[G+1]}else{var H=[e,8*n],W=[],q=0,Z=D*N,Y=[0,0],V=0;for(A=0;q0;)W[q++]=A,V--;var X=(b-1)%3,J=1!=X?D:0,Q=0!=X?N:0;for(F=0;F>>1)+J,$=F*D;for(j=0;j>>1,et=2*D,rt=2*N;for(F=0;F>14-2*ht&3;var lt=ot[st];if(0!=lt)for(F=0;F>>1)*(m>>>1)+(j>>>1)],gt=ut[G]-2048,bt=ct[G]-2048,_t=dt[G]-2048,yt=(gt<<1)+mt,wt=(bt<<1)+mt,vt=mt+_t,xt=mt-_t;l[pt]=d(yt),l[pt+1]=d(vt),l[pt+m]=d(xt),l[pt+m+1]=d(wt)}}n+=4*T}else if(16388==I)n+=4*T;else if(8192!=B&&8448!=B&&9216!=B)throw I.toString(16)}}console.log(Date.now()-E)}}(),t.decode._decodeLogLuv32=function(t,e,r,i,n,a){for(var o=t.width,s=4*o,h=0,l=new Uint8Array(s);h>>11,p=15&u>>>22,m=15&u>>>26,g=0;g<4&&128<>3))>>>(7&b)&127)<2047&&(y[x]=2047),b+=7);for(x=0;x<16;x++,A+=2)U=y[x]<<1,t.decode._putsF(a,(I*s+A)*l,U<<16-l);A-=1&A?1:31}}}else for(var x=0;x>>4,a[o+x+1]=E<<4|S>>>4,a[o+x+2]=S<<4|k>>>4}else{h+=8;var M,A,I,B=[i,0,0,0],T=new Uint16Array(32770),R=[3857,3856,3599,3342,3085,2828,2571,2314,2057,1800,1543,1286,1029,772,771,768,514,513],P=0,O=t.decode._ljpeg_diff;for(T[0]=15,M=x=0;x<18;x++)for(var L=32768>>>(R[x]>>>8),C=0;C1&&(R=Math.floor(T/(P-1))),68==y&&32==w&&R>0&&(d=x.readShort(b,562));var O=[0,0],L=p(h[c]),C=[n,0,0,0];for(S=0;S>>4),0)<<1)<>>1)&1<>>3;t[i]|=r>>>16,t[i+1]|=r>>>8,t[i+2]|=r},t.decode._getbithuff=function(e,r,i,n){t.decode._get_byte;var a,o=r[0],s=r[1],h=r[2],l=r[3];if(0==i||h<0)return 0;for(;!l&&h>>32-i,n?(h-=n[a+1]>>>8,a=255&n[a+1]):h-=i,h<0)throw"e";return r[0]=o,r[1]=s,r[2]=h,r[3]=l,a},t.decode._make_decoder=function(t){var e,r,i,n,a,o=[];for(e=16;0!=e&&!t[e];e--);var s=17;for(o[0]=e,i=r=1;r<=e;r++)for(n=0;n>>8;else for(u=0;u>>8,a[o+(u<<1)+1]=255&m[u];else if(14==p||12==p){var b=16-p;for(u=0;u1),!d){if(255==e[r]&&e[r+1]==f)return{jpegOffset:r};if(null!=p&&(255==e[r+m]&&e[r+m+1]==f?u=r+m:n("JPEGInterchangeFormat does not point to SOI"),null==g?n("JPEGInterchangeFormatLength field is missing"):(m>=c||m+b<=c)&&n("JPEGInterchangeFormatLength field value is invalid"),null!=u))return{jpegOffset:u}}if(null!=y&&(w=y[0],v=y[1]),null!=p&&null!=g)if(b>=2&&m+b<=c){for(a=255==e[r+m+b-2]&&e[r+m+b-1]==f?new Uint8Array(b-2):new Uint8Array(b),s=0;s offset to first strip or tile");if(null==a){var k=0,S=[];S[k++]=255,S[k++]=f;var M=t.t519;if(null==M)throw new Error("JPEGQTables tag is missing");for(s=0;s>>8,S[k++]=255&I,S[k++]=s|l<<4,h=0;h<16;h++)S[k++]=e[r+A[s]+h];for(h=0;h>>8&255,S[k++]=255&t.height,S[k++]=t.width>>>8&255,S[k++]=255&t.width,S[k++]=x,1==x)S[k++]=1,S[k++]=17,S[k++]=0;else for(s=0;s<3;s++)S[k++]=s+1,S[k++]=0!=s?17:(15&w)<<4|15&v,S[k++]=s;null!=E&&0!=E[0]&&(S[k++]=255,S[k++]=221,S[k++]=0,S[k++]=4,S[k++]=E[0]>>>8&255,S[k++]=255&E[0]),a=new Uint8Array(S)}var B=-1;for(s=0;s>>8&255,a[R++]=255&t.height,a[R++]=t.width>>>8&255,a[R++]=255&t.width,a[R++]=x,1==x)a[R++]=1,a[R++]=17,a[R++]=0;else for(s=0;s<3;s++)a[R++]=s+1,a[R++]=0!=s?17:(15&w)<<4|15&v,a[R++]=s}if(255==e[c]&&218==e[c+1]){var P=e[c+2]<<8|e[c+3];for((o=new Uint8Array(P+2))[0]=e[c],o[1]=e[c+1],o[2]=e[c+2],o[3]=e[c+3],s=0;s>>8&255,l[u.sofPosition+6]=255&e.height,l[u.sofPosition+7]=e.width>>>8&255,l[u.sofPosition+8]=255&e.width,255==r[i]&&r[i+1]==SOS||(l.set(u.sosMarker,f),f+=sosMarker.length),p=0;p=0&&h<128)for(var l=0;l=-127&&h<0){for(l=0;l<1-h;l++)o[n]=a[e],n++;e++}}return n},t.decode._decodeThunder=function(t,e,r,i,n){for(var a=[0,1,0,-1],o=[0,1,2,3,0,-3,-2,-1],s=e+r,h=2*n,l=0;e>>6,c=63&f;if(e++,3==u&&(l=15&c,i[h>>>1]|=l<<4*(1-h&1),h++),0==u)for(var d=0;d>>1]|=l<<4*(1-h&1),h++;if(2==u)for(d=0;d<2;d++)4!=(p=c>>>3*(1-d)&7)&&(l+=o[p],i[h>>>1]|=l<<4*(1-h&1),h++);if(1==u)for(d=0;d<3;d++){var p;2!=(p=c>>>2*(2-d)&3)&&(l+=a[p],i[h>>>1]|=l<<4*(1-h&1),h++)}}},t.decode._dmap={1:0,"011":1,"000011":2,"0000011":3,"010":-1,"000010":-2,"0000010":-3},t.decode._lens=function(){var t=function(t,e,r,i){for(var n=0;n>>3>>3]>>>7-(7&l)&1),2==s&&(k=e[l>>>3]>>>(7&l)&1),l++,u+=k,"H"==v){if(null!=h._lens[y][u]){var S=h._lens[y][u];u="",f+=S,S<64&&(h._addNtimes(c,f,y),m+=f,y=1-y,f=0,0==--x&&(v=""))}}else"0001"==u&&(u="",h._addNtimes(c,_-m,y),m=_),"001"==u&&(u="",v="H",x=2),null!=h._dmap[u]&&(g=b+h._dmap[u],h._addNtimes(c,g-m,y),m=g,u="",y=1-y);c.length==o&&""==v&&(h._writeBits(c,n,8*a+w*E),y=0,w++,m=0,d=h._makeDiff(c),c=[])}},t.decode._findDiff=function(t,e,r){for(var i=0;i=e&&t[i+1]==r)return t[i]},t.decode._makeDiff=function(t){var e=[];1==t[0]&&e.push(0,1);for(var r=1;r>>3>>3]>>>7-(7&l)&1),2==s&&(g=e[l>>>3]>>>(7&l)&1),l++,u+=g,null!=(f=h._lens[d][u])&&(h._addNtimes(c,f,d),u="",f<64&&(d=1-d),c.length==o&&(h._writeBits(c,n,8*a+p*m),c=[],p++,d=0,0!=(7&l)&&(l+=8-(7&l)),f>=64&&(l+=8)))}},t.decode._decodeG3=function(e,r,i,n,a,o,s,h){for(var l=t.decode,f=r<<3,u=0,c="",d=[],p=[],m=0;m>>3>>3]>>>7-(7&f)&1),2==s&&(M=e[f>>>3]>>>(7&f)&1),f++,c+=M,k){if(null!=l._lens[w][c]){var A=l._lens[w][c];c="",u+=A,A<64&&(l._addNtimes(d,u,w),w=1-w,u=0)}}else"H"==x?null!=l._lens[w][c]&&(A=l._lens[w][c],c="",u+=A,A<64&&(l._addNtimes(d,u,w),g+=u,w=1-w,u=0,0==--E&&(x=""))):("0001"==c&&(c="",l._addNtimes(d,y-g,w),g=y),"001"==c&&(c="",x="H",E=2),null!=l._dmap[c]&&(b=_+l._dmap[c],l._addNtimes(d,b-g,w),g=b,c="",w=1-w));c.endsWith("000000000001")&&(v>=0&&l._writeBits(d,n,8*a+v*S),h&&(1==s&&(k=1==(e[f>>>3]>>>7-(7&f)&1)),2==s&&(k=1==(e[f>>>3]>>>(7&f)&1)),f++),c="",w=0,v++,g=0,p=l._makeDiff(d),d=[])}d.length==o&&l._writeBits(d,n,8*a+v*S)},t.decode._addNtimes=function(t,e,r){for(var i=0;i>>3]|=t[i]<<7-(r+i&7)},t.decode._decodeLZW=t.decode._decodeLZW=(s=0,h=0,l=0,f=0,u=function(){var t=r>>>3,e=(i[t]<<16|i[t+1]<<8|i[t+2])>>>24-(7&r)-h&(1<>>----------------");for(var f=0;f4&&(e.writeUint(i,n,h),g=h),1==c||7==c)for(var b=0;b4&&(h+=m+=1&m),n+=4}}return[n,h]},t.toRGBA8=function(t,e){var r=t.width,i=t.height,a=r*i,o=4*a,s=t.data,h=new Uint8Array(4*a),l=t.t262?t.t262[0]:2,f=t.t258?Math.min(32,t.t258[0]):1;if(null==t.t262&&1==f&&(l=0),0==l)for(var u=Math.ceil(f*r/8),c=0;c>3)]>>7-(7&m)&1;h[g]=h[g+1]=h[g+2]=255*(1-b),h[g+3]=255}if(4==f)for(m=0;m>1)]>>4-4*(1&m)&15,h[g]=h[g+1]=h[g+2]=17*(15-b),h[g+3]=255;if(8==f)for(m=0;m>3)]>>7-(7&m)&1,h[g]=h[g+1]=h[g+2]=255*b,h[g+3]=255;if(2==f)for(m=0;m>2)]>>6-2*(3&m)&3,h[g]=h[g+1]=h[g+2]=85*b,h[g+3]=255;if(8==f)for(m=0;m>>3)]>>>7-(7&S)&1;else if(2==f)M=s[A+(S>>>2)]>>>6-2*(3&S)&3;else if(4==f)M=s[A+(S>>>1)]>>>4-4*(1&S)&15;else{if(8!=f)throw f;M=s[A+S*_]}h[g]=E[M]>>8,h[g+1]=E[k+M]>>8,h[g+2]=E[k+k+M]>>8,h[g+3]=255}}else if(5==l){var I=(_=t.t258?t.t258.length:4)>4?1:0;for(m=0;m>>1))+(1&z)];var D=s[B+2]-128,N=s[B+3]-128,F=P+((N>>2)+(N>>3)+(N>>5)),j=P-((D>>2)+(D>>4)+(D>>5))-((N>>1)+(N>>3)+(N>>4)+(N>>5)),G=P+(D+(D>>1)+(D>>2)+(D>>6));h[g]=Math.max(0,Math.min(255,F)),h[g+1]=Math.max(0,Math.min(255,j)),h[g+2]=Math.max(0,Math.min(255,G)),h[g+3]=255}}}else if(32845==l){function H(t){return t<.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055}for(c=0;cn&&(n=h,a=s)}}t.decodeImage(e,a,r);var l=t.toRGBA8(a),f=a.width,u=a.height,c=document.createElement("canvas");c.width=f,c.height=u;var d=c.getContext("2d"),p=new ImageData(new Uint8ClampedArray(l.buffer),f,u);return d.putImageData(p,0,0),c.toDataURL()},t._binBE={nextZero:function(t,e){for(;0!=t[e];)e++;return e},readUshort:function(t,e){return t[e]<<8|t[e+1]},readShort:function(e,r){var i=t._binBE.ui8;return i[0]=e[r+1],i[1]=e[r+0],t._binBE.i16[0]},readInt:function(e,r){var i=t._binBE.ui8;return i[0]=e[r+3],i[1]=e[r+2],i[2]=e[r+1],i[3]=e[r+0],t._binBE.i32[0]},readUint:function(e,r){var i=t._binBE.ui8;return i[0]=e[r+3],i[1]=e[r+2],i[2]=e[r+1],i[3]=e[r+0],t._binBE.ui32[0]},readASCII:function(t,e,r){for(var i="",n=0;n>8&255,t[e+1]=255&r},writeInt:function(e,r,i){var n=t._binBE.ui8;t._binBE.i32[0]=i,e[r+3]=n[0],e[r+2]=n[1],e[r+1]=n[2],e[r+0]=n[3]},writeUint:function(t,e,r){t[e]=r>>24&255,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=r>>0&255},writeASCII:function(t,e,r){for(var i=0;i>8&255},writeInt:function(e,r,i){var n=t._binBE.ui8;t._binBE.i32[0]=i,e[r+0]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3]},writeUint:function(t,e,r){t[e]=r>>>0&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24&255},writeASCII:t._binBE.writeASCII},t._copyTile=function(t,e,r,i,n,a,o,s){for(var h=Math.min(e,n-o),l=Math.min(r,a-s),f=0;f>--l&1)];h[o]=u}}function a(t,e,r,i){if(255!=t[e+3])return 0;if(0==r)return e;for(var n=0;n<2;n++){0==t[e+n]&&(t[e+n]=t.length,t.push(0,0,i,255));var o=a(t,t[e+n],r-1,i+1);if(0!=o)return o}return 0}function o(t){for(var e=t.b,r=t.a;e<25&&t.e>>8),r=r<<8|i,e+=8}if(e<0)throw"e";t.b=e,t.a=r}function s(t,e){return e.b>(e.b-=t)&65535>>16-t}function h(t,e){var r=t[0],i=0,n=255;e.b<16&&o(e);var a=e.a>>e.b-8&255;for(n=r[(i=t[1][a])+3],e.b-=r[i+2];255==n;)n=r[(i=r[i+(e.a>>--e.b&1)])+3];return n}function l(t,e){return t<32768>>16-e&&(t+=1-(1<>>1);else if(6==e)g=t[p]+(m-t[p-o]>>>1);else{if(7!=e)throw e;g=m+t[p]>>>1}t[d]+=g}}}return function(a){if(t=a,e=0,65496!=i())throw"e";for(var o=[],s=0,l=0,f=[],p=[],m=[],g=0,b=0,_=0;;){var y=i();if(65535!=y){var w=i();if(65475==y){l=r(),b=i(),_=i(),g=r();for(var v=0;v>4,15&E]}}else if(65476==y)for(var k=e+w-2;e>>4],f[S[0]]=S.slice(1)}s=r(),e+=2;break}e+=w-2}}else e--}var M=new(l>8?Uint16Array:Uint8Array)(b*_*g),A={b:0,a:0,c:8==s,e,data:t,d:t.length};if(A.c)!function(r,i,n,a,o){for(var s=t.length-e,l=0;lB&&(B=N),(D=R[1])>T&&(T=D),I.push(N*D)}if(1!=B||1!=T){var P=[],O=0;for(v=0;v>>6),i=0;i<3;i++)for(var n=0;n<41;n++)e[i][n]=[r,1];return e}function _(t,e){var r=0,i=8-t.a;if(t.j,t.a,e){if(e>=i)do{r<<=i,e-=i,r|=t[t.j]&(1<=8);e&&(r<<=e,i-=e,r|=t[t.j]>>>i&(1<c&&u>>2,s)return void(b[p]=d);h=e.t*e.c[t.g+x-w]+e.c[t.g+v-x]}else d=x>v&&x>E||x>>2:k+S>>>1,h=e.t*e.c[t.g+x-v]+e.c[t.g+v-k];l=M(h);var A=function(t){for(var e=-1,r=0;!r;e++)r=t[t.j]>>>7-t.a&1,t.a++,t.a&=7,t.a||t.j++;return e}(r);if(A>>1):g>>>1,o[l][0]+=M(g),o[l][1]==t.f&&(o[l][0]>>>=1,o[l][1]>>>=1),o[l][1]++,d=h<0?d-g:d+g,t.i&&(d<0?d+=e.w:d>t.g&&(d-=e.w)),b[p]=d>=0?Math.min(d,t.g):0}function w(t,e,r){for(var i=t[0].length,n=e;n<=r;n++)t[n][0]=t[n-1][1],t[n][i-1]=t[n-1][i-2]}function v(t){w(t,o,u),w(t,e,i),w(t,p,g)}function x(t,e,r,n,a,o,s,h,l,f,u,d,p){for(var m=0,g=1,b=ai;g8&&(y(t,e,r,n,a,g,h[l]),y(t,e,r,n,o,g,h[l]),g+=2);v(n)}function E(t,n,a,c,d,b){x(t,n,a,c,e,o,d,b,0,0,1,0,8),x(t,n,a,c,s,p,d,b,1,0,1,0,8),x(t,n,a,c,r,h,d,b,2,1,0,3,0),x(t,n,a,c,l,m,d,b,0,0,0,3,2),x(t,n,a,c,i,f,d,b,1,0,0,3,2),x(t,n,a,c,u,g,d,b,2,1,0,3,0)}function k(t,r,i,n,a,s){var h=s.length,l=t.l;a+1==t.s&&(l=t.e-a*t.l);for(var f=6*t.e*n+a*t.l,u=0;u<6;u++){for(var c=0;c>>1):2==m?p+(u>>>1):o+u;var g=t.h?(2*c/3&2147483646|c%3&1)+(c%3>>>1):c>>>1;r[f+c]=i[d][g+1]}f+=t.e}}t._decompressRAF=function(o,s){var h=function(e){var r=t._binBE.readUshort,i={b:r(e,0),i:e[2],C:e[3],u:e[4],q:r(e,5),k:r(e,7),e:r(e,9),l:r(e,11),s:e[13],d:r(e,14)};if(18771!=i.b||i.i>1||i.q<6||i.q%6||i.e<768||i.e%24||768!=i.l||i.k=i.l||i.s>16||i.s!=i.k/i.l||i.s!=Math.ceil(i.e/i.l)||i.d!=i.q/6||12!=i.u&&14!=i.u&&16!=i.u||16!=i.C&&0!=i.C)throw"Invalid data";if(0==i.i)throw"Not implemented. We need this file!";return i.h=16==i.C,i.m=0|(i.h?2*i.l/3:i.l>>>1),i.A=i.m+2,i.f=64,i.g=(1<{"use strict";r.r(e),r.d(e,{DOMException:()=>v,Headers:()=>f,Request:()=>b,Response:()=>y,fetch:()=>x});var i="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==i&&i,n={searchParams:"URLSearchParams"in i,iterable:"Symbol"in i&&"iterator"in Symbol,blob:"FileReader"in i&&"Blob"in i&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in i,arrayBuffer:"ArrayBuffer"in i};if(n.arrayBuffer)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],o=ArrayBuffer.isView||function(t){return t&&a.indexOf(Object.prototype.toString.call(t))>-1};function s(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||""===t)throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function h(t){return"string"!=typeof t&&(t=String(t)),t}function l(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return n.iterable&&(e[Symbol.iterator]=function(){return e}),e}function f(t){this.map={},t instanceof f?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function u(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function c(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function d(t){var e=new FileReader,r=c(e);return e.readAsArrayBuffer(t),r}function p(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(t){var e;this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:n.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:n.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:n.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():n.arrayBuffer&&n.blob&&(e=t)&&DataView.prototype.isPrototypeOf(e)?(this._bodyArrayBuffer=p(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):n.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||o(t))?this._bodyArrayBuffer=p(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},n.blob&&(this.blob=function(){var t=u(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?u(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer)):this.blob().then(d)}),this.text=function(){var t,e,r,i=u(this);if(i)return i;if(this._bodyBlob)return t=this._bodyBlob,r=c(e=new FileReader),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),i=0;i-1?i:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(n),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==e.cache&&"no-cache"!==e.cache)){var a=/([?&])_=[^&]*/;a.test(this.url)?this.url=this.url.replace(a,"$1_="+(new Date).getTime()):this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}function _(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),i=r.shift().replace(/\+/g," "),n=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(i),decodeURIComponent(n))}})),e}function y(t,e){if(!(this instanceof y))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText=void 0===e.statusText?"":""+e.statusText,this.headers=new f(e.headers),this.url=e.url||"",this._initBody(t)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},m.call(b.prototype),m.call(y.prototype),y.prototype.clone=function(){return new y(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},y.error=function(){var t=new y(null,{status:0,statusText:""});return t.type="error",t};var w=[301,302,303,307,308];y.redirect=function(t,e){if(-1===w.indexOf(e))throw new RangeError("Invalid status code");return new y(null,{status:e,headers:{location:t}})};var v=i.DOMException;try{new v}catch(t){(v=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack}).prototype=Object.create(Error.prototype),v.prototype.constructor=v}function x(t,e){return new Promise((function(r,a){var o=new b(t,e);if(o.signal&&o.signal.aborted)return a(new v("Aborted","AbortError"));var s=new XMLHttpRequest;function l(){s.abort()}s.onload=function(){var t,e,i={status:s.status,statusText:s.statusText,headers:(t=s.getAllResponseHeaders()||"",e=new f,t.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(t){return 0===t.indexOf("\n")?t.substr(1,t.length):t})).forEach((function(t){var r=t.split(":"),i=r.shift().trim();if(i){var n=r.join(":").trim();e.append(i,n)}})),e)};i.url="responseURL"in s?s.responseURL:i.headers.get("X-Request-URL");var n="response"in s?s.response:s.responseText;setTimeout((function(){r(new y(n,i))}),0)},s.onerror=function(){setTimeout((function(){a(new TypeError("Network request failed"))}),0)},s.ontimeout=function(){setTimeout((function(){a(new TypeError("Network request failed"))}),0)},s.onabort=function(){setTimeout((function(){a(new v("Aborted","AbortError"))}),0)},s.open(o.method,function(t){try{return""===t&&i.location.href?i.location.href:t}catch(e){return t}}(o.url),!0),"include"===o.credentials?s.withCredentials=!0:"omit"===o.credentials&&(s.withCredentials=!1),"responseType"in s&&(n.blob?s.responseType="blob":n.arrayBuffer&&o.headers.get("Content-Type")&&-1!==o.headers.get("Content-Type").indexOf("application/octet-stream")&&(s.responseType="arraybuffer")),!e||"object"!=typeof e.headers||e.headers instanceof f?o.headers.forEach((function(t,e){s.setRequestHeader(e,t)})):Object.getOwnPropertyNames(e.headers).forEach((function(t){s.setRequestHeader(t,h(e.headers[t]))})),o.signal&&(o.signal.addEventListener("abort",l),s.onreadystatechange=function(){4===s.readyState&&o.signal.removeEventListener("abort",l)}),s.send(void 0===o._bodyInit?null:o._bodyInit)}))}x.polyfill=!0,i.fetch||(i.fetch=x,i.Headers=f,i.Request=b,i.Response=y)},6290:(t,e,r)=>{"use strict";var i=r(5048),n=r(9748),a=r(4655),o=r(1960);function s(t,e,r){var i=t;return n(e)?(r=e,"string"==typeof t&&(i={uri:t})):i=o(e,{uri:t}),i.callback=r,i}function h(t,e,r){return l(e=s(t,e,r))}function l(t){if(void 0===t.callback)throw new Error("callback argument missing");var e=!1,r=function(r,i,n){e||(e=!0,t.callback(r,i,n))};function i(){var t=void 0;if(t=f.response?f.response:f.responseText||function(t){try{if("document"===t.responseType)return t.responseXML;var e=t.responseXML&&"parsererror"===t.responseXML.documentElement.nodeName;if(""===t.responseType&&!e)return t.responseXML}catch(t){}return null}(f),b)try{t=JSON.parse(t)}catch(t){}return t}function n(t){return clearTimeout(u),t instanceof Error||(t=new Error(""+(t||"Unknown XMLHttpRequest Error"))),t.statusCode=0,r(t,_)}function o(){if(!l){var e;clearTimeout(u),e=t.useXDR&&void 0===f.status?200:1223===f.status?204:f.status;var n=_,o=null;return 0!==e?(n={body:i(),statusCode:e,method:d,headers:{},url:c,rawRequest:f},f.getAllResponseHeaders&&(n.headers=a(f.getAllResponseHeaders()))):o=new Error("Internal XMLHttpRequest Error"),r(o,n,n.body)}}var s,l,f=t.xhr||null;f||(f=t.cors||t.useXDR?new h.XDomainRequest:new h.XMLHttpRequest);var u,c=f.url=t.uri||t.url,d=f.method=t.method||"GET",p=t.body||t.data,m=f.headers=t.headers||{},g=!!t.sync,b=!1,_={body:void 0,headers:{},statusCode:0,method:d,url:c,rawRequest:f};if("json"in t&&!1!==t.json&&(b=!0,m.accept||m.Accept||(m.Accept="application/json"),"GET"!==d&&"HEAD"!==d&&(m["content-type"]||m["Content-Type"]||(m["Content-Type"]="application/json"),p=JSON.stringify(!0===t.json?p:t.json))),f.onreadystatechange=function(){4===f.readyState&&setTimeout(o,0)},f.onload=o,f.onerror=n,f.onprogress=function(){},f.onabort=function(){l=!0},f.ontimeout=n,f.open(d,c,!g,t.username,t.password),g||(f.withCredentials=!!t.withCredentials),!g&&t.timeout>0&&(u=setTimeout((function(){if(!l){l=!0,f.abort("timeout");var t=new Error("XMLHttpRequest timeout");t.code="ETIMEDOUT",n(t)}}),t.timeout)),f.setRequestHeader)for(s in m)m.hasOwnProperty(s)&&f.setRequestHeader(s,m[s]);else if(t.headers&&!function(t){for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}(t.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in t&&(f.responseType=t.responseType),"beforeSend"in t&&"function"==typeof t.beforeSend&&t.beforeSend(f),f.send(p||null),f}t.exports=h,t.exports.default=h,h.XMLHttpRequest=i.XMLHttpRequest||function(){},h.XDomainRequest="withCredentials"in new h.XMLHttpRequest?h.XMLHttpRequest:i.XDomainRequest,function(t,e){for(var r=0;r{t.exports=void 0!==self.DOMParser?function(t){return(new self.DOMParser).parseFromString(t,"application/xml")}:void 0!==self.ActiveXObject&&new self.ActiveXObject("Microsoft.XMLDOM")?function(t){var e=new self.ActiveXObject("Microsoft.XMLDOM");return e.async="false",e.loadXML(t),e}:function(t){var e=document.createElement("div");return e.innerHTML=t,e}},1960:t=>{t.exports=function(){for(var t={},r=0;r{},6777:()=>{},5546:()=>{},2460:(t,e,r)=>{var i=r(4406),n=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,h=(t,e)=>{for(var r in e)n(t,r,{get:e[r],enumerable:!0})},l=(t=>(e,r)=>t&&t.get(e)||(r=((t,e,r,i)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let r of o(e))s.call(t,r)||n(t,r,{get:()=>e[r],enumerable:!(i=a(e,r))||i.enumerable});return t})(n({},"__esModule",{value:!0}),e),t&&t.set(e,r),r))("undefined"!=typeof WeakMap?new WeakMap:0),f=(t,e,r)=>(((t,e,r)=>{e in t?n(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r})(t,"symbol"!=typeof e?e+"":e,r),r),u={};h(u,{applyPalette:()=>te,applyPaletteSync:()=>$t,buildPalette:()=>Kt,buildPaletteSync:()=>Qt,constants:()=>c,conversion:()=>b,distance:()=>H,image:()=>Ct,palette:()=>ot,quality:()=>Wt,utils:()=>ct});var c={};h(c,{bt709:()=>d});var d={};h(d,{Y:()=>p,x:()=>m,y:()=>g});var p=(t=>(t[t.RED=.2126]="RED",t[t.GREEN=.7152]="GREEN",t[t.BLUE=.0722]="BLUE",t[t.WHITE=1]="WHITE",t))(p||{}),m=(t=>(t[t.RED=.64]="RED",t[t.GREEN=.3]="GREEN",t[t.BLUE=.15]="BLUE",t[t.WHITE=.3127]="WHITE",t))(m||{}),g=(t=>(t[t.RED=.33]="RED",t[t.GREEN=.6]="GREEN",t[t.BLUE=.06]="BLUE",t[t.WHITE=.329]="WHITE",t))(g||{}),b={};function _(t){return t>.04045?((t+.055)/1.055)**2.4:t/12.92}function y(t,e,r){return{x:.4124*(t=_(t/255))+.3576*(e=_(e/255))+.1805*(r=_(r/255)),y:.2126*t+.7152*e+.0722*r,z:.0193*t+.1192*e+.9505*r}}h(b,{lab2rgb:()=>G,lab2xyz:()=>N,rgb2hsl:()=>I,rgb2lab:()=>L,rgb2xyz:()=>y,xyz2lab:()=>O,xyz2rgb:()=>j});var w={};function v(t){return t*(Math.PI/180)}function x(t,e,r){let i=t;return ie&&(i=e),i>r&&(i=r),i}function k(t,e,r){return t>r&&(t=r),t255?t=255:t<0&&(t=0),t}function M(t){return t>255?t=255:t<0&&(t=0),t}function A(t,e){const r=typeof t[0];let i;if("number"===r||"string"===r){const r=Object.create(null);for(let e=0,i=t.length;ee(t,i)||r[t]-r[i]))}else{const r=t.slice(0);i=t.sort(((t,i)=>e(t,i)||r.indexOf(t)-r.indexOf(i)))}return i}function I(t,e,r){const i=E(t,e,r),n=x(t,e,r),a=n-i,o=(i+n)/510;let s=0;o>0&&o<1&&(s=a/(o<.5?n+i:510-n-i));let h=0;return a>0&&(h=n===t?(e-r)/a:n===e?2+(r-t)/a:4+(t-e)/a,h*=60,h<0&&(h+=360)),{h,s,l:o}}h(w,{degrees2radians:()=>v,inRange0to255:()=>M,inRange0to255Rounded:()=>S,intInRange:()=>k,max3:()=>x,min3:()=>E,stableSort:()=>A});var B=.95047,T=1,R=1.08883;function P(t){return t>.008856?t**(1/3):7.787*t+16/116}function O(t,e,r){if(t=P(t/B),e=P(e/T),r=P(r/R),116*e-16<0)throw new Error("xxx");return{L:Math.max(0,116*e-16),a:500*(t-e),b:200*(e-r)}}function L(t,e,r){const i=y(t,e,r);return O(i.x,i.y,i.z)}var C=.95047,U=1,z=1.08883;function D(t){return t>.206893034?t**3:(t-16/116)/7.787}function N(t,e,r){const i=(t+16)/116,n=i-r/200;return{x:C*D(e/500+i),y:U*D(i),z:z*D(n)}}function F(t){return t>.0031308?1.055*t**(1/2.4)-.055:12.92*t}function j(t,e,r){const i=F(3.2406*t+-1.5372*e+-.4986*r),n=F(-.9689*t+1.8758*e+.0415*r),a=F(.0557*t+-.204*e+1.057*r);return{r:S(255*i),g:S(255*n),b:S(255*a)}}function G(t,e,r){const i=N(t,e,r);return j(i.x,i.y,i.z)}var H={};h(H,{AbstractDistanceCalculator:()=>W,AbstractEuclidean:()=>Q,AbstractManhattan:()=>et,CIE94GraphicArts:()=>Y,CIE94Textiles:()=>Z,CIEDE2000:()=>X,CMetric:()=>J,Euclidean:()=>K,EuclideanBT709:()=>$,EuclideanBT709NoAlpha:()=>tt,Manhattan:()=>rt,ManhattanBT709:()=>nt,ManhattanNommyde:()=>it,PNGQuant:()=>at});var W=class{constructor(){f(this,"_maxDistance"),f(this,"_whitePoint"),this._setDefaults(),this.setWhitePoint(255,255,255,255)}setWhitePoint(t,e,r,i){this._whitePoint={r:t>0?255/t:0,g:e>0?255/e:0,b:r>0?255/r:0,a:i>0?255/i:0},this._maxDistance=this.calculateRaw(t,e,r,i,0,0,0,0)}calculateNormalized(t,e){return this.calculateRaw(t.r,t.g,t.b,t.a,e.r,e.g,e.b,e.a)/this._maxDistance}},q=class extends W{calculateRaw(t,e,r,i,n,a,o,s){const h=L(M(t*this._whitePoint.r),M(e*this._whitePoint.g),M(r*this._whitePoint.b)),l=L(M(n*this._whitePoint.r),M(a*this._whitePoint.g),M(o*this._whitePoint.b)),f=h.L-l.L,u=h.a-l.a,c=h.b-l.b,d=Math.sqrt(h.a*h.a+h.b*h.b),p=d-Math.sqrt(l.a*l.a+l.b*l.b);let m=u*u+c*c-p*p;m=m<0?0:Math.sqrt(m);const g=(s-i)*this._whitePoint.a*this._kA;return Math.sqrt((f/this._Kl)**2+(p/(1+this._K1*d))**2+(m/(1+this._K2*d))**2+g**2)}},Z=class extends q{_setDefaults(){this._Kl=2,this._K1=.048,this._K2=.014,this._kA=12.5/255}},Y=class extends q{_setDefaults(){this._Kl=1,this._K1=.045,this._K2=.015,this._kA=25/255}},V=class extends W{_setDefaults(){}static _calculatehp(t,e){const r=Math.atan2(t,e);return r>=0?r:r+V._deg360InRad}static _calculateRT(t,e){const r=e**7,i=2*Math.sqrt(r/(r+V._pow25to7)),n=V._deg30InRad*Math.exp(-(((t-V._deg275InRad)/V._deg25InRad)**2));return-Math.sin(2*n)*i}static _calculateT(t){return 1-.17*Math.cos(t-V._deg30InRad)+.24*Math.cos(2*t)+.32*Math.cos(3*t+V._deg6InRad)-.2*Math.cos(4*t-V._deg63InRad)}static _calculate_ahp(t,e,r,i){const n=r+i;return 0===t?n:e<=V._deg180InRad?n/2:n>8)+4*f*f+((767-h)*u*u>>8),d=(s-i)*this._whitePoint.a;return Math.sqrt(c+d*d)}_setDefaults(){}},Q=class extends W{calculateRaw(t,e,r,i,n,a,o,s){const h=n-t,l=a-e,f=o-r,u=s-i;return Math.sqrt(this._kR*h*h+this._kG*l*l+this._kB*f*f+this._kA*u*u)}},K=class extends Q{_setDefaults(){this._kR=1,this._kG=1,this._kB=1,this._kA=1}},$=class extends Q{_setDefaults(){this._kR=.2126,this._kG=.7152,this._kB=.0722,this._kA=1}},tt=class extends Q{_setDefaults(){this._kR=.2126,this._kG=.7152,this._kB=.0722,this._kA=0}},et=class extends W{calculateRaw(t,e,r,i,n,a,o,s){let h=n-t,l=a-e,f=o-r,u=s-i;return h<0&&(h=0-h),l<0&&(l=0-l),f<0&&(f=0-f),u<0&&(u=0-u),this._kR*h+this._kG*l+this._kB*f+this._kA*u}},rt=class extends et{_setDefaults(){this._kR=1,this._kG=1,this._kB=1,this._kA=1}},it=class extends et{_setDefaults(){this._kR=.4984,this._kG=.8625,this._kB=.2979,this._kA=1}},nt=class extends et{_setDefaults(){this._kR=.2126,this._kG=.7152,this._kB=.0722,this._kA=1}},at=class extends W{calculateRaw(t,e,r,i,n,a,o,s){const h=(s-i)*this._whitePoint.a;return this._colordifferenceCh(t*this._whitePoint.r,n*this._whitePoint.r,h)+this._colordifferenceCh(e*this._whitePoint.g,a*this._whitePoint.g,h)+this._colordifferenceCh(r*this._whitePoint.b,o*this._whitePoint.b,h)}_colordifferenceCh(t,e,r){const i=t-e,n=i+r;return i*i+n*n}_setDefaults(){}},ot={};h(ot,{AbstractPaletteQuantizer:()=>st,ColorHistogram:()=>kt,NeuQuant:()=>yt,NeuQuantFloat:()=>xt,RGBQuant:()=>Mt,WuColorCube:()=>Pt,WuQuant:()=>Lt});var st=class{quantizeSync(){for(const t of this.quantize())if(t.palette)return t.palette;throw new Error("unreachable")}},ht=class{constructor(){f(this,"r"),f(this,"g"),f(this,"b"),f(this,"a"),f(this,"uint32"),f(this,"rgba"),this.uint32=-1>>>0,this.r=this.g=this.b=this.a=0,this.rgba=new Array(4),this.rgba[0]=0,this.rgba[1]=0,this.rgba[2]=0,this.rgba[3]=0}static createByQuadruplet(t){const e=new ht;return e.r=0|t[0],e.g=0|t[1],e.b=0|t[2],e.a=0|t[3],e._loadUINT32(),e._loadQuadruplet(),e}static createByRGBA(t,e,r,i){const n=new ht;return n.r=0|t,n.g=0|e,n.b=0|r,n.a=0|i,n._loadUINT32(),n._loadQuadruplet(),n}static createByUint32(t){const e=new ht;return e.uint32=t>>>0,e._loadRGBA(),e._loadQuadruplet(),e}from(t){this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this.uint32=t.uint32,this.rgba[0]=t.r,this.rgba[1]=t.g,this.rgba[2]=t.b,this.rgba[3]=t.a}getLuminosity(t){let e=this.r,r=this.g,i=this.b;return t&&(e=Math.min(255,255-this.a+this.a*e/255),r=Math.min(255,255-this.a+this.a*r/255),i=Math.min(255,255-this.a+this.a*i/255)),.2126*e+.7152*r+.0722*i}_loadUINT32(){this.uint32=(this.a<<24|this.b<<16|this.g<<8|this.r)>>>0}_loadRGBA(){this.r=255&this.uint32,this.g=this.uint32>>>8&255,this.b=this.uint32>>>16&255,this.a=this.uint32>>>24&255}_loadQuadruplet(){this.rgba[0]=this.r,this.rgba[1]=this.g,this.rgba[2]=this.b,this.rgba[3]=this.a}},lt=class{constructor(){f(this,"_pointArray"),f(this,"_width"),f(this,"_height"),this._width=0,this._height=0,this._pointArray=[]}getWidth(){return this._width}getHeight(){return this._height}setWidth(t){this._width=t}setHeight(t){this._height=t}getPointArray(){return this._pointArray}clone(){const t=new lt;t._width=this._width,t._height=this._height;for(let e=0,r=this._pointArray.length;e=n&&t=0;e--)if(t.uint32===this._pointArray[e].uint32)return!0;return!1}getNearestColor(t,e){return this._pointArray[0|this._getNearestIndex(t,e)]}getPointContainer(){return this._pointContainer}_nearestPointFromCache(t){return"number"==typeof this._i32idx[t]?this._i32idx[t]:-1}_getNearestIndex(t,e){let r=this._nearestPointFromCache(""+e.uint32);if(r>=0)return r;let i=Number.MAX_VALUE;r=0;for(let n=0,a=this._pointArray.length;n{const r=I(t.r,t.g,t.b),i=I(e.r,e.g,e.b),n=t.r===t.g&&t.g===t.b?0:1+ft(r.h,10),a=(e.r===e.g&&e.g===e.b?0:1+ft(i.h,10))-n;if(a)return-a;const o=t.getLuminosity(!0),s=e.getLuminosity(!0);if(s-o!=0)return s-o;const h=(100*i.s|0)-(100*r.s|0);return h?-h:0}))}},ct={};h(ct,{HueStatistics:()=>pt,Palette:()=>ut,Point:()=>ht,PointContainer:()=>lt,ProgressTracker:()=>gt,arithmetic:()=>w});var dt=class{constructor(){f(this,"num",0),f(this,"cols",[])}},pt=class{constructor(t,e){f(this,"_numGroups"),f(this,"_minCols"),f(this,"_stats"),f(this,"_groupsFull"),this._numGroups=t,this._minCols=e,this._stats=[];for(let e=0;e<=t;e++)this._stats[e]=new dt;this._groupsFull=0}check(t){this._groupsFull===this._numGroups+1&&(this.check=()=>{});const e=255&t,r=t>>>8&255,i=t>>>16&255,n=e===r&&r===i?0:1+ft(I(e,r,i).h,this._numGroups),a=this._stats[n],o=this._minCols;a.num++,a.num>o||(a.num===o&&this._groupsFull++,a.num<=o&&this._stats[n].cols.push(t))}injectIntoDictionary(t){for(let e=0;e<=this._numGroups;e++)this._stats[e].num<=this._minCols&&this._stats[e].cols.forEach((e=>{t[e]?t[e]++:t[e]=1}))}injectIntoArray(t){for(let e=0;e<=this._numGroups;e++)this._stats[e].num<=this._minCols&&this._stats[e].cols.forEach((e=>{-1===t.indexOf(e)&&t.push(e)}))}},mt=class{constructor(t,e){f(this,"progress"),f(this,"_step"),f(this,"_range"),f(this,"_last"),f(this,"_progressRange"),this._range=t,this._progressRange=e,this._step=Math.max(1,this._range/(mt.steps+1)|0),this._last=-this._step,this.progress=0}shouldNotify(t){return t-this._last>=this._step&&(this._last=t,this.progress=Math.min(this._progressRange*this._last/this._range,this._progressRange),!0)}},gt=mt;f(gt,"steps",100);var bt=class{constructor(t){f(this,"r"),f(this,"g"),f(this,"b"),f(this,"a"),this.r=this.g=this.b=this.a=t}toPoint(){return ht.createByRGBA(this.r>>3,this.g>>3,this.b>>3,this.a>>3)}subtract(t,e,r,i){this.r-=0|t,this.g-=0|e,this.b-=0|r,this.a-=0|i}},_t=class extends st{constructor(t,e=256){super(),f(this,"_pointArray"),f(this,"_networkSize"),f(this,"_network"),f(this,"_sampleFactor"),f(this,"_radPower"),f(this,"_freq"),f(this,"_bias"),f(this,"_distance"),this._distance=t,this._pointArray=[],this._sampleFactor=1,this._networkSize=e,this._distance.setWhitePoint(2040,2040,2040,2040)}sample(t){this._pointArray=this._pointArray.concat(t.getPointArray())}*quantize(){this._init(),yield*this._learn(),yield{palette:this._buildPalette(),progress:100}}_init(){this._freq=[],this._bias=[],this._radPower=[],this._network=[];for(let t=0;t>3)*_t._radiusBias,h=s>>_t._radiusBiasShift;h<=1&&(h=0);for(let t=0;t>>0;n=e<_t._minpicturebytes?1:e%_t._prime1!=0?_t._prime1:e%_t._prime2!=0?_t._prime2:e%_t._prime3!=0?_t._prime3:_t._prime4;const l=new gt(i,99);for(let t=0,f=0;t=e&&(f-=e),t++,0===a&&(a=1),t%a==0){o-=o/r|0,s-=s/_t._radiusDecrease|0,h=s>>_t._radiusBiasShift,h<=1&&(h=0);for(let t=0;t>>0}}}_buildPalette(){const t=new ut;return this._network.forEach((e=>{t.add(e.toPoint())})),t.sort(),t}_alterNeighbour(t,e,r,i,n,a){let o=e-t;o<-1&&(o=-1);let s=e+t;s>this._networkSize&&(s=this._networkSize);let h=e+1,l=e-1,f=1;for(;ho;){const t=this._radPower[f++]/_t._alphaRadBias;if(ho){const e=this._network[l--];e.subtract(t*(e.r-n),t*(e.g-i),t*(e.b-r),t*(e.a-a))}}}_alterSingle(t,e,r,i,n,a){t/=_t._initAlpha;const o=this._network[e];o.subtract(t*(o.r-n),t*(o.g-i),t*(o.b-r),t*(o.a-a))}_contest(t,e,r,i){let n=~(1<<31),a=n,o=-1,s=o;for(let h=0;h>_t._initialBiasShift-3);u>_t._betaShift;this._freq[h]-=c,this._bias[h]+=c<<_t._gammaShift}return this._freq[o]+=_t._beta,this._bias[o]-=_t._betaGamma,s}},yt=_t;f(yt,"_prime1",499),f(yt,"_prime2",491),f(yt,"_prime3",487),f(yt,"_prime4",503),f(yt,"_minpicturebytes",_t._prime4),f(yt,"_nCycles",100),f(yt,"_initialBiasShift",16),f(yt,"_initialBias",1<<_t._initialBiasShift),f(yt,"_gammaShift",10),f(yt,"_betaShift",10),f(yt,"_beta",_t._initialBias>>_t._betaShift),f(yt,"_betaGamma",_t._initialBias<<_t._gammaShift-_t._betaShift),f(yt,"_radiusBiasShift",6),f(yt,"_radiusBias",1<<_t._radiusBiasShift),f(yt,"_radiusDecrease",30),f(yt,"_alphaBiasShift",10),f(yt,"_initAlpha",1<<_t._alphaBiasShift),f(yt,"_radBiasShift",8),f(yt,"_radBias",1<<_t._radBiasShift),f(yt,"_alphaRadBiasShift",_t._alphaBiasShift+_t._radBiasShift),f(yt,"_alphaRadBias",1<<_t._alphaRadBiasShift);var wt=class{constructor(t){f(this,"r"),f(this,"g"),f(this,"b"),f(this,"a"),this.r=this.g=this.b=this.a=t}toPoint(){return ht.createByRGBA(this.r>>3,this.g>>3,this.b>>3,this.a>>3)}subtract(t,e,r,i){this.r-=t,this.g-=e,this.b-=r,this.a-=i}},vt=class extends st{constructor(t,e=256){super(),f(this,"_pointArray"),f(this,"_networkSize"),f(this,"_network"),f(this,"_sampleFactor"),f(this,"_radPower"),f(this,"_freq"),f(this,"_bias"),f(this,"_distance"),this._distance=t,this._pointArray=[],this._sampleFactor=1,this._networkSize=e,this._distance.setWhitePoint(2040,2040,2040,2040)}sample(t){this._pointArray=this._pointArray.concat(t.getPointArray())}*quantize(){this._init(),yield*this._learn(),yield{palette:this._buildPalette(),progress:100}}_init(){this._freq=[],this._bias=[],this._radPower=[],this._network=[];for(let t=0;t>3)*vt._radiusBias,h=s>>vt._radiusBiasShift;h<=1&&(h=0);for(let t=0;t=e&&(f-=e),t++,0===a&&(a=1),t%a==0){o-=o/r,s-=s/vt._radiusDecrease,h=s>>vt._radiusBiasShift,h<=1&&(h=0);for(let t=0;t{t.add(e.toPoint())})),t.sort(),t}_alterNeighbour(t,e,r,i,n,a){let o=e-t;o<-1&&(o=-1);let s=e+t;s>this._networkSize&&(s=this._networkSize);let h=e+1,l=e-1,f=1;for(;ho;){const t=this._radPower[f++]/vt._alphaRadBias;if(ho){const e=this._network[l--];e.subtract(t*(e.r-n),t*(e.g-i),t*(e.b-r),t*(e.a-a))}}}_alterSingle(t,e,r,i,n,a){t/=vt._initAlpha;const o=this._network[e];o.subtract(t*(o.r-n),t*(o.g-i),t*(o.b-r),t*(o.a-a))}_contest(t,e,r,i){let n=~(1<<31),a=n,o=-1,s=o;for(let h=0;h>vt._initialBiasShift-3);u>vt._betaShift;this._freq[h]-=c,this._bias[h]+=c<>vt._betaShift),f(xt,"_betaGamma",vt._initialBias<this._histogram[e]-this._histogram[t]));if(0===t.length)return[];let e;switch(this._method){case 1:const r=Math.min(t.length,this._initColors),i=t[r-1],n=this._histogram[i];e=t.slice(0,r);let a=r;const o=t.length;for(;a+t))}_colorStats1D(t){const e=this._histogram,r=t.getPointArray(),i=r.length;for(let t=0;t{let r=Math.round(t.w*t.h/o)*Et._boxPixels;r<2&&(r=2);const n={};this._iterateBox(t,e,(t=>{const e=i[t].uint32;this._hueStats.check(e),e in h?h[e]++:e in n?++n[e]>=r&&(h[e]=n[e]):n[e]=1}))})),this._hueStats.injectIntoDictionary(h)}_iterateBox(t,e,r){const i=t,n=i.y*e+i.x,a=(i.y+i.h-1)*e+(i.x+i.w-1),o=e-i.w+1;let s=0,h=n;do{r.call(this,h),h+=++s%i.w==0?o:1}while(h<=a)}_makeBoxes(t,e,r,i){const n=t%r,a=e%i,o=t-n,s=e-a,h=[];for(let l=0;lthis._colors;){a.length=0;for(let t=0;t3*this._colors?this._initialDistance:this._distanceIncrement}if(oe.distance-t.distance));let t=0;for(;o=0;t--)0===i[t]&&(t!==l-1&&(r[t]=r[l-1]),--l);r.length=l,e.sort(),yield{palette:e,progress:100}}};function At(t){const e=[];for(let r=0;r0){const r=this._sums[e],i=this._reds[e]/r,n=this._greens[e]/r,a=this._blues[e]/r,o=this._alphas[e]/r,s=ht.createByRGBA(0|i,0|n,0|a,0|o);t.add(s)}t.sort(),yield{palette:t,progress:100}}*_preparePalette(){yield*this._calculateMoments();let t=0;const e=At(this._colors);for(let r=1;r1?this._calculateVariance(this._cubes[t]):0,e[r]=this._cubes[r].volume>1?this._calculateVariance(this._cubes[r]):0):(e[t]=0,r--),t=0;let i=e[0];for(let n=1;n<=r;++n)e[n]>i&&(i=e[n],t=n);if(i<=0){this._colors=r+1;break}}const r=[],i=[],n=[],a=[];for(let t=0;t0?(r[t]=Ot._volume(this._cubes[t],this._momentsRed)/e|0,i[t]=Ot._volume(this._cubes[t],this._momentsGreen)/e|0,n[t]=Ot._volume(this._cubes[t],this._momentsBlue)/e|0,a[t]=Ot._volume(this._cubes[t],this._momentsAlpha)/e|0):(r[t]=0,i[t]=0,n[t]=0,a[t]=0)}this._reds=At(this._colors+1),this._greens=At(this._colors+1),this._blues=At(this._colors+1),this._alphas=At(this._colors+1),this._sums=At(this._colors+1);for(let t=0,e=this._pixels.length;t>e),i=1+(t.g>>e),n=1+(t.b>>e),a=1+(t.a>>e);this._weights[a][r][i][n]++,this._momentsRed[a][r][i][n]+=t.r,this._momentsGreen[a][r][i][n]+=t.g,this._momentsBlue[a][r][i][n]+=t.b,this._momentsAlpha[a][r][i][n]+=t.a,this._moments[a][r][i][n]+=this._table[t.r]+this._table[t.g]+this._table[t.b]+this._table[t.a]}*_calculateMoments(){const t=[],e=[],r=[],i=[],n=[],a=[],o=Bt(this._sideSize,this._sideSize,this._sideSize),s=Bt(this._sideSize,this._sideSize,this._sideSize),h=Bt(this._sideSize,this._sideSize,this._sideSize),l=Bt(this._sideSize,this._sideSize,this._sideSize),f=Bt(this._sideSize,this._sideSize,this._sideSize),u=Bt(this._sideSize,this._sideSize,this._sideSize);let c=0;const d=new gt(this._alphaMaxSideIndex*this._maxSideIndex,99);for(let p=1;p<=this._alphaMaxSideIndex;++p){Tt(o,this._sideSize,this._sideSize,this._sideSize,0),Tt(s,this._sideSize,this._sideSize,this._sideSize,0),Tt(h,this._sideSize,this._sideSize,this._sideSize,0),Tt(l,this._sideSize,this._sideSize,this._sideSize,0),Tt(f,this._sideSize,this._sideSize,this._sideSize,0),Tt(u,this._sideSize,this._sideSize,this._sideSize,0);for(let m=1;m<=this._maxSideIndex;++m,++c){d.shouldNotify(c)&&(yield{progress:d.progress}),Rt(t,this._sideSize,0),Rt(e,this._sideSize,0),Rt(r,this._sideSize,0),Rt(i,this._sideSize,0),Rt(n,this._sideSize,0),Rt(a,this._sideSize,0);for(let c=1;c<=this._maxSideIndex;++c){let d=0,g=0,b=0,_=0,y=0,w=0;for(let v=1;v<=this._maxSideIndex;++v)d+=this._weights[p][m][c][v],g+=this._momentsRed[p][m][c][v],b+=this._momentsGreen[p][m][c][v],_+=this._momentsBlue[p][m][c][v],y+=this._momentsAlpha[p][m][c][v],w+=this._moments[p][m][c][v],t[v]+=d,e[v]+=g,r[v]+=b,i[v]+=_,n[v]+=y,a[v]+=w,o[m][c][v]=o[m-1][c][v]+t[v],s[m][c][v]=s[m-1][c][v]+e[v],h[m][c][v]=h[m-1][c][v]+r[v],l[m][c][v]=l[m-1][c][v]+i[v],f[m][c][v]=f[m-1][c][v]+n[v],u[m][c][v]=u[m-1][c][v]+a[v],this._weights[p][m][c][v]=this._weights[p-1][m][c][v]+o[m][c][v],this._momentsRed[p][m][c][v]=this._momentsRed[p-1][m][c][v]+s[m][c][v],this._momentsGreen[p][m][c][v]=this._momentsGreen[p-1][m][c][v]+h[m][c][v],this._momentsBlue[p][m][c][v]=this._momentsBlue[p-1][m][c][v]+l[m][c][v],this._momentsAlpha[p][m][c][v]=this._momentsAlpha[p-1][m][c][v]+f[m][c][v],this._moments[p][m][c][v]=this._moments[p-1][m][c][v]+u[m][c][v]}}}}static _volumeFloat(t,e){return e[t.alphaMaximum][t.redMaximum][t.greenMaximum][t.blueMaximum]-e[t.alphaMaximum][t.redMaximum][t.greenMinimum][t.blueMaximum]-e[t.alphaMaximum][t.redMinimum][t.greenMaximum][t.blueMaximum]+e[t.alphaMaximum][t.redMinimum][t.greenMinimum][t.blueMaximum]-e[t.alphaMinimum][t.redMaximum][t.greenMaximum][t.blueMaximum]+e[t.alphaMinimum][t.redMaximum][t.greenMinimum][t.blueMaximum]+e[t.alphaMinimum][t.redMinimum][t.greenMaximum][t.blueMaximum]-e[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMaximum]-(e[t.alphaMaximum][t.redMaximum][t.greenMaximum][t.blueMinimum]-e[t.alphaMinimum][t.redMaximum][t.greenMaximum][t.blueMinimum]-e[t.alphaMaximum][t.redMaximum][t.greenMinimum][t.blueMinimum]+e[t.alphaMinimum][t.redMaximum][t.greenMinimum][t.blueMinimum]-e[t.alphaMaximum][t.redMinimum][t.greenMaximum][t.blueMinimum]+e[t.alphaMinimum][t.redMinimum][t.greenMaximum][t.blueMinimum]+e[t.alphaMaximum][t.redMinimum][t.greenMinimum][t.blueMinimum]-e[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMinimum])}static _volume(t,e){return 0|Ot._volumeFloat(t,e)}static _top(t,e,r,i){let n;switch(e){case Ot._alpha:n=i[r][t.redMaximum][t.greenMaximum][t.blueMaximum]-i[r][t.redMaximum][t.greenMinimum][t.blueMaximum]-i[r][t.redMinimum][t.greenMaximum][t.blueMaximum]+i[r][t.redMinimum][t.greenMinimum][t.blueMaximum]-(i[r][t.redMaximum][t.greenMaximum][t.blueMinimum]-i[r][t.redMaximum][t.greenMinimum][t.blueMinimum]-i[r][t.redMinimum][t.greenMaximum][t.blueMinimum]+i[r][t.redMinimum][t.greenMinimum][t.blueMinimum]);break;case Ot._red:n=i[t.alphaMaximum][r][t.greenMaximum][t.blueMaximum]-i[t.alphaMaximum][r][t.greenMinimum][t.blueMaximum]-i[t.alphaMinimum][r][t.greenMaximum][t.blueMaximum]+i[t.alphaMinimum][r][t.greenMinimum][t.blueMaximum]-(i[t.alphaMaximum][r][t.greenMaximum][t.blueMinimum]-i[t.alphaMaximum][r][t.greenMinimum][t.blueMinimum]-i[t.alphaMinimum][r][t.greenMaximum][t.blueMinimum]+i[t.alphaMinimum][r][t.greenMinimum][t.blueMinimum]);break;case Ot._green:n=i[t.alphaMaximum][t.redMaximum][r][t.blueMaximum]-i[t.alphaMaximum][t.redMinimum][r][t.blueMaximum]-i[t.alphaMinimum][t.redMaximum][r][t.blueMaximum]+i[t.alphaMinimum][t.redMinimum][r][t.blueMaximum]-(i[t.alphaMaximum][t.redMaximum][r][t.blueMinimum]-i[t.alphaMaximum][t.redMinimum][r][t.blueMinimum]-i[t.alphaMinimum][t.redMaximum][r][t.blueMinimum]+i[t.alphaMinimum][t.redMinimum][r][t.blueMinimum]);break;case Ot._blue:n=i[t.alphaMaximum][t.redMaximum][t.greenMaximum][r]-i[t.alphaMaximum][t.redMaximum][t.greenMinimum][r]-i[t.alphaMaximum][t.redMinimum][t.greenMaximum][r]+i[t.alphaMaximum][t.redMinimum][t.greenMinimum][r]-(i[t.alphaMinimum][t.redMaximum][t.greenMaximum][r]-i[t.alphaMinimum][t.redMaximum][t.greenMinimum][r]-i[t.alphaMinimum][t.redMinimum][t.greenMaximum][r]+i[t.alphaMinimum][t.redMinimum][t.greenMinimum][r]);break;default:throw new Error("impossible")}return 0|n}static _bottom(t,e,r){switch(e){case Ot._alpha:return-r[t.alphaMinimum][t.redMaximum][t.greenMaximum][t.blueMaximum]+r[t.alphaMinimum][t.redMaximum][t.greenMinimum][t.blueMaximum]+r[t.alphaMinimum][t.redMinimum][t.greenMaximum][t.blueMaximum]-r[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMaximum]-(-r[t.alphaMinimum][t.redMaximum][t.greenMaximum][t.blueMinimum]+r[t.alphaMinimum][t.redMaximum][t.greenMinimum][t.blueMinimum]+r[t.alphaMinimum][t.redMinimum][t.greenMaximum][t.blueMinimum]-r[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMinimum]);case Ot._red:return-r[t.alphaMaximum][t.redMinimum][t.greenMaximum][t.blueMaximum]+r[t.alphaMaximum][t.redMinimum][t.greenMinimum][t.blueMaximum]+r[t.alphaMinimum][t.redMinimum][t.greenMaximum][t.blueMaximum]-r[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMaximum]-(-r[t.alphaMaximum][t.redMinimum][t.greenMaximum][t.blueMinimum]+r[t.alphaMaximum][t.redMinimum][t.greenMinimum][t.blueMinimum]+r[t.alphaMinimum][t.redMinimum][t.greenMaximum][t.blueMinimum]-r[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMinimum]);case Ot._green:return-r[t.alphaMaximum][t.redMaximum][t.greenMinimum][t.blueMaximum]+r[t.alphaMaximum][t.redMinimum][t.greenMinimum][t.blueMaximum]+r[t.alphaMinimum][t.redMaximum][t.greenMinimum][t.blueMaximum]-r[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMaximum]-(-r[t.alphaMaximum][t.redMaximum][t.greenMinimum][t.blueMinimum]+r[t.alphaMaximum][t.redMinimum][t.greenMinimum][t.blueMinimum]+r[t.alphaMinimum][t.redMaximum][t.greenMinimum][t.blueMinimum]-r[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMinimum]);case Ot._blue:return-r[t.alphaMaximum][t.redMaximum][t.greenMaximum][t.blueMinimum]+r[t.alphaMaximum][t.redMaximum][t.greenMinimum][t.blueMinimum]+r[t.alphaMaximum][t.redMinimum][t.greenMaximum][t.blueMinimum]-r[t.alphaMaximum][t.redMinimum][t.greenMinimum][t.blueMinimum]-(-r[t.alphaMinimum][t.redMaximum][t.greenMaximum][t.blueMinimum]+r[t.alphaMinimum][t.redMaximum][t.greenMinimum][t.blueMinimum]+r[t.alphaMinimum][t.redMinimum][t.greenMaximum][t.blueMinimum]-r[t.alphaMinimum][t.redMinimum][t.greenMinimum][t.blueMinimum]);default:return 0}}_calculateVariance(t){const e=Ot._volume(t,this._momentsRed),r=Ot._volume(t,this._momentsGreen),i=Ot._volume(t,this._momentsBlue),n=Ot._volume(t,this._momentsAlpha);return Ot._volumeFloat(t,this._moments)-(e*e+r*r+i*i+n*n)/Ot._volume(t,this._weights)}_maximize(t,e,r,i,n,a,o,s,h){const l=0|Ot._bottom(t,e,this._momentsRed),f=0|Ot._bottom(t,e,this._momentsGreen),u=0|Ot._bottom(t,e,this._momentsBlue),c=0|Ot._bottom(t,e,this._momentsAlpha),d=0|Ot._bottom(t,e,this._weights);let p=0,m=-1;for(let g=r;gp&&(p=e,m=g))}}return{max:p,position:m}}_cut(t,e){let r;const i=Ot._volume(t,this._momentsRed),n=Ot._volume(t,this._momentsGreen),a=Ot._volume(t,this._momentsBlue),o=Ot._volume(t,this._momentsAlpha),s=Ot._volume(t,this._weights),h=this._maximize(t,Ot._red,t.redMinimum+1,t.redMaximum,i,n,a,o,s),l=this._maximize(t,Ot._green,t.greenMinimum+1,t.greenMaximum,i,n,a,o,s),f=this._maximize(t,Ot._blue,t.blueMinimum+1,t.blueMaximum,i,n,a,o,s),u=this._maximize(t,Ot._alpha,t.alphaMinimum+1,t.alphaMaximum,i,n,a,o,s);if(u.max>=h.max&&u.max>=l.max&&u.max>=f.max){if(r=Ot._alpha,u.position<0)return!1}else r=h.max>=u.max&&h.max>=l.max&&h.max>=f.max?Ot._red:l.max>=u.max&&l.max>=h.max&&l.max>=f.max?Ot._green:Ot._blue;switch(e.redMaximum=t.redMaximum,e.greenMaximum=t.greenMaximum,e.blueMaximum=t.blueMaximum,e.alphaMaximum=t.alphaMaximum,r){case Ot._red:e.redMinimum=t.redMaximum=h.position,e.greenMinimum=t.greenMinimum,e.blueMinimum=t.blueMinimum,e.alphaMinimum=t.alphaMinimum;break;case Ot._green:e.greenMinimum=t.greenMaximum=l.position,e.redMinimum=t.redMinimum,e.blueMinimum=t.blueMinimum,e.alphaMinimum=t.alphaMinimum;break;case Ot._blue:e.blueMinimum=t.blueMaximum=f.position,e.redMinimum=t.redMinimum,e.greenMinimum=t.greenMinimum,e.alphaMinimum=t.alphaMinimum;break;case Ot._alpha:e.alphaMinimum=t.alphaMaximum=u.position,e.blueMinimum=t.blueMinimum,e.redMinimum=t.redMinimum,e.greenMinimum=t.greenMinimum}return t.volume=(t.redMaximum-t.redMinimum)*(t.greenMaximum-t.greenMinimum)*(t.blueMaximum-t.blueMinimum)*(t.alphaMaximum-t.alphaMinimum),e.volume=(e.redMaximum-e.redMinimum)*(e.greenMaximum-e.greenMinimum)*(e.blueMaximum-e.blueMinimum)*(e.alphaMaximum-e.alphaMinimum),!0}_initialize(t){this._colors=t,this._cubes=[];for(let e=0;eUt,ErrorDiffusionArray:()=>Nt,ErrorDiffusionArrayKernel:()=>Dt,ErrorDiffusionRiemersma:()=>Ht,NearestColor:()=>zt});var Ut=class{quantizeSync(t,e){for(const r of this.quantize(t,e))if(r.pointContainer)return r.pointContainer;throw new Error("unreachable")}},zt=class extends Ut{constructor(t){super(),f(this,"_distance"),this._distance=t}*quantize(t,e){const r=t.getPointArray(),i=t.getWidth(),n=t.getHeight(),a=new gt(n,99);for(let t=0;t(t[t.FloydSteinberg=0]="FloydSteinberg",t[t.FalseFloydSteinberg=1]="FalseFloydSteinberg",t[t.Stucki=2]="Stucki",t[t.Atkinson=3]="Atkinson",t[t.Jarvis=4]="Jarvis",t[t.Burkes=5]="Burkes",t[t.Sierra=6]="Sierra",t[t.TwoSierra=7]="TwoSierra",t[t.SierraLite=8]="SierraLite",t))(Dt||{}),Nt=class extends Ut{constructor(t,e,r=!0,i=0,n=!1){super(),f(this,"_minColorDistance"),f(this,"_serpentine"),f(this,"_kernel"),f(this,"_calculateErrorLikeGIMP"),f(this,"_distance"),this._setKernel(e),this._distance=t,this._minColorDistance=i,this._serpentine=r,this._calculateErrorLikeGIMP=n}*quantize(t,e){const r=t.getPointArray(),i=new ht,n=t.getWidth(),a=t.getHeight(),o=[];let s=1,h=1;for(const t of this._kernel){const e=t[2]+1;h=0&&r+l=0&&i+te&&(t.length=e);const r=t.length;for(let e=0;e=0&&t.x=0&&t.y{const s=r[t+n*i];let{r:h,g:l,b:f,a:u}=s;for(let t=0;tYt});var qt=.01,Zt=.03;function Yt(t,e){if(t.getHeight()!==e.getHeight()||t.getWidth()!==e.getWidth())throw new Error("Images have different sizes!");const r=(255*qt)**2,i=(255*Zt)**2;let n=0,a=0;return function(t,e,r){const i=t.getWidth(),n=t.getHeight();for(let a=0;a{let h=0,l=0,f=0;for(let r=0;ri.nextTick(t):t=>setTimeout(t,0);function Qt(t,{colorDistanceFormula:e,paletteQuantization:r,colors:i}={}){const n=ie(ee(e),r,i);return t.forEach((t=>n.sample(t))),n.quantizeSync()}async function Kt(t,{colorDistanceFormula:e,paletteQuantization:r,colors:i,onProgress:n}={}){return new Promise(((a,o)=>{const s=ie(ee(e),r,i);let h;t.forEach((t=>s.sample(t)));const l=s.quantize(),f=()=>{try{const t=l.next();t.done?a(h):(t.value.palette&&(h=t.value.palette),n&&n(t.value.progress),Jt(f))}catch(t){o(t)}};Jt(f)}))}function $t(t,e,{colorDistanceFormula:r,imageQuantization:i}={}){return re(ee(r),i).quantizeSync(t,e)}async function te(t,e,{colorDistanceFormula:r,imageQuantization:i,onProgress:n}={}){return new Promise(((a,o)=>{let s;const h=re(ee(r),i).quantize(t,e),l=()=>{try{const t=h.next();t.done?a(s):(t.value.pointContainer&&(s=t.value.pointContainer),n&&n(t.value.progress),Jt(l))}catch(t){o(t)}};Jt(l)}))}function ee(t="euclidean-bt709"){switch(t){case"cie94-graphic-arts":return new Y;case"cie94-textiles":return new Z;case"ciede2000":return new X;case"color-metric":return new J;case"euclidean":return new K;case"euclidean-bt709":return new $;case"euclidean-bt709-noalpha":return new tt;case"manhattan":return new rt;case"manhattan-bt709":return new nt;case"manhattan-nommyde":return new it;case"pngquant":return new at;default:throw new Error(`Unknown colorDistanceFormula ${t}`)}}function re(t,e="floyd-steinberg"){switch(e){case"nearest":return new zt(t);case"riemersma":return new Ht(t);case"floyd-steinberg":return new Nt(t,0);case"false-floyd-steinberg":return new Nt(t,1);case"stucki":return new Nt(t,2);case"atkinson":return new Nt(t,3);case"jarvis":return new Nt(t,4);case"burkes":return new Nt(t,5);case"sierra":return new Nt(t,6);case"two-sierra":return new Nt(t,7);case"sierra-lite":return new Nt(t,8);default:throw new Error(`Unknown imageQuantization ${e}`)}}function ie(t,e="wuquant",r=256){switch(e){case"neuquant":return new yt(t,r);case"rgbquant":return new Mt(t,r);case"wuquant":return new Lt(t,r);case"neuquant-float":return new xt(t,r);default:throw new Error(`Unknown paletteQuantization ${e}`)}}t.exports=l(u)}},__webpack_module_cache__={};function __webpack_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var r=__webpack_module_cache__[t]={exports:{}};return __webpack_modules__[t](r,r.exports,__webpack_require__),r.exports}__webpack_require__.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return __webpack_require__.d(e,{a:e}),e},__webpack_require__.d=(t,e)=>{for(var r in e)__webpack_require__.o(e,r)&&!__webpack_require__.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),__webpack_require__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__webpack_require__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var t={};__webpack_require__.r(t),__webpack_require__.d(t,{AUTO:()=>et,BLEND_ADD:()=>ut,BLEND_DARKEN:()=>pt,BLEND_DESTINATION_OVER:()=>lt,BLEND_DIFFERENCE:()=>bt,BLEND_EXCLUSION:()=>_t,BLEND_HARDLIGHT:()=>gt,BLEND_LIGHTEN:()=>mt,BLEND_MULTIPLY:()=>ft,BLEND_OVERLAY:()=>dt,BLEND_SCREEN:()=>ct,BLEND_SOURCE_OVER:()=>ht,EDGE_CROP:()=>vt,EDGE_EXTEND:()=>yt,EDGE_WRAP:()=>wt,HORIZONTAL_ALIGN_CENTER:()=>it,HORIZONTAL_ALIGN_LEFT:()=>rt,HORIZONTAL_ALIGN_RIGHT:()=>nt,VERTICAL_ALIGN_BOTTOM:()=>st,VERTICAL_ALIGN_MIDDLE:()=>ot,VERTICAL_ALIGN_TOP:()=>at});var e={};__webpack_require__.r(e),__webpack_require__.d(e,{add:()=>St,darken:()=>It,difference:()=>Rt,dstOver:()=>Et,exclusion:()=>Pt,hardLight:()=>Tt,lighten:()=>Bt,multiply:()=>kt,overlay:()=>At,screen:()=>Mt,srcOver:()=>xt});var r=__webpack_require__(5546),i=__webpack_require__.n(r),n=__webpack_require__(1023),a=__webpack_require__.n(n),o=__webpack_require__(2699),s=__webpack_require__.n(o);function h(t){if(void 0===t)return!1;if("function"!=typeof t)throw new TypeError("Callback must be a function");return!0}function l(t,e){if("string"==typeof t&&(t=new Error(t)),"function"==typeof e)return e.call(this,t);throw t}function f(t,e,r,i,n,a){e=Math.round(e),r=Math.round(r),i=Math.round(i),n=Math.round(n);for(let o=r;o1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=D(t,360),e=D(e,100),r=D(r,100),0===e)i=n=a=r;else{var s=r<.5?r*(1+e):r+e-r*e,h=2*r-s;i=o(h,s,t+1/3),n=o(h,s,t),a=o(h,s,t-1/3)}return{r:255*i,g:255*n,b:255*a}}(t.h,o,h),l=!0,f="hsl"),t.hasOwnProperty("a")&&(a=t.a)),a=z(a),{ok:l,format:t.format||f,r:Math.min(255,Math.max(n.r,0)),g:Math.min(255,Math.max(n.g,0)),b:Math.min(255,Math.max(n.b,0)),a}}(t);this._originalInput=t,this._r=r.r,this._g=r.g,this._b=r.b,this._a=r.a,this._roundA=Math.round(100*this._a)/100,this._format=e.format||r.format,this._gradientType=e.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=r.ok}function y(t,e,r){t=D(t,255),e=D(e,255),r=D(r,255);var i,n,a=Math.max(t,e,r),o=Math.min(t,e,r),s=(a+o)/2;if(a==o)i=n=0;else{var h=a-o;switch(n=s>.5?h/(2-a-o):h/(a+o),a){case t:i=(e-r)/h+(e>1)+720)%360;--e;)i.h=(i.h+n)%360,a.push(_(i));return a}function L(t,e){e=e||6;for(var r=_(t).toHsv(),i=r.h,n=r.s,a=r.v,o=[],s=1/e;e--;)o.push(_({h:i,s:n,v:a})),a=(a+s)%1;return o}_.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,e,r,i=this.toRgb();return t=i.r/255,e=i.g/255,r=i.b/255,.2126*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.7152*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))},setAlpha:function(t){return this._a=z(t),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var t=w(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=w(this._r,this._g,this._b),e=Math.round(360*t.h),r=Math.round(100*t.s),i=Math.round(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+i+"%)":"hsva("+e+", "+r+"%, "+i+"%, "+this._roundA+")"},toHsl:function(){var t=y(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=y(this._r,this._g,this._b),e=Math.round(360*t.h),r=Math.round(100*t.s),i=Math.round(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+i+"%)":"hsla("+e+", "+r+"%, "+i+"%, "+this._roundA+")"},toHex:function(t){return v(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,i,n){var a=[j(Math.round(t).toString(16)),j(Math.round(e).toString(16)),j(Math.round(r).toString(16)),j(H(i))];return n&&a[0].charAt(0)==a[0].charAt(1)&&a[1].charAt(0)==a[1].charAt(1)&&a[2].charAt(0)==a[2].charAt(1)&&a[3].charAt(0)==a[3].charAt(1)?a[0].charAt(0)+a[1].charAt(0)+a[2].charAt(0)+a[3].charAt(0):a.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*D(this._r,255))+"%",g:Math.round(100*D(this._g,255))+"%",b:Math.round(100*D(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*D(this._r,255))+"%, "+Math.round(100*D(this._g,255))+"%, "+Math.round(100*D(this._b,255))+"%)":"rgba("+Math.round(100*D(this._r,255))+"%, "+Math.round(100*D(this._g,255))+"%, "+Math.round(100*D(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(U[v(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+x(this._r,this._g,this._b,this._a),r=e,i=this._gradientType?"GradientType = 1, ":"";if(t){var n=_(t);r="#"+x(n._r,n._g,n._b,n._a)}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,i=this._a<1&&this._a>=0;return e||!i||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return _(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(M,arguments)},brighten:function(){return this._applyModification(A,arguments)},darken:function(){return this._applyModification(I,arguments)},desaturate:function(){return this._applyModification(E,arguments)},saturate:function(){return this._applyModification(k,arguments)},greyscale:function(){return this._applyModification(S,arguments)},spin:function(){return this._applyModification(B,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(O,arguments)},complement:function(){return this._applyCombination(T,arguments)},monochromatic:function(){return this._applyCombination(L,arguments)},splitcomplement:function(){return this._applyCombination(P,arguments)},triad:function(){return this._applyCombination(R,[3])},tetrad:function(){return this._applyCombination(R,[4])}},_.fromRatio=function(t,e){if("object"==m(t)){var r={};for(var i in t)t.hasOwnProperty(i)&&(r[i]="a"===i?t[i]:G(t[i]));t=r}return _(t,e)},_.equals=function(t,e){return!(!t||!e)&&_(t).toRgbString()==_(e).toRgbString()},_.random=function(){return _.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},_.mix=function(t,e,r){r=0===r?0:r||50;var i=_(t).toRgb(),n=_(e).toRgb(),a=r/100;return _({r:(n.r-i.r)*a+i.r,g:(n.g-i.g)*a+i.g,b:(n.b-i.b)*a+i.b,a:(n.a-i.a)*a+i.a})},_.readability=function(t,e){var r=_(t),i=_(e);return(Math.max(r.getLuminance(),i.getLuminance())+.05)/(Math.min(r.getLuminance(),i.getLuminance())+.05)},_.isReadable=function(t,e,r){var i,n,a,o,s,h=_.readability(t,e);switch(n=!1,(a=r,"AA"!==(o=((a=a||{level:"AA",size:"small"}).level||"AA").toUpperCase())&&"AAA"!==o&&(o="AA"),"small"!==(s=(a.size||"small").toLowerCase())&&"large"!==s&&(s="small"),i={level:o,size:s}).level+i.size){case"AAsmall":case"AAAlarge":n=h>=4.5;break;case"AAlarge":n=h>=3;break;case"AAAsmall":n=h>=7}return n},_.mostReadable=function(t,e,r){var i,n,a,o,s=null,h=0;n=(r=r||{}).includeFallbackColors,a=r.level,o=r.size;for(var l=0;lh&&(h=i,s=_(e[l]));return _.isReadable(t,s,{level:a,size:o})||!n?s:(r.includeFallbackColors=!1,_.mostReadable(t,["#fff","#000"],r))};var C=_.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},U=_.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(C);function z(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function D(t,e){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(t)&&(t="100%");var r=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(t);return t=Math.min(e,Math.max(0,parseFloat(t))),r&&(t=parseInt(t*e,10)/100),Math.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function N(t){return Math.min(1,Math.max(0,t))}function F(t){return parseInt(t,16)}function j(t){return 1==t.length?"0"+t:""+t}function G(t){return t<=1&&(t=100*t+"%"),t}function H(t){return Math.round(255*parseFloat(t)).toString(16)}function W(t){return F(t)/255}var q,Z,Y,V=(Z="[\\s|\\(]+("+(q="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+q+")[,|\\s]+("+q+")\\s*\\)?",Y="[\\s|\\(]+("+q+")[,|\\s]+("+q+")[,|\\s]+("+q+")[,|\\s]+("+q+")\\s*\\)?",{CSS_UNIT:new RegExp(q),rgb:new RegExp("rgb"+Z),rgba:new RegExp("rgba"+Y),hsl:new RegExp("hsl"+Z),hsla:new RegExp("hsla"+Y),hsv:new RegExp("hsv"+Z),hsva:new RegExp("hsva"+Y),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function X(t){return!!V.CSS_UNIT.exec(t)}function J(t,e){this.size=this.size||t,this.smallerSize=this.smallerSize||e,function(t){for(let e=1;e>>=8),i=255&(t>>>=8);return{r:255&(t>>>=8),g:i,b:r,a:e}}J.prototype.size=32,J.prototype.smallerSize=8,J.prototype.distance=function(t,e){let r=0;for(let i=0;in?"1":"0";return a};const K=[],$=J;__webpack_require__(9307);const tt=(t,e)=>{let{url:r,...i}=t;fetch(r,i).then((t=>{if(t.ok)return t.arrayBuffer().catch((t=>{throw new Error(`Response is not a buffer for url ${r}. Error: ${t.message}`)}));throw new Error(`HTTP Status ${t.status} for url ${r}`)})).then((t=>e(null,t))).catch((t=>e(t)))},et=-1,rt=1,it=2,nt=4,at=8,ot=16,st=32,ht="srcOver",lt="dstOver",ft="multiply",ut="add",ct="screen",dt="overlay",pt="darken",mt="lighten",gt="hardLight",bt="difference",_t="exclusion",yt=1,wt=2,vt=3;function xt(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a;return{r:(t.r*t.a+e.r*e.a*(1-t.a))/i,g:(t.g*t.a+e.g*e.a*(1-t.a))/i,b:(t.b*t.a+e.b*e.a*(1-t.a))/i,a:i}}function Et(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a;return{r:(e.r*e.a+t.r*t.a*(1-e.a))/i,g:(e.g*e.a+t.g*t.a*(1-e.a))/i,b:(e.b*e.a+t.b*t.a*(1-e.a))/i,a:i}}function kt(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a,s=e.r*e.a,h=e.g*e.a,l=e.b*e.a;return{r:(n*s+n*(1-e.a)+s*(1-t.a))/i,g:(a*h+a*(1-e.a)+h*(1-t.a))/i,b:(o*l+o*(1-e.a)+l*(1-t.a))/i,a:i}}function St(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a;return{r:(n+e.r*e.a)/i,g:(a+e.g*e.a)/i,b:(o+e.b*e.a)/i,a:i}}function Mt(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a,s=e.r*e.a,h=e.g*e.a,l=e.b*e.a;return{r:(n*e.a+s*t.a-n*s+n*(1-e.a)+s*(1-t.a))/i,g:(a*e.a+h*t.a-a*h+a*(1-e.a)+h*(1-t.a))/i,b:(o*e.a+l*t.a-o*l+o*(1-e.a)+l*(1-t.a))/i,a:i}}function At(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a,s=e.r*e.a,h=e.g*e.a,l=e.b*e.a;return{r:(2*s<=e.a?2*n*s+n*(1-e.a)+s*(1-t.a):n*(1+e.a)+s*(1+t.a)-2*s*n-e.a*t.a)/i,g:(2*h<=e.a?2*a*h+a*(1-e.a)+h*(1-t.a):a*(1+e.a)+h*(1+t.a)-2*h*a-e.a*t.a)/i,b:(2*l<=e.a?2*o*l+o*(1-e.a)+l*(1-t.a):o*(1+e.a)+l*(1+t.a)-2*l*o-e.a*t.a)/i,a:i}}function It(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a,s=e.r*e.a,h=e.g*e.a,l=e.b*e.a;return{r:(Math.min(n*e.a,s*t.a)+n*(1-e.a)+s*(1-t.a))/i,g:(Math.min(a*e.a,h*t.a)+a*(1-e.a)+h*(1-t.a))/i,b:(Math.min(o*e.a,l*t.a)+o*(1-e.a)+l*(1-t.a))/i,a:i}}function Bt(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a,s=e.r*e.a,h=e.g*e.a,l=e.b*e.a;return{r:(Math.max(n*e.a,s*t.a)+n*(1-e.a)+s*(1-t.a))/i,g:(Math.max(a*e.a,h*t.a)+a*(1-e.a)+h*(1-t.a))/i,b:(Math.max(o*e.a,l*t.a)+o*(1-e.a)+l*(1-t.a))/i,a:i}}function Tt(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a,s=e.r*e.a,h=e.g*e.a,l=e.b*e.a;return{r:(2*n<=t.a?2*n*s+n*(1-e.a)+s*(1-t.a):n*(1+e.a)+s*(1+t.a)-2*s*n-e.a*t.a)/i,g:(2*a<=t.a?2*a*h+a*(1-e.a)+h*(1-t.a):a*(1+e.a)+h*(1+t.a)-2*h*a-e.a*t.a)/i,b:(2*o<=t.a?2*o*l+o*(1-e.a)+l*(1-t.a):o*(1+e.a)+l*(1+t.a)-2*l*o-e.a*t.a)/i,a:i}}function Rt(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a,s=e.r*e.a,h=e.g*e.a,l=e.b*e.a;return{r:(n+s-2*Math.min(n*e.a,s*t.a))/i,g:(a+h-2*Math.min(a*e.a,h*t.a))/i,b:(o+l-2*Math.min(o*e.a,l*t.a))/i,a:i}}function Pt(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t.a*=r;const i=e.a+t.a-e.a*t.a,n=t.r*t.a,a=t.g*t.a,o=t.b*t.a,s=e.r*e.a,h=e.g*e.a,l=e.b*e.a;return{r:(n*e.a+s*t.a-2*n*s+n*(1-e.a)+s*(1-t.a))/i,g:(a*e.a+h*t.a-2*a*h+a*(1-e.a)+h*(1-t.a))/i,b:(o*e.a+l*t.a-2*o*l+o*(1-e.a)+l*(1-t.a))/i,a:i}}const Ot=function(t,e){for(var r=arguments.length,i=new Array(r>2?r-2:0),n=2;n{i.push(((t,e)=>{t&&n(t),r(e)})),t.bind(e)(...i)}))},Lt={},Ct=(t,e)=>{Lt[t]=e},Ut=t=>{const e=t.split("/").slice(-1);var r;return(r=e[e.length-1].split(".").pop(),Object.entries(Lt).find((t=>t[1].includes(r)))||[])[0]};var zt=__webpack_require__(5025),Dt=__webpack_require__.n(zt),Nt=__webpack_require__(6551),Ft=__webpack_require__.n(Nt),jt=__webpack_require__(8834).lW;function Gt(t){return t._exif&&t._exif.tags&&t._exif.tags.Orientation||1}async function Ht(t,e,r){const i=await async function(t,e){const r=await Dt().fromBuffer(t);return r?r.mime:e?Ut(e):null}(t,e);if("string"!=typeof i)return r(new Error("Could not find MIME for Buffer <"+e+">"));this._originalMime=i.toLowerCase();try{const e=this.getMIME();if(!this.constructor.decoders[e])return l.call(this,"Unsupported MIME type: "+e,r);this.bitmap=this.constructor.decoders[e](t)}catch(t){return r.call(this,t,this)}try{this._exif=Ft().create(t).parse(),function(t){if(Gt(t)<2)return;const e=function(t){const e=t.getWidth(),r=t.getHeight();switch(Gt(t)){case 1:default:return null;case 2:return function(t,r){return[e-t-1,r]};case 3:return function(t,i){return[e-t-1,r-i-1]};case 4:return function(t,e){return[t,r-e-1]};case 5:return function(t,e){return[e,t]};case 6:return function(t,e){return[e,r-t-1]};case 7:return function(t,i){return[e-i-1,r-t-1]};case 8:return function(t,r){return[e-r-1,t]}}}(t),r=Gt(t)>4;!function(t,e,r,i){const n=t.bitmap.data,a=t.bitmap.width,o=jt.alloc(n.length);for(let t=0;t{e.call(this,null,t)})):e.call(this,null,r)}return this}function qt(t){return Ot(Wt,this,t)}var Zt=__webpack_require__(8834).lW;function Yt(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var i=r.call(t,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}const Vt="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",Xt=[NaN,NaN];for(let t=2;t<65;t++){const e=c()(c().BIN,Vt.slice(0,t))(new Array(65).join("1"));Xt.push(e.length)}function Jt(){}function Qt(t){return Object.prototype.toString.call(t).toLowerCase().indexOf("arraybuffer")>-1}function Kt(t){const e=Zt.alloc(t.byteLength),r=new Uint8Array(t);for(let t=0;tr?e(r):"object"==typeof i&&Zt.isBuffer(i)?e(null,i):"object"==typeof i&&Qt(i)?e(null,Kt(i)):new Error(`Could not load Buffer from <${t.url}>`)))}const te={data:null,width:null,height:null};class ee extends(s()){constructor(){for(var t=arguments.length,e=new Array(t),r=0;rOt(this.write,this,t))),Yt(this,"getBase64Async",(t=>Ot(this.getBase64,this,t))),Yt(this,"getBuffer",Wt),Yt(this,"getBufferAsync",qt),Yt(this,"getPixelColour",this.getPixelColor),Yt(this,"setPixelColour",this.setPixelColor);const n=this;let a=Jt;function o(){for(var t=arguments.length,e=new Array(t),r=0;r{i&&a===Jt?n.emitError("constructor",i):i||n.emitMulti("constructor","initialized"),a.call(n,...e)}),1)}if(Qt(e[0])&&(e[0]=Kt(e[0])),"number"==typeof e[0]&&"number"==typeof e[1]||parseInt(e[0],10)&&parseInt(e[1],10)){const t=parseInt(e[0],10),r=parseInt(e[1],10);if(a=e[2],"number"==typeof e[2]&&(this._background=e[2],a=e[3]),"string"==typeof e[2]&&(this._background=ee.cssColorToHex(e[2]),a=e[3]),void 0===a&&(a=Jt),"function"!=typeof a)return l.call(this,"cb must be a function",o);this.bitmap={data:Zt.alloc(t*r*4),width:t,height:r};for(let t=0;t{if(t)return l.call(this,t,o);this.parseBitmap(r,e[0].url,o)}))}else if(e[0]instanceof ee){const[t]=e;if(a=e[1],void 0===a&&(a=Jt),"function"!=typeof a)return l.call(this,"cb must be a function",o);this.bitmap={data:Zt.from(t.bitmap.data),width:t.bitmap.width,height:t.bitmap.height},this._quality=t._quality,this._deflateLevel=t._deflateLevel,this._deflateStrategy=t._deflateStrategy,this._filterType=t._filterType,this._rgba=t._rgba,this._background=t._background,this._originalMime=t._originalMime,o(null,this)}else if((s=e[0])&&"object"==typeof s&&"number"==typeof s.width&&"number"==typeof s.height&&(Zt.isBuffer(s.data)||s.data instanceof Uint8Array||"function"==typeof Uint8ClampedArray&&s.data instanceof Uint8ClampedArray)&&(s.data.length===s.width*s.height*4||s.data.length===s.width*s.height*3)){const[t]=e;a=e[1]||Jt;const r=t.width*t.height*4===t.data.length?Zt.from(t.data):function(t){if(t.length%3!=0)throw new Error("Buffer length is incorrect");const e=Zt.allocUnsafe(t.length/3*4);let r=0;for(let i=0;i{if(e)return l.call(this,e,o);this.parseBitmap(r,t,o)}))}else if("object"==typeof e[0]&&Zt.isBuffer(e[0])){const t=e[0];if(a=e[1],"function"!=typeof a)return l.call(this,"cb must be a function",o);this.parseBitmap(t,null,o)}else{a=e[e.length-1],"function"!=typeof a&&(a=e[e.length-2],"function"!=typeof a&&(a=Jt));const t=ee.__extraConstructors.find((t=>t.test(...e)));if(!t)return l.call(this,"No matching constructor overloading was found. Please see the docs for how to call the Jimp constructor.",o);new Promise(((r,i)=>{t.run.call(this,r,i,...e)})).then((()=>o(null,this))).catch(o)}var s}parseBitmap(t,e,r){Ht.call(this,t,null,r)}rgba(t,e){return"boolean"!=typeof t?l.call(this,"bool must be a boolean, true for RGBA or false for RGB",e):(this._rgba=t,h(e)&&e.call(this,null,this),this)}emitMulti(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r=Object.assign(r,{methodName:t,eventName:e}),this.emit("any",r),t&&this.emit(t,r),this.emit(e,r)}emitError(t,e){this.emitMulti(t,"error",e)}getHeight(){return this.bitmap.height}getWidth(){return this.bitmap.width}inspect(){return""}toString(){return"[object Jimp]"}getMIME(){return this._originalMime||ee.MIME_PNG}getExtension(){const t=this.getMIME();return(Lt[t.toLowerCase()]||[])[0]}write(t,e){if(!i()||!i().createWriteStream)throw new Error("Cant access the filesystem. You can use the getBase64 method.");if("string"!=typeof t)return l.call(this,"path must be a string",e);if(void 0===e&&(e=Jt),"function"!=typeof e)return l.call(this,"cb must be a function",e);const r=Ut(t)||this.getMIME(),n=a().parse(t);return n.dir&&i().mkdirSync(n.dir,{recursive:!0}),this.getBuffer(r,((r,n)=>{if(r)return l.call(this,r,e);const a=i().createWriteStream(t);a.on("open",(()=>{a.write(n),a.end()})).on("error",(t=>l.call(this,t,e))),a.on("finish",(()=>{e.call(this,null,this)}))})),this}getBase64(t,e){return t===ee.AUTO&&(t=this.getMIME()),"string"!=typeof t?l.call(this,"mime must be a string",e):"function"!=typeof e?l.call(this,"cb must be a function",e):(this.getBuffer(t,(function(r,i){if(r)return l.call(this,r,e);const n="data:"+t+";base64,"+i.toString("base64");e.call(this,null,n)})),this)}hash(t,e){if("function"==typeof(t=t||64)&&(e=t,t=64),"number"!=typeof t)return l.call(this,"base must be a number",e);if(t<2||t>64)return l.call(this,"base must be a number between 2 and 64",e);let r=this.pHash();for(r=c()(c().BIN,Vt.slice(0,t))(r);r.length=this.bitmap.width&&(n=this.bitmap.width-1),e<0&&(a=0),e>=this.bitmap.height&&(a=this.bitmap.height-1)),r===ee.EDGE_WRAP&&(t<0&&(n=this.bitmap.width+t),t>=this.bitmap.width&&(n=t%this.bitmap.width),e<0&&(a=this.bitmap.height+e),e>=this.bitmap.height&&(a=e%this.bitmap.height));let o=this.bitmap.width*a+n<<2;return(n<0||n>=this.bitmap.width)&&(o=-1),(a<0||a>=this.bitmap.height)&&(o=-1),h(i)&&i.call(this,null,o),o}getPixelColor(t,e,r){if("number"!=typeof t||"number"!=typeof e)return l.call(this,"x and y must be numbers",r);const i=this.getPixelIndex(t,e),n=this.bitmap.data.readUInt32BE(i);return h(r)&&r.call(this,null,n),n}setPixelColor(t,e,r,i){if("number"!=typeof t||"number"!=typeof e||"number"!=typeof r)return l.call(this,"hex, x and y must be numbers",i);const n=this.getPixelIndex(e,r);return this.bitmap.data.writeUInt32BE(t,n),h(i)&&i.call(this,null,this),this}hasAlpha(){const{width:t,height:e,data:r}=this.bitmap,i=t*e<<2;for(let t=3;t1&&void 0!==arguments[1]?arguments[1]:ee;Object.entries(t).forEach((t=>{let[r,i]=t;e[r]=i}))}function ie(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ee;Object.entries(t).forEach((t=>{let[r,i]=t;e.prototype[r]=i}))}function ne(t,e,r){const i="before-"+e,n=e.replace(/e$/,"")+"ed";ee.prototype[t]=function(){let e;for(var a=arguments.length,o=new Array(a),s=0;s3&&void 0!==arguments[3]?arguments[3]:{},a=arguments.length>4?arguments[4]:void 0;if("function"==typeof n&&(a=n,n={}),!(t instanceof this.constructor))return l.call(this,"The source must be a Jimp image",a);if("number"!=typeof r||"number"!=typeof i)return l.call(this,"x and y must be numbers",a);let{mode:o,opacitySource:s,opacityDest:f}=n;o||(o=ht),("number"!=typeof s||s<0||s>1)&&(s=1),("number"!=typeof f||f<0||f>1)&&(f=1);const u=e[o];r=Math.round(r),i=Math.round(i);const c=this;return 1!==f&&c.opacity(f),t.scanQuiet(0,0,t.bitmap.width,t.bitmap.height,(function(t,e,n){const a=c.getPixelIndex(r+t,i+e,vt);if(-1===a)return;const o=u({r:this.bitmap.data[n+0]/255,g:this.bitmap.data[n+1]/255,b:this.bitmap.data[n+2]/255,a:this.bitmap.data[n+3]/255},{r:c.bitmap.data[a+0]/255,g:c.bitmap.data[a+1]/255,b:c.bitmap.data[a+2]/255,a:c.bitmap.data[a+3]/255},s);c.bitmap.data[a+0]=this.constructor.limit255(255*o.r),c.bitmap.data[a+1]=this.constructor.limit255(255*o.g),c.bitmap.data[a+2]=this.constructor.limit255(255*o.b),c.bitmap.data[a+3]=this.constructor.limit255(255*o.a)})),h(a)&&a.call(this,null,this),this}}),ee.__extraConstructors=[],ee.appendConstructorOption=function(t,e,r){ee.__extraConstructors.push({name:t,test:e,run:r})},ee.read=function(){for(var t=arguments.length,e=new Array(t),r=0;r{new ee(...e,((e,i)=>{e?r(e):t(i)}))}))},ee.create=ee.read,ee.rgbaToInt=function(t,e,r,i,n){if("number"!=typeof t||"number"!=typeof e||"number"!=typeof r||"number"!=typeof i)return l.call(this,"r, g, b and a must be numbers",n);if(t<0||t>255)return l.call(this,"r must be between 0 and 255",n);if((e<0||e>255)&&l.call(this,"g must be between 0 and 255",n),r<0||r>255)return l.call(this,"b must be between 0 and 255",n);if(i<0||i>255)return l.call(this,"a must be between 0 and 255",n);let a=255&t;return a<<=8,a|=255&e,a<<=8,a|=255&r,a<<=8,a|=255&i,a>>>=0,h(n)&&n.call(this,null,a),a},ee.intToRGBA=function(t,e){if("number"!=typeof t)return l.call(this,"i must be a number",e);const r={};return r.r=Math.floor(t/Math.pow(256,3)),r.g=Math.floor((t-r.r*Math.pow(256,3))/Math.pow(256,2)),r.b=Math.floor((t-r.r*Math.pow(256,3)-r.g*Math.pow(256,2))/Math.pow(256,1)),r.a=Math.floor((t-r.r*Math.pow(256,3)-r.g*Math.pow(256,2)-r.b*Math.pow(256,1))/Math.pow(256,0)),h(e)&&e.call(this,null,r),r},ee.cssColorToHex=function(t){return"number"==typeof(t=t||0)?Number(t):parseInt(_(t).toHex8(),16)},ee.limit255=function(t){return t=Math.max(t,0),Math.min(t,255)},ee.diff=function(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:.1;if(!(t instanceof ee&&e instanceof ee))return l.call(this,"img1 and img2 must be an Jimp images");const i=t.bitmap,n=e.bitmap;if(i.width===n.width&&i.height===n.height||(i.width*i.height>n.width*n.height?t=t.cloneQuiet().resize(n.width,n.height):e=e.cloneQuiet().resize(i.width,i.height)),"number"!=typeof r||r<0||r>1)return l.call(this,"threshold must be a number between 0 and 1");const a=new ee(i.width,i.height,4294967295);return{percent:p()(i.data,n.data,a.bitmap.data,a.bitmap.width,a.bitmap.height,{threshold:r})/(a.bitmap.width*a.bitmap.height),image:a}},ee.distance=function(t,e){const r=new $,i=r.getHash(t),n=r.getHash(e);return r.distance(i,n)},ee.compareHashes=function(t,e){return(new $).distance(t,e)},ee.colorDiff=function(t,e){const r=t=>Math.pow(t,2),{max:i}=Math;return 0===t.a||t.a||(t.a=255),0===e.a||e.a||(e.a=255),(i(r(t.r-e.r),r(t.r-e.r-t.a+e.a))+i(r(t.g-e.g),r(t.g-e.g-t.a+e.a))+i(r(t.b-e.b),r(t.b-e.b-t.a+e.a)))/195075},ne("clone","clone",(function(t){const e=new ee(this);return h(t)&&t.call(e,null,e),e})),ae("background",(function(t,e){return"number"!=typeof t?l.call(this,"hex must be a hexadecimal rgba value",e):(this._background=t,h(e)&&e.call(this,null,this),this)})),ae("scan",(function(t,e,r,i,n,a){if("number"!=typeof t||"number"!=typeof e)return l.call(this,"x and y must be numbers",a);if("number"!=typeof r||"number"!=typeof i)return l.call(this,"w and h must be numbers",a);if("function"!=typeof n)return l.call(this,"f must be a function",a);const o=f(this,t,e,r,i,n);return h(a)&&a.call(this,null,o),o}));{let t;"undefined"!=typeof window&&"object"==typeof window&&(t=window),"undefined"!=typeof self&&"object"==typeof self&&(t=self),t.Jimp=ee,t.Buffer=Zt}const oe=ee;var se=__webpack_require__(643),he=__webpack_require__(2691),le=__webpack_require__.n(he);const fe="image/jpeg",ue=()=>({mime:{[fe]:["jpeg","jpg","jpe"]},constants:{MIME_JPEG:fe},decoders:{[fe]:le().decode},encoders:{[fe]:t=>le().encode(t.bitmap,t._quality).data},class:{_quality:100,quality(t,e){return"number"!=typeof t?l.call(this,"n must be a number",e):t<0||t>100?l.call(this,"n must be a number 0 - 100",e):(this._quality=Math.round(t),h(e)&&e.call(this,null,this),this)}}});var ce=__webpack_require__(9902);const de="image/png",pe=()=>({mime:{[de]:["png"]},constants:{MIME_PNG:de,PNG_FILTER_AUTO:-1,PNG_FILTER_NONE:0,PNG_FILTER_SUB:1,PNG_FILTER_UP:2,PNG_FILTER_AVERAGE:3,PNG_FILTER_PATH:4},hasAlpha:{[de]:!0},decoders:{[de]:ce.PNG.sync.read},encoders:{[de](t){const e=new ce.PNG({width:t.bitmap.width,height:t.bitmap.height});return e.data=t.bitmap.data,ce.PNG.sync.write(e,{deflateLevel:t._deflateLevel,deflateStrategy:t._deflateStrategy,filterType:t._filterType,colorType:"number"==typeof t._colorType?t._colorType:t._rgba?6:2,inputHasAlpha:t._rgba})}},class:{_deflateLevel:9,_deflateStrategy:3,_filterType:-1,_colorType:null,deflateLevel(t,e){return"number"!=typeof t?l.call(this,"l must be a number",e):t<0||t>9?l.call(this,"l must be a number 0 - 9",e):(this._deflateLevel=Math.round(t),h(e)&&e.call(this,null,this),this)},deflateStrategy(t,e){return"number"!=typeof t?l.call(this,"s must be a number",e):t<0||t>3?l.call(this,"s must be a number 0 - 3",e):(this._deflateStrategy=Math.round(t),h(e)&&e.call(this,null,this),this)},filterType(t,e){return"number"!=typeof t?l.call(this,"n must be a number",e):t<-1||t>4?l.call(this,"n must be -1 (auto) or a number 0 - 4",e):(this._filterType=Math.round(t),h(e)&&e.call(this,null,this),this)},colorType(t,e){return"number"!=typeof t?l.call(this,"s must be a number",e):0!==t&&2!==t&&4!==t&&6!==t?l.call(this,"s must be a number 0, 2, 4, 6.",e):(this._colorType=Math.round(t),h(e)&&e.call(this,null,this),this)}}});var me=__webpack_require__(486),ge=__webpack_require__.n(me);const be="image/bmp",_e="image/x-ms-bmp",ye=t=>{return f({bitmap:e=ge().decode(t)},0,0,e.width,e.height,(function(t,r,i){const n=this.bitmap.data[i+0],a=this.bitmap.data[i+1],o=this.bitmap.data[i+2],s=this.bitmap.data[i+3];this.bitmap.data[i+0]=s,this.bitmap.data[i+1]=o,this.bitmap.data[i+2]=a,this.bitmap.data[i+3]=e.is_with_alpha?n:255})).bitmap;var e},we=t=>ge().encode(function(t){return f(t,0,0,t.bitmap.width,t.bitmap.height,(function(t,e,r){const i=this.bitmap.data[r+0],n=this.bitmap.data[r+1],a=this.bitmap.data[r+2],o=this.bitmap.data[r+3];this.bitmap.data[r+0]=o,this.bitmap.data[r+1]=a,this.bitmap.data[r+2]=n,this.bitmap.data[r+3]=i})).bitmap}(t)).data;var ve=__webpack_require__(9299),xe=__webpack_require__.n(ve),Ee=__webpack_require__(8834).lW;const ke="image/tiff";var Se=__webpack_require__(63),Me=__webpack_require__(9455),Ae=__webpack_require__(8834).lW;const Ie="image/gif",Be=[1,57,41,21,203,34,97,73,227,91,149,62,105,45,39,137,241,107,3,173,39,71,65,238,219,101,187,87,81,151,141,133,249,117,221,209,197,187,177,169,5,153,73,139,133,127,243,233,223,107,103,99,191,23,177,171,165,159,77,149,9,139,135,131,253,245,119,231,224,109,211,103,25,195,189,23,45,175,171,83,81,79,155,151,147,9,141,137,67,131,129,251,123,30,235,115,113,221,217,53,13,51,50,49,193,189,185,91,179,175,43,169,83,163,5,79,155,19,75,147,145,143,35,69,17,67,33,65,255,251,247,243,239,59,29,229,113,111,219,27,213,105,207,51,201,199,49,193,191,47,93,183,181,179,11,87,43,85,167,165,163,161,159,157,155,77,19,75,37,73,145,143,141,35,138,137,135,67,33,131,129,255,63,250,247,61,121,239,237,117,29,229,227,225,111,55,109,216,213,211,209,207,205,203,201,199,197,195,193,48,190,47,93,185,183,181,179,178,176,175,173,171,85,21,167,165,41,163,161,5,79,157,78,154,153,19,75,149,74,147,73,144,143,71,141,140,139,137,17,135,134,133,66,131,65,129,1],Te=[0,9,10,10,14,12,14,14,16,15,16,15,16,15,15,17,18,17,12,18,16,17,17,19,19,18,19,18,18,19,19,19,20,19,20,20,20,20,20,20,15,20,19,20,20,20,21,21,21,20,20,20,21,18,21,21,21,21,20,21,17,21,21,21,22,22,21,22,22,21,22,21,19,22,22,19,20,22,22,21,21,21,22,22,22,18,22,22,21,22,22,23,22,20,23,22,22,23,23,21,19,21,21,21,23,23,23,22,23,23,21,23,22,23,18,22,23,20,22,23,23,23,21,22,20,22,21,22,24,24,24,24,24,22,21,24,23,23,24,21,24,23,24,22,24,24,22,24,24,22,23,24,24,24,20,23,22,23,24,24,24,24,24,24,24,23,21,23,22,23,24,24,24,22,24,24,24,23,22,24,24,25,23,25,25,23,24,25,25,24,22,25,25,25,24,23,24,25,25,25,25,25,25,25,25,25,25,25,25,23,25,23,24,25,25,25,25,25,25,25,25,25,24,22,25,25,23,25,25,20,24,25,24,25,25,22,24,25,24,25,24,25,25,24,25,25,25,25,22,25,25,25,24,25,24,25,18];var Re=__webpack_require__(8834).lW;function Pe(t,e,r,i){const n=[0,0,0],a=(e.length-1)/2;for(let o=0;onull!=t;function Le(t){return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,e,r){const i=parseInt(.2126*this.bitmap.data[r]+.7152*this.bitmap.data[r+1]+.0722*this.bitmap.data[r+2],10);this.bitmap.data[r]=i,this.bitmap.data[r+1]=i,this.bitmap.data[r+2]=i})),h(t)&&t.call(this,null,this),this}function Ce(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:50;return{r:(e.r-t.r)*(r/100)+t.r,g:(e.g-t.g)*(r/100)+t.g,b:(e.b-t.b)*(r/100)+t.b}}function Ue(t,e){return t&&Array.isArray(t)?(t=t.map((t=>("xor"!==t.apply&&"mix"!==t.apply||(t.params[0]=_(t.params[0]).toRgb()),t))),this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,((r,i,n)=>{let a={r:this.bitmap.data[n],g:this.bitmap.data[n+1],b:this.bitmap.data[n+2]};const o=(t,e)=>this.constructor.limit255(a[t]+e);t.forEach((t=>{if("mix"===t.apply)a=Ce(a,t.params[0],t.params[1]);else if("tint"===t.apply)a=Ce(a,{r:255,g:255,b:255},t.params[0]);else if("shade"===t.apply)a=Ce(a,{r:0,g:0,b:0},t.params[0]);else if("xor"===t.apply)a={r:a.r^t.params[0].r,g:a.g^t.params[0].g,b:a.b^t.params[0].b};else if("red"===t.apply)a.r=o("r",t.params[0]);else if("green"===t.apply)a.g=o("g",t.params[0]);else if("blue"===t.apply)a.b=o("b",t.params[0]);else{if("hue"===t.apply&&(t.apply="spin"),a=_(a),!a[t.apply])return l.call(this,"action "+t.apply+" not supported",e);a=a[t.apply](...t.params).toRgb()}})),this.bitmap.data[n]=a.r,this.bitmap.data[n+1]=a.g,this.bitmap.data[n+2]=a.b})),h(e)&&e.call(this,null,this),this):l.call(this,"actions must be an array",e)}Object.freeze({LIGHTEN:"lighten",BRIGHTEN:"brighten",DARKEN:"darken",DESATURATE:"desaturate",SATURATE:"saturate",GREYSCALE:"greyscale",SPIN:"spin",HUE:"hue",MIX:"mix",TINT:"tint",SHADE:"shade",XOR:"xor",RED:"red",GREEN:"green",BLUE:"blue"});var ze=__webpack_require__(8834).lW;function De(t){const e=[1,9,3,11,13,5,15,7,4,12,2,10,16,8,14,6];return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,r,i){const n=e[((3&r)<<2)+t%4];this.bitmap.data[i]=Math.min(this.bitmap.data[i]+n,255),this.bitmap.data[i+1]=Math.min(this.bitmap.data[i+1]+n,255),this.bitmap.data[i+2]=Math.min(this.bitmap.data[i+2]+n,255)})),h(t)&&t.call(this,null,this),this}var Ne=__webpack_require__(8834).lW;function Fe(t,e,r){if("boolean"!=typeof t||"boolean"!=typeof e)return l.call(this,"horizontal and vertical must be Booleans",r);const i=Ne.alloc(this.bitmap.data.length);return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(r,n,a){const o=t?this.bitmap.width-1-r:r,s=e?this.bitmap.height-1-n:n,h=this.bitmap.width*s+o<<2,l=this.bitmap.data.readUInt32BE(a);i.writeUInt32BE(l,h)})),this.bitmap.data=Ne.from(i),h(r)&&r.call(this,null,this),this}function je(){const t={r:new Array(256).fill(0),g:new Array(256).fill(0),b:new Array(256).fill(0)};return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(e,r,i){t.r[this.bitmap.data[i+0]]++,t.g[this.bitmap.data[i+1]]++,t.b[this.bitmap.data[i+2]]++})),t}const Ge=function(t,e,r){return 255*(t-e)/(r-e)},He=function(t){return[t.findIndex((t=>t>0)),255-t.slice().reverse().findIndex((t=>t>0))]};var We=__webpack_require__(8058),qe=__webpack_require__.n(We);function Ze(t,e){let r=0;for(let i=0;i{const i=[...a,e].join(" "),s=Ze(t,i);s<=r&&!e.includes("\n")?(s>o&&(o=s),a.push(e)):(n.push(a),a=[e.replace("\n","")])})),n.push(a),{lines:n,longestLine:o}}function Ve(t,e,r){const{lines:i}=Ye(t,e,r);return i.length*t.common.lineHeight}function Xe(t,e,r,i,n){if(n.width>0&&n.height>0){const a=e.pages[n.page];t.blit(a,r+n.xoffset,i+n.yoffset,n.x,n.y,n.width,n.height)}return t}function Je(t,e,r,i,n){for(let a=0;a0&&this.heightOriginal>0&&this.targetWidth>0&&this.targetHeight>0))throw new Error("Invalid settings specified for the resizer.");this.configurePasses()},Ke.prototype.configurePasses=function(){this.widthOriginal===this.targetWidth?this.resizeWidth=this.bypassResizer:(this.ratioWeightWidthPass=this.widthOriginal/this.targetWidth,this.ratioWeightWidthPass<1&&this.interpolationPass?(this.initializeFirstPassBuffers(!0),this.resizeWidth=4===this.colorChannels?this.resizeWidthInterpolatedRGBA:this.resizeWidthInterpolatedRGB):(this.initializeFirstPassBuffers(!1),this.resizeWidth=4===this.colorChannels?this.resizeWidthRGBA:this.resizeWidthRGB)),this.heightOriginal===this.targetHeight?this.resizeHeight=this.bypassResizer:(this.ratioWeightHeightPass=this.heightOriginal/this.targetHeight,this.ratioWeightHeightPass<1&&this.interpolationPass?(this.initializeSecondPassBuffers(!0),this.resizeHeight=this.resizeHeightInterpolated):(this.initializeSecondPassBuffers(!1),this.resizeHeight=4===this.colorChannels?this.resizeHeightRGBA:this.resizeHeightRGB))},Ke.prototype._resizeWidthInterpolatedRGBChannels=function(t,e){const r=e?4:3,i=this.ratioWeightWidthPass,n=this.widthBuffer;let a,o,s=0,h=0,l=0,f=0,u=0;for(a=0;s<1/3;a+=r,s+=i)for(h=a,l=0;h=u)){d+=f;break}c+=r,d=c,f-=u}while(f>0&&c=h)){f+=s;break}l=d,f=l,s-=h}while(s>0&&l3&&(this.outputWidthWorkBenchOpaquePixelsCount=this.generateFloat64Buffer(this.heightOriginal)))},Ke.prototype.initializeSecondPassBuffers=function(t){this.heightBuffer=this.generateUint8Buffer(this.finalResultSize),t||(this.outputHeightWorkBench=this.generateFloatBuffer(this.targetWidthMultipliedByChannels),this.colorChannels>3&&(this.outputHeightWorkBenchOpaquePixelsCount=this.generateFloat64Buffer(this.targetWidth)))},Ke.prototype.generateFloatBuffer=function(t){try{return new Float32Array(t)}catch(t){return[]}},Ke.prototype.generateFloat64Buffer=function(t){try{return new Float64Array(t)}catch(t){return[]}},Ke.prototype.generateUint8Buffer=function(t){try{return new Uint8Array(t)}catch(t){return[]}};const $e=Ke;var tr=__webpack_require__(8834).lW;const er={nearestNeighbor(t,e){const r=t.width,i=t.height,n=e.width,a=e.height,o=t.data,s=e.data;for(let t=0;t0?n[e-4]:2*n[e]-n[e+4],f=n[e],u=n[e+4],c=a0?p[e-4*u]:2*p[e]-p[e+4*u],l=p[e],f=p[e+4*u],c=n1)for(let t=0;t=0&&a.x=0&&a.y({blit(t,e,r,i,n,a,o,s){if(!(t instanceof this.constructor))return l.call(this,"The source must be a Jimp image",s);if("number"!=typeof e||"number"!=typeof r)return l.call(this,"x and y must be numbers",s);if("function"==typeof i)s=i,i=0,n=0,a=t.bitmap.width,o=t.bitmap.height;else{if(typeof i!=typeof n||typeof n!=typeof a||typeof a!=typeof o)return l.call(this,"srcx, srcy, srcw, srch must be numbers",s);i=i||0,n=n||0,a=a||t.bitmap.width,o=o||t.bitmap.height}e=Math.round(e),r=Math.round(r),i=Math.round(i),n=Math.round(n),a=Math.round(a),o=Math.round(o);const f=this.bitmap.width,u=this.bitmap.height,c=this;return t.scanQuiet(i,n,a,o,(function(t,a,o){const s=e+t-i,h=r+a-n;if(s>=0&&h>=0&&f-s>0&&u-h>0){const t=c.getPixelIndex(s,h),e={r:this.bitmap.data[o],g:this.bitmap.data[o+1],b:this.bitmap.data[o+2],a:this.bitmap.data[o+3]},r={r:c.bitmap.data[t],g:c.bitmap.data[t+1],b:c.bitmap.data[t+2],a:c.bitmap.data[t+3]};c.bitmap.data[t]=(e.a*(e.r-r.r)-r.r+255>>8)+r.r,c.bitmap.data[t+1]=(e.a*(e.g-r.g)-r.g+255>>8)+r.g,c.bitmap.data[t+2]=(e.a*(e.b-r.b)-r.b+255>>8)+r.b,c.bitmap.data[t+3]=this.constructor.limit255(r.a+e.a)}})),h(s)&&s.call(this,null,this),this}}),()=>({blur(t,e){if("number"!=typeof t)return l.call(this,"r must be a number",e);if(t<1)return l.call(this,"r must be greater than 0",e);let r,i,n,a,o,s,f,u,c,d,p,m,g,b;const _=this.bitmap.width-1,y=this.bitmap.height-1,w=t+1,v=Be[t],x=Te[t],E=[],k=[],S=[],M=[],A=[],I=[];let B=2;for(;B-- >0;){for(m=0,g=0,s=0;s_?_:f)<<2),r+=this.bitmap.data[u++],i+=this.bitmap.data[u++],n+=this.bitmap.data[u++],a+=this.bitmap.data[u];for(o=0;o0?u<<2:0),c=g+A[o],d=g+I[o],r+=this.bitmap.data[c++]-this.bitmap.data[d++],i+=this.bitmap.data[c++]-this.bitmap.data[d++],n+=this.bitmap.data[c++]-this.bitmap.data[d++],a+=this.bitmap.data[c]-this.bitmap.data[d],m++;g+=this.bitmap.width<<2}for(o=0;oy?0:this.bitmap.width,r+=E[p],i+=k[p],n+=S[p],a+=M[p];for(m=o<<2,s=0;s>>x,this.bitmap.data[m+3]=b,b>255&&(this.bitmap.data[m+3]=255),b>0?(b=255/b,this.bitmap.data[m]=(r*v>>>x)*b,this.bitmap.data[m+1]=(i*v>>>x)*b,this.bitmap.data[m+2]=(n*v>>>x)*b):(this.bitmap.data[m+2]=0,this.bitmap.data[m+1]=0,this.bitmap.data[m]=0),0===o&&(A[s]=((u=s+w)0?u*this.bitmap.width:0),c=o+A[s],d=o+I[s],r+=E[c]-E[d],i+=k[c]-k[d],n+=S[c]-S[d],a+=M[c]-M[d],m+=this.bitmap.width<<2}}return h(e)&&e.call(this,null,this),this}}),()=>({circle(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;"function"==typeof t&&(e=t,t={});const r=t.radius||(this.bitmap.width>this.bitmap.height?this.bitmap.height:this.bitmap.width)/2,i="number"==typeof t.x?t.x:this.bitmap.width/2,n="number"==typeof t.y?t.y:this.bitmap.height/2;return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,e,a){const o=Math.sqrt(Math.pow(t-i,2)+Math.pow(e-n,2));r-o<=0?this.bitmap.data[a+3]=0:r-o<1&&(this.bitmap.data[a+3]=255*(r-o))})),h(e)&&e.call(this,null,this),this}}),()=>({brightness(t,e){return"number"!=typeof t?l.call(this,"val must be numbers",e):t<-1||t>1?l.call(this,"val must be a number between -1 and +1",e):(this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(e,r,i){t<0?(this.bitmap.data[i]*=1+t,this.bitmap.data[i+1]*=1+t,this.bitmap.data[i+2]*=1+t):(this.bitmap.data[i]+=(255-this.bitmap.data[i])*t,this.bitmap.data[i+1]+=(255-this.bitmap.data[i+1])*t,this.bitmap.data[i+2]+=(255-this.bitmap.data[i+2])*t)})),h(e)&&e.call(this,null,this),this)},contrast(t,e){if("number"!=typeof t)return l.call(this,"val must be numbers",e);if(t<-1||t>1)return l.call(this,"val must be a number between -1 and +1",e);const r=(t+1)/(1-t);function i(t){return(t=Math.floor(r*(t-127)+127))<0?0:t>255?255:t}return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,e,r){this.bitmap.data[r]=i(this.bitmap.data[r]),this.bitmap.data[r+1]=i(this.bitmap.data[r+1]),this.bitmap.data[r+2]=i(this.bitmap.data[r+2])})),h(e)&&e.call(this,null,this),this},posterize(t,e){return"number"!=typeof t?l.call(this,"n must be numbers",e):(t<2&&(t=2),this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(e,r,i){this.bitmap.data[i]=Math.floor(this.bitmap.data[i]/255*(t-1))/(t-1)*255,this.bitmap.data[i+1]=Math.floor(this.bitmap.data[i+1]/255*(t-1))/(t-1)*255,this.bitmap.data[i+2]=Math.floor(this.bitmap.data[i+2]/255*(t-1))/(t-1)*255})),h(e)&&e.call(this,null,this),this)},greyscale:Le,grayscale:Le,opacity(t,e){return"number"!=typeof t?l.call(this,"f must be a number",e):t<0||t>1?l.call(this,"f must be a number from 0 to 1",e):(this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(e,r,i){const n=this.bitmap.data[i+3]*t;this.bitmap.data[i+3]=n})),h(e)&&e.call(this,null,this),this)},sepia(t){return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,e,r){let i=this.bitmap.data[r],n=this.bitmap.data[r+1],a=this.bitmap.data[r+2];i=.393*i+.769*n+.189*a,n=.349*i+.686*n+.168*a,a=.272*i+.534*n+.131*a,this.bitmap.data[r]=i<255?i:255,this.bitmap.data[r+1]=n<255?n:255,this.bitmap.data[r+2]=a<255?a:255})),h(t)&&t.call(this,null,this),this},fade(t,e){return"number"!=typeof t?l.call(this,"f must be a number",e):t<0||t>1?l.call(this,"f must be a number from 0 to 1",e):(this.opacity(1-t),h(e)&&e.call(this,null,this),this)},convolution(t,e,r){"function"==typeof e&&void 0===r&&(r=e,e=null),e||(e=this.constructor.EDGE_EXTEND);const i=Re.from(this.bitmap.data),n=t.length,a=t[0].length,o=Math.floor(n/2),s=Math.floor(a/2),l=-o,f=-s;let u,c,d,p,m,g,b,_,y,w;return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(r,n,a){p=0,d=0,c=0;for(let i=l;i<=o;i++)for(let a=f;a<=s;a++)_=r+a,y=n+i,u=t[i+o][a+s],w=this.getPixelIndex(_,y,e),-1===w?(b=0,g=0,m=0):(m=this.bitmap.data[w+0],g=this.bitmap.data[w+1],b=this.bitmap.data[w+2]),c+=u*m,d+=u*g,p+=u*b;c<0&&(c=0),d<0&&(d=0),p<0&&(p=0),c>255&&(c=255),d>255&&(d=255),p>255&&(p=255),i[a+0]=c,i[a+1]=d,i[a+2]=p})),this.bitmap.data=i,h(r)&&r.call(this,null,this),this},opaque(t){return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,e,r){this.bitmap.data[r+3]=255})),h(t)&&t.call(this,null,this),this},pixelate(t,e,r,i,n,a){if("function"==typeof e)a=e,n=null,i=null,r=null,e=null;else{if("number"!=typeof t)return l.call(this,"size must be a number",a);if(Oe(e)&&"number"!=typeof e)return l.call(this,"x must be a number",a);if(Oe(r)&&"number"!=typeof r)return l.call(this,"y must be a number",a);if(Oe(i)&&"number"!=typeof i)return l.call(this,"w must be a number",a);if(Oe(n)&&"number"!=typeof n)return l.call(this,"h must be a number",a)}const o=[[1/16,2/16,1/16],[2/16,.25,2/16],[1/16,2/16,1/16]];e=e||0,r=r||0,i=Oe(i)?i:this.bitmap.width-e,n=Oe(n)?n:this.bitmap.height-r;const s=this.cloneQuiet();return this.scanQuiet(e,r,i,n,(function(e,r,i){e=t*Math.floor(e/t),r=t*Math.floor(r/t);const n=Pe(s,o,e,r);this.bitmap.data[i]=n[0],this.bitmap.data[i+1]=n[1],this.bitmap.data[i+2]=n[2]})),h(a)&&a.call(this,null,this),this},convolute(t,e,r,i,n,a){if(!Array.isArray(t))return l.call(this,"the kernel must be an array",a);if("function"==typeof e)a=e,e=null,r=null,i=null,n=null;else{if(Oe(e)&&"number"!=typeof e)return l.call(this,"x must be a number",a);if(Oe(r)&&"number"!=typeof r)return l.call(this,"y must be a number",a);if(Oe(i)&&"number"!=typeof i)return l.call(this,"w must be a number",a);if(Oe(n)&&"number"!=typeof n)return l.call(this,"h must be a number",a)}e=Oe(e)?e:0,r=Oe(r)?r:0,i=Oe(i)?i:this.bitmap.width-e,n=Oe(n)?n:this.bitmap.height-r;const o=this.cloneQuiet();return this.scanQuiet(e,r,i,n,(function(e,r,i){const n=Pe(o,t,e,r);this.bitmap.data[i]=this.constructor.limit255(n[0]),this.bitmap.data[i+1]=this.constructor.limit255(n[1]),this.bitmap.data[i+2]=this.constructor.limit255(n[2])})),h(a)&&a.call(this,null,this),this},color:Ue,colour:Ue}),()=>({contain(t,e,r,i,n){if("number"!=typeof t||"number"!=typeof e)return l.call(this,"w and h must be numbers",n);"string"==typeof r&&("function"==typeof i&&void 0===n&&(n=i),i=r,r=null),"function"==typeof r&&(void 0===n&&(n=r),i=null,r=null),"function"==typeof i&&void 0===n&&(n=i,i=null);const a=7&(r=r||this.constructor.HORIZONTAL_ALIGN_CENTER|this.constructor.VERTICAL_ALIGN_MIDDLE),o=r>>3;if((0===a||a&a-1)&&(0===o||o&o-1))return l.call(this,"only use one flag per alignment direction",n);const s=a>>1,f=o>>1,u=t/e>this.bitmap.width/this.bitmap.height?e/this.bitmap.height:t/this.bitmap.width,c=this.cloneQuiet().scale(u,i);return this.resize(t,e,i),this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,e,r){this.bitmap.data.writeUInt32BE(this._background,r)})),this.blit(c,(this.bitmap.width-c.bitmap.width)/2*s,(this.bitmap.height-c.bitmap.height)/2*f),h(n)&&n.call(this,null,this),this}}),()=>({cover(t,e,r,i,n){if("number"!=typeof t||"number"!=typeof e)return l.call(this,"w and h must be numbers",n);r&&"function"==typeof r&&void 0===n?(n=r,r=null,i=null):"function"==typeof i&&void 0===n&&(n=i,i=null);const a=7&(r=r||this.constructor.HORIZONTAL_ALIGN_CENTER|this.constructor.VERTICAL_ALIGN_MIDDLE),o=r>>3;if((0===a||a&a-1)&&(0===o||o&o-1))return l.call(this,"only use one flag per alignment direction",n);const s=a>>1,f=o>>1,u=t/e>this.bitmap.width/this.bitmap.height?t/this.bitmap.width:e/this.bitmap.height;return this.scale(u,i),this.crop((this.bitmap.width-t)/2*s,(this.bitmap.height-e)/2*f,t,e),h(n)&&n.call(this,null,this),this}}),function(t){return t("crop",(function(t,e,r,i,n){if("number"!=typeof t||"number"!=typeof e)return l.call(this,"x and y must be numbers",n);if("number"!=typeof r||"number"!=typeof i)return l.call(this,"w and h must be numbers",n);if(t=Math.round(t),e=Math.round(e),r=Math.round(r),i=Math.round(i),0===t&&r===this.bitmap.width){const n=r*e+t<<2,a=n+(i*r<<2);this.bitmap.data=this.bitmap.data.slice(n,a)}else{const n=ze.allocUnsafe(r*i*4);let a=0;this.scanQuiet(t,e,r,i,(function(t,e,r){const i=this.bitmap.data.readUInt32BE(r,!0);n.writeUInt32BE(i,a,!0),a+=4})),this.bitmap.data=n}return this.bitmap.width=r,this.bitmap.height=i,h(n)&&n.call(this,null,this),this})),{class:{autocrop(){const t=this.bitmap.width,e=this.bitmap.height;let r,i=0,n=2e-4,a=!0,o=!1,s={north:!1,south:!1,east:!1,west:!1};for(var l=arguments.length,f=new Array(l),u=0;un)break t}p++}if(c=this.getPixelColor(t,0),!s.west)t:for(let r=0;rn)break t}b++}if(c=this.getPixelColor(0,e),!s.south)t:for(let r=e-1;r>=p+1;r--){for(let e=t-m-1;e>=0;e--){const t=this.getPixelColor(e,r),i=this.constructor.intToRGBA(t);if(this.constructor.colorDiff(d,i)>n)break t}g++}if(c=this.getPixelColor(t,e),!s.east)t:for(let r=t-1;r>=0+b+1;r--){for(let t=e-1;t>=0+p;t--){const e=this.getPixelColor(r,t),i=this.constructor.intToRGBA(e);if(this.constructor.colorDiff(d,i)>n)break t}m++}let _=!1;if(b-=i,m-=i,p-=i,g-=i,o){const t=Math.min(m,b),e=Math.min(p,g);b=t,m=t,p=e,g=e}b=b>=0?b:0,m=m>=0?m:0,p=p>=0?p:0,g=g>=0?g:0;const y=t-(b+m),w=e-(g+p);return _=a?0!==m&&0!==p&&0!==b&&0!==g:0!==m||0!==p||0!==b||0!==g,_&&this.crop(b,p,y,w),h(r)&&r.call(this,null,this),this}}}},()=>({displace(t,e,r){if("object"!=typeof t||t.constructor!==this.constructor)return l.call(this,"The source must be a Jimp image",r);if("number"!=typeof e)return l.call(this,"factor must be a number",r);const i=this.cloneQuiet();return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(r,n,a){let o=t.bitmap.data[a]/256*e;o=Math.round(o);const s=this.getPixelIndex(r+o,n);this.bitmap.data[s]=i.bitmap.data[a],this.bitmap.data[s+1]=i.bitmap.data[a+1],this.bitmap.data[s+2]=i.bitmap.data[a+2]})),h(r)&&r.call(this,null,this),this}}),()=>({dither565:De,dither16:De}),()=>({fisheye(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{r:2.5},e=arguments.length>1?arguments[1]:void 0;"function"==typeof t&&(e=t,t={r:2.5});const r=this.cloneQuiet(),{width:i,height:n}=r.bitmap;return r.scanQuiet(0,0,i,n,((e,a)=>{const o=e/i,s=a/n,h=Math.sqrt(Math.pow(o-.5,2)+Math.pow(s-.5,2)),l=2*Math.pow(h,t.r),f=(o-.5)/h,u=(s-.5)/h,c=Math.round((l*f+.5)*i),d=Math.round((l*u+.5)*n),p=r.getPixelColor(c,d);this.setPixelColor(p,e,a)})),this.setPixelColor(r.getPixelColor(i/2,n/2),i/2,n/2),h(e)&&e.call(this,null,this),this}}),()=>({flip:Fe,mirror:Fe}),()=>({gaussian(t,e){if("number"!=typeof t)return l.call(this,"r must be a number",e);if(t<1)return l.call(this,"r must be greater than 0",e);const r=Math.ceil(2.57*t),i=2*r+1,n=t*t*2,a=n*Math.PI,o=[];for(let t=0;t({invert(t){return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,e,r){this.bitmap.data[r]=255-this.bitmap.data[r],this.bitmap.data[r+1]=255-this.bitmap.data[r+1],this.bitmap.data[r+2]=255-this.bitmap.data[r+2]})),h(t)&&t.call(this,null,this),this}}),()=>({mask(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3?arguments[3]:void 0;if(!(t instanceof this.constructor))return l.call(this,"The source must be a Jimp image",i);if("number"!=typeof e||"number"!=typeof r)return l.call(this,"x and y must be numbers",i);e=Math.round(e),r=Math.round(r);const n=this.bitmap.width,a=this.bitmap.height,o=this;return t.scanQuiet(0,0,t.bitmap.width,t.bitmap.height,(function(t,i,s){const h=e+t,l=r+i;if(h>=0&&l>=0&&h({normalize(t){const e=je.call(this),r={r:He(e.r),g:He(e.g),b:He(e.b)};return this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,(function(t,e,i){const n=this.bitmap.data[i+0],a=this.bitmap.data[i+1],o=this.bitmap.data[i+2];this.bitmap.data[i+0]=Ge(n,r.r[0],r.r[1]),this.bitmap.data[i+1]=Ge(a,r.g[0],r.g[1]),this.bitmap.data[i+2]=Ge(o,r.b[0],r.b[1])})),h(t)&&t.call(this,null,this),this}}),()=>({constants:{measureText:Ze,measureTextHeight:Ve,FONT_SANS_8_BLACK:a().join(Qe,"fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt"),FONT_SANS_10_BLACK:a().join(Qe,"fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt"),FONT_SANS_12_BLACK:a().join(Qe,"fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt"),FONT_SANS_14_BLACK:a().join(Qe,"fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt"),FONT_SANS_16_BLACK:a().join(Qe,"fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt"),FONT_SANS_32_BLACK:a().join(Qe,"fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt"),FONT_SANS_64_BLACK:a().join(Qe,"fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt"),FONT_SANS_128_BLACK:a().join(Qe,"fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt"),FONT_SANS_8_WHITE:a().join(Qe,"fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt"),FONT_SANS_16_WHITE:a().join(Qe,"fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt"),FONT_SANS_32_WHITE:a().join(Qe,"fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt"),FONT_SANS_64_WHITE:a().join(Qe,"fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt"),FONT_SANS_128_WHITE:a().join(Qe,"fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt"),loadFont(t,e){return"string"!=typeof t?l.call(this,"file must be a string",e):new Promise(((r,i)=>{e=e||function(t,e){t?i(t):r(e)},qe()(t,((r,i)=>{const n={},o={};if(r)return l.call(this,r,e);for(let t=0;tt.read(e+"/"+r)));return Promise.all(i)})(this,a().dirname(t),i.pages).then((t=>{e(null,{chars:n,kernings:o,pages:t,common:i.common,info:i.info})}))}))}))}},class:{print(t,e,r,i,n,a,o){if("function"==typeof n&&void 0===o&&(o=n,n=1/0),void 0===n&&(n=1/0),"function"==typeof a&&void 0===o&&(o=a,a=1/0),void 0===a&&(a=1/0),"object"!=typeof t)return l.call(this,"font must be a Jimp loadFont",o);if("number"!=typeof e||"number"!=typeof r||"number"!=typeof n)return l.call(this,"x, y and maxWidth must be numbers",o);if("number"!=typeof n)return l.call(this,"maxWidth must be a number",o);if("number"!=typeof a)return l.call(this,"maxHeight must be a number",o);let s,f;"object"==typeof i&&null!==i.text&&void 0!==i.text?(s=i.alignmentX||this.constructor.HORIZONTAL_ALIGN_LEFT,f=i.alignmentY||this.constructor.VERTICAL_ALIGN_TOP,({text:i}=i)):(s=this.constructor.HORIZONTAL_ALIGN_LEFT,f=this.constructor.VERTICAL_ALIGN_TOP,i=i.toString()),a!==1/0&&f===this.constructor.VERTICAL_ALIGN_BOTTOM?r+=a-Ve(t,i,n):a!==1/0&&f===this.constructor.VERTICAL_ALIGN_MIDDLE&&(r+=a/2-Ve(t,i,n)/2);const u=Object.entries(t.chars)[0][1].xadvance,{lines:c,longestLine:d}=Ye(t,i,n);return c.forEach((i=>{const a=i.join(" "),o=function(t,e,r,i,n){return n===t.HORIZONTAL_ALIGN_LEFT?0:n===t.HORIZONTAL_ALIGN_CENTER?(i-Ze(e,r))/2:i-Ze(e,r)}(this.constructor,t,a,n,s);Je.call(this,t,e+o,r,a,u),r+=t.common.lineHeight})),h(o)&&o.call(this,null,this,{x:e+d,y:r}),this}}}),()=>({constants:{RESIZE_NEAREST_NEIGHBOR:"nearestNeighbor",RESIZE_BILINEAR:"bilinearInterpolation",RESIZE_BICUBIC:"bicubicInterpolation",RESIZE_HERMITE:"hermiteInterpolation",RESIZE_BEZIER:"bezierInterpolation"},class:{resize(t,e,r,i){if("number"!=typeof t||"number"!=typeof e)return l.call(this,"w and h must be numbers",i);if("function"==typeof r&&void 0===i&&(i=r,r=null),t===this.constructor.AUTO&&e===this.constructor.AUTO)return l.call(this,"w and h cannot both be set to auto",i);if(t===this.constructor.AUTO&&(t=this.bitmap.width*(e/this.bitmap.height)),e===this.constructor.AUTO&&(e=this.bitmap.height*(t/this.bitmap.width)),t<0||e<0)return l.call(this,"w and h must be positive numbers",i);if(t=Math.round(t)||1,e=Math.round(e)||1,"function"==typeof rr[r]){const i={data:ir.alloc(t*e*4),width:t,height:e};rr[r](this.bitmap,i),this.bitmap=i}else{const r=this;new $e(this.bitmap.width,this.bitmap.height,t,e,!0,!0,(i=>{r.bitmap.data=ir.from(i),r.bitmap.width=t,r.bitmap.height=e})).resize(this.bitmap.data)}return h(i)&&i.call(this,null,this),this}}}),()=>({rotate(t,e,r){return null==e&&(e=!0),"function"==typeof e&&void 0===r&&(r=e,e=!0),"number"!=typeof t?l.call(this,"deg must be a number",r):"boolean"!=typeof e&&"string"!=typeof e?l.call(this,"mode must be a boolean or a string",r):(t%90!=0||!e&&this.bitmap.width!==this.bitmap.height&&t%180!=0?or.call(this,t,e,r):ar.call(this,t),h(r)&&r.call(this,null,this),this)}}),()=>({scale(t,e,r){if("number"!=typeof t)return l.call(this,"f must be a number",r);if(t<0)return l.call(this,"f must be a positive number",r);"function"==typeof e&&void 0===r&&(r=e,e=null);const i=this.bitmap.width*t,n=this.bitmap.height*t;return this.resize(i,n,e),h(r)&&r.call(this,null,this),this},scaleToFit(t,e,r,i){if("number"!=typeof t||"number"!=typeof e)return l.call(this,"w and h must be numbers",i);"function"==typeof r&&void 0===i&&(i=r,r=null);const n=t/e>this.bitmap.width/this.bitmap.height?e/this.bitmap.height:t/this.bitmap.width;return this.scale(n,r),h(i)&&i.call(this,null,this),this}}),()=>({shadow(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;"function"==typeof t&&(e=t,t={});const{opacity:r=.7,size:i=1.1,x:n=-25,y:a=25,blur:o=5}=t,s=this.clone(),l=this.clone();return l.scan(0,0,l.bitmap.width,l.bitmap.height,((t,e,i)=>{l.bitmap.data[i]=0,l.bitmap.data[i+1]=0,l.bitmap.data[i+2]=0,l.bitmap.data[i+3]=l.constructor.limit255(l.bitmap.data[i+3]*r),this.bitmap.data[i]=0,this.bitmap.data[i+1]=0,this.bitmap.data[i+2]=0,this.bitmap.data[i+3]=0})),l.resize(l.bitmap.width*i,l.bitmap.height*i).blur(o),this.composite(l,n,a),this.composite(s,0,0),h(e)&&e.call(this,null,this),this}}),()=>({threshold(t,e){let{max:r,replace:i=255,autoGreyscale:n=!0}=t;return"number"!=typeof r?l.call(this,"max must be a number",e):"number"!=typeof i?l.call(this,"replace must be a number",e):"boolean"!=typeof n?l.call(this,"autoGreyscale must be a boolean",e):(r=this.constructor.limit255(r),i=this.constructor.limit255(i),n&&this.greyscale(),this.scanQuiet(0,0,this.bitmap.width,this.bitmap.height,((t,e,n)=>{const a=this.bitmap.data[n]1&&void 0!==arguments[1]?arguments[1]:oe;const r={hasAlpha:{},encoders:{},decoders:{},class:{},constants:{}};function i(t){Object.entries(t).forEach((t=>{let[e,i]=t;r[e]={...r[e],...i}}))}t.types&&(t.types.forEach((function(t){const e=t();Array.isArray(e.mime)?Ct(...e.mime):Object.entries(e.mime).forEach((t=>Ct(...t))),delete e.mime,i(e)})),e.decoders={...e.decoders,...r.decoders},e.encoders={...e.encoders,...r.encoders},e.hasAlpha={...e.hasAlpha,...r.hasAlpha}),t.plugins&&t.plugins.forEach((function(t){const e=t(ae)||{};e.class||e.constants?i(e):i({class:e})})),ie(r.class,e),re(r.constants,e)}({types:[()=>(0,se.Ee)(ue(),pe(),{mime:{[be]:["bmp"]},constants:{MIME_BMP:be,MIME_X_MS_BMP:_e},decoders:{[be]:ye,[_e]:ye},encoders:{[be]:we,[_e]:we}},{mime:{[ke]:["tiff","tif"]},constants:{MIME_TIFF:ke},decoders:{[ke]:t=>{const e=xe().decode(t),r=e[0];e.forEach((e=>{xe().decodeImage(t,e)}));const i=xe().toRGBA8(r);return{data:Ee.from(i),width:r.t256[0],height:r.t257[0]}}},encoders:{[ke]:t=>{const e=xe().encodeImage(t.bitmap.data,t.bitmap.width,t.bitmap.height);return Ee.from(e)}}},{mime:{[Ie]:["gif"]},constants:{MIME_GIF:Ie},decoders:{[Ie]:t=>{const e=new Se.N(t),r=Ae.alloc(e.width*e.height*4);return e.decodeAndBlitFrameRGBA(0,r),{data:r,width:e.width,height:e.height}}},encoders:{[Ie]:t=>{const e=new Me.BitmapImage(t.bitmap);Me.GifUtil.quantizeDekker(e,256);const r=new Me.GifFrame(e);return(new Me.GifCodec).encodeGif([r],{}).then((t=>t.buffer))}}})],plugins:[t=>{const e=sr.map((e=>{let r=e(t)||{};return r.class||r.constants||(r={class:r}),r}));return(0,se.Ee)(...e)}]})})()})(); +//# sourceMappingURL=jimp.js.map \ No newline at end of file diff --git a/node_modules/jimp/browser/lib/jimp.js.LICENSE.txt b/node_modules/jimp/browser/lib/jimp.js.LICENSE.txt new file mode 100644 index 00000000..b0ed320f --- /dev/null +++ b/node_modules/jimp/browser/lib/jimp.js.LICENSE.txt @@ -0,0 +1,277 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +/*! + * Timm + * + * Immutability helpers with fast reads and acceptable writes. + * + * @copyright Guillermo Grau Panea 2016 + * @license MIT + */ + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * cie94.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * ciede2000.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * cmetric.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * common.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * constants.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * ditherErrorDiffusionArray.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * euclidean.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * helper.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * hueStatistics.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * iq.ts - Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * lab2rgb.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * lab2xyz.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * manhattanNeuQuant.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * nearestColor.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * palette.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * pngQuant.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * point.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * pointContainer.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * rgb2hsl.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * rgb2lab.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * rgb2xyz.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * ssim.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * wuQuant.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * xyz2lab.ts - part of Image Quantization Library + */ + +/** + * @preserve + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * xyz2rgb.ts - part of Image Quantization Library + */ + +/** + * @preserve + * MIT License + * + * Copyright 2015-2018 Igor Bezkrovnyi + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * riemersma.ts - part of Image Quantization Library + */ + +/** + * @preserve TypeScript port: + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * colorHistogram.ts - part of Image Quantization Library + */ + +/** + * @preserve TypeScript port: + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * neuquant.ts - part of Image Quantization Library + */ + +/** + * @preserve TypeScript port: + * Copyright 2015-2018 Igor Bezkrovnyi + * All rights reserved. (MIT Licensed) + * + * rgbquant.ts - part of Image Quantization Library + */ diff --git a/node_modules/jimp/browser/lib/jimp.js.map b/node_modules/jimp/browser/lib/jimp.js.map new file mode 100644 index 00000000..b88b007a --- /dev/null +++ b/node_modules/jimp/browser/lib/jimp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jimp.js","mappings":";6CAAA,IAAIA,EAAY,EAAQ,MAUxB,SAASC,EAAQC,EAAaC,GAC1B,IAAIC,EAAY,IAAIJ,EAAUE,EAAaC,GAQ3C,OAAO,SAAUE,GACb,OAAOD,EAAUE,QAAQD,EAC7B,CACJ,CAEAJ,EAAQM,IAAM,KACdN,EAAQO,IAAM,WACdP,EAAQQ,IAAM,aACdR,EAAQS,IAAM,mBAEdC,EAAOC,QAAUX,yBCpBjB,SAASD,EAAUE,EAAaC,GAC5B,KAAKD,GAAgBC,GAAgBD,EAAYW,QAAWV,EAAYU,QACpE,MAAM,IAAIC,MAAM,gBAEpBC,KAAKb,YAAcA,EACnBa,KAAKZ,YAAcA,CACvB,CASAH,EAAUgB,UAAUV,QAAU,SAASD,GACnC,IAAIY,EAAGC,EAAQC,EACfC,EAAY,CAAC,EACbC,EAAWN,KAAKb,YAAYW,OAC5BS,EAASP,KAAKZ,YAAYU,OAC1BA,EAASR,EAAOQ,OAChBU,EAA2B,iBAAXlB,EAAsB,GAAK,GAE3C,IAAKU,KAAKS,QAAQnB,GACd,MAAM,IAAIS,MAAM,WAAaT,EAAS,wCAA0CU,KAAKb,YAAc,KAGvG,GAAIa,KAAKb,cAAgBa,KAAKZ,YAC1B,OAAOE,EAGX,IAAKY,EAAI,EAAGA,EAAIJ,EAAQI,IACpBG,EAAUH,GAAKF,KAAKb,YAAYuB,QAAQpB,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,KAAKme,YAAane,KAAK4D,OAASA,EAAQ9D,GAASE,KAAKyR,aAAczR,KAAKkb,OAAQlb,KAAKoe,aAClH,GAGDxe,EAAOC,QAAUub,YCjGjBxb,EAAOC,QAAU,CAChBmf,KAAO,CACN,EAAS,eACT,EAAS,iBACT,GAAS,qBACT,IAAS,cACT,IAAS,iBACT,IAAS,aACT,IAAS,cACT,IAAS,gBACT,IAAS,cACT,IAAS,4BACT,IAAS,eACT,IAAS,YACT,IAAS,aACT,IAAS,YACT,IAAS,eACT,IAAS,mBACT,IAAS,OACT,IAAS,QACT,IAAS,eACT,IAAS,cACT,IAAS,kBACT,IAAS,eACT,IAAS,kBACT,IAAS,iBACT,IAAS,iBACT,IAAS,cACT,IAAS,cACT,IAAS,sBACT,IAAS,WACT,IAAS,YACT,IAAS,YACT,IAAS,cACT,IAAS,iBACT,IAAS,mBACT,IAAS,oBACT,IAAS,YACT,IAAS,YACT,IAAS,iBACT,IAAS,aACT,IAAS,oBACT,IAAS,mBACT,IAAS,WACT,IAAS,aACT,IAAS,SACT,IAAS,eACT,IAAS,YACT,IAAS,aACT,IAAS,wBACT,IAAS,WACT,IAAS,gBACT,IAAS,YACT,IAAS,aACT,IAAS,cACT,IAAS,iBACT,IAAS,cACT,IAAS,eACT,IAAS,yBACT,IAAS,SACT,IAAS,SACT,IAAS,WACT,IAAS,eACT,IAAS,WACT,IAAS,gBACT,IAAS,eACT,IAAS,eACT,IAAS,kBACT,IAAS,kBACT,IAAS,gBACT,IAAS,WACT,IAAS,iBACT,IAAS,iBACT,IAAS,UACT,IAAS,aACT,IAAS,WACT,IAAS,sBACT,IAAS,cACT,IAAS,aACT,IAAS,gBACT,IAAS,cACT,IAAS,aACT,IAAS,SACT,IAAS,oBACT,IAAS,aACT,IAAS,aACT,IAAS,WACT,IAAS,kBACT,IAAS,kBACT,IAAS,sBACT,IAAS,yBACT,IAAS,sBACT,IAAS,cACT,IAAS,eACT,IAAS,eACT,IAAS,oBACT,IAAS,mBACT,IAAS,mBACT,IAAS,sBACT,IAAS,iBACT,IAAS,mBACT,IAAS,qBACT,KAAS,yBACT,KAAS,oBACT,KAAS,qBACT,MAAS,SACT,MAAS,aACT,MAAS,aACT,MAAS,gBACT,MAAS,UACT,MAAS,WACT,MAAS,iBACT,MAAS,WACT,MAAS,WACT,MAAS,WACT,MAAS,WACT,MAAS,aACT,MAAS,YACT,MAAS,SACT,MAAS,sBACT,MAAS,cACT,MAAS,eACT,MAAS,WACT,MAAS,YACT,MAAS,eACT,MAAS,UACT,MAAS,YACT,MAAS,eACT,MAAS,eACT,MAAS,YACT,MAAS,eACT,MAAS,aACT,MAAS,aACT,MAAS,cACT,MAAS,aACT,MAAS,cACT,MAAS,iBACT,MAAS,UACT,MAAS,UACT,MAAS,UACT,MAAS,UACT,MAAS,WACT,MAAS,uBACT,MAAS,0BACT,MAAS,mBACT,MAAS,eACT,MAAS,gBACT,MAAS,OACT,MAAS,gBACT,MAAS,YACT,MAAS,gBACT,MAAS,mBACT,MAAS,2BACT,MAAS,aACT,MAAS,sBACT,MAAS,2BACT,MAAS,kBACT,MAAS,uBACT,MAAS,sBACT,MAAS,wBACT,MAAS,wBACT,MAAS,UACT,MAAS,gBACT,MAAS,iBACT,MAAS,UACT,MAAS,YACT,MAAS,wBACT,MAAS,iBACT,MAAS,gBACT,MAAS,WACT,MAAS,oBACT,MAAS,aACT,MAAS,cACT,MAAS,oBACT,MAAS,gBACT,MAAS,aACT,MAAS,aACT,MAAS,aACT,MAAS,mBACT,MAAS,sBACT,MAAS,qBACT,MAAS,kBACT,MAAS,sBACT,MAAS,UACT,MAAS,MACT,MAAS,0BACT,MAAS,YACT,MAAS,iBACT,MAAS,gBACT,MAAS,kBACT,MAAS,4BACT,MAAS,2BACT,MAAS,WACT,MAAS,sBACT,MAAS,sBACT,MAAS,gBACT,MAAS,gBACT,MAAS,cACT,MAAS,aACT,MAAS,cACT,MAAS,mBACT,MAAS,aACT,MAAS,0BACT,MAAS,yBACT,MAAS,oBACT,MAAS,gBACT,MAAS,kBACT,MAAS,uBACT,MAAS,mBACT,MAAS,kBACT,MAAS,eACT,MAAS,cACT,MAAS,QACT,MAAS,cACT,MAAS,cACT,MAAS,2BACT,MAAS,QACT,MAAS,wBACT,MAAS,wBACT,MAAS,2BACT,MAAS,cACT,MAAS,yBACT,MAAS,eACT,MAAS,cACT,MAAS,gBACT,MAAS,oBACT,MAAS,gBACT,MAAS,eACT,MAAS,YACT,MAAS,WACT,MAAS,UACT,MAAS,YACT,MAAS,cACT,MAAS,aACT,MAAS,qBACT,MAAS,sBACT,MAAS,iBACT,MAAS,uBACT,MAAS,yBACT,MAAS,kBACT,MAAS,UACT,MAAS,YACT,MAAS,WACT,MAAS,aACT,MAAS,YACT,MAAS,kBACT,MAAS,aACT,MAAS,iBACT,MAAS,kBACT,MAAS,mBACT,MAAS,gBACT,MAAS,cACT,MAAS,2BACT,MAAS,QACT,MAAS,wBACT,MAAS,wBACT,MAAS,2BACT,MAAS,cACT,MAAS,yBACT,MAAS,eACT,MAAS,kBACT,MAAS,gBACT,MAAS,oBACT,MAAS,gBACT,MAAS,aACT,MAAS,YACT,MAAS,aACT,MAAS,iBACT,MAAS,eACT,MAAS,eACT,MAAS,mBACT,MAAS,0BACT,MAAS,mBACT,MAAS,cACT,MAAS,WACT,MAAS,aACT,MAAS,YACT,MAAS,2BACT,MAAS,uBACT,MAAS,gBACT,MAAS,YACT,MAAS,eACT,MAAS,WACT,MAAS,WACT,MAAS,YACT,MAAS,mBACT,MAAS,eACT,MAAS,aACT,MAAS,QACT,MAAS,iBACT,MAAS,aACT,MAAS,aACT,MAAS,mBACT,MAAS,gBACT,MAAS,kBACT,MAAS,cACT,MAAS,iBACT,MAAS,eACT,MAAS,YACT,MAAS,aACT,MAAS,cACT,MAAS,kBACT,MAAS,mBACT,MAAS,cACT,MAAS,iBACT,MAAS,cACT,MAAS,iBACT,MAAS,mBACT,MAAS,mBACT,MAAS,iBACT,MAAS,yBACT,MAAS,cACT,MAAS,gBACT,MAAS,cACT,MAAS,UACT,MAAS,2BACT,MAAS,aACT,MAAS,qBACT,MAAS,oBACT,MAAS,uBACT,MAAS,gBACT,MAAS,YACT,MAAS,qBACT,MAAS,sBACT,MAAS,aACT,MAAS,mBACT,MAAS,mBACT,MAAS,aACT,MAAS,eACT,MAAS,oBACT,MAAS,kBACT,MAAS,eACT,MAAS,eACT,MAAS,qBACT,MAAS,qBACT,MAAS,mBACT,MAAS,mBACT,MAAS,gBACT,MAAS,gBACT,MAAS,gBACT,MAAS,mBACT,MAAS,gBACT,MAAS,oBACT,MAAS,kBACT,MAAS,sBACT,MAAS,qBACT,MAAS,cACT,MAAS,mBACT,MAAS,oBACT,MAAS,cACT,MAAS,iBACT,MAAS,kBACT,MAAS,uBACT,MAAS,yBACT,MAAS,yBACT,MAAS,mBACT,MAAS,kBACT,MAAS,qBACT,MAAS,sBACT,MAAS,sBACT,MAAS,aACT,MAAS,cACT,MAAS,mBACT,MAAS,yBACT,MAAS,oBACT,MAAS,0BACT,MAAS,wBACT,MAAS,iBACT,MAAS,kBACT,MAAS,uBACT,MAAS,wBACT,MAAS,aACT,MAAS,oBACT,MAAS,wBACT,MAAS,cACT,MAAS,uBACT,MAAS,wBACT,MAAS,wBACT,MAAS,mBACT,MAAS,qBACT,MAAS,mBACT,MAAS,iBACT,MAAS,iBACT,MAAS,yBACT,MAAS,4BACT,MAAS,sBACT,MAAS,wBACT,MAAS,oBACT,MAAS,kBACT,MAAS,iBACT,MAAS,wBACT,MAAS,mBACT,MAAS,sBACT,MAAS,uBACT,MAAS,uBACT,MAAS,cACT,MAAS,cACT,MAAS,cACT,MAAS,eACT,MAAS,YACT,MAAS,YACT,MAAS,QACT,MAAS,WACT,MAAS,2BACT,MAAS,0BACT,MAAS,0BACT,MAAS,cACT,MAAS,2BACT,MAAS,2BACT,MAAS,yBACT,MAAS,qBACT,MAAS,oBACT,MAAS,mBACT,MAAS,kBACT,MAAS,UACT,MAAS,eACT,KAAS,YACT,MAAS,eAC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MACA,OACA,MACA,OACA,OACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,OACA,MACA,MACA,OACA,MACA,MACA,MACA,KACA,MACA,KACA,MACA,MACA,MACA,MACA,OACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,OACA,OACA,MACA,MACA,MACA,MACA,OACA,MACA,MACA,MACA,OACA,OACA,QACA,MACA,MACA,MACA,MACA,MACA,KACA,KACA,SACA,MACA,MACA,MACA,MACA,MACA,KACA,MACA,IACA,KACA,MACA,MACA,MACA,QACA,MACA,OACA,OACA,OACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,OACA,OACA,MACA,MACA,MACA,KACA,MACA,MACA,MACA,OACA,MACA,MACA,QACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,QACA,MACA,MACA,MACA,KACA,MACA,KACA,KACA,MACA,OACA,MACA,MACA,MACA,OACA,MACA,MACA,MACA,MACA,MACA,OAEDC,UAAW,CACV,aACA,YACA,YACA,aACA,aACA,cACA,oBACA,oBACA,aACA,YACA,qBACA,4BACA,yBACA,uBACA,0BACA,0CACA,iDACA,kDACA,0EACA,4EACA,oEACA,kBACA,oBACA,+BACA,mBACA,sBACA,8BACA,gCACA,6BACA,YACA,aACA,mBACA,aACA,kBACA,gBACA,iBACA,cACA,iBACA,iBACA,yBACA,aACA,aACA,aACA,YACA,aACA,YACA,YACA,kBACA,eACA,YACA,gBACA,YACA,kBACA,2BACA,gCACA,kBACA,mBACA,YACA,aACA,gCACA,WACA,WACA,eACA,cACA,yBACA,kBACA,mBACA,wBACA,iCACA,wCACA,oCACA,oBACA,6BACA,oBACA,yBACA,qBACA,oBACA,oBACA,kBACA,aACA,wBACA,YACA,YACA,YACA,YACA,YACA,aACA,kBACA,iCACA,aACA,sBACA,aACA,sBACA,aACA,YACA,oBACA,mBACA,gBACA,aACA,oBACA,+BACA,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B,MAAO,CACLjrD,KAAM,GAAOkE,KAAK4oB,GAClBjuB,MAAOosD,EAAK05F,KAAK,GACjB7lJ,OAAQmsD,EAAK25F,KAAK,GACnB,GAGLxa,SAAU,CACR,CAAC,IAAYj8G,IACX,MAAM02H,EAAO,iBAAiB12H,EAAMxC,OAAO3rB,KAAMmuB,EAAMxC,OAAO9sB,MAAOsvB,EAAMxC,OAAO7sB,QAClF,OAAO,GAAOoF,KAAK2gJ,EAAK,ICxBR,CACpBtnI,KAAM,CACJ,CAAC,IAAY,CAAC,QAEhBm4C,UAAW,CACTovF,SAAU,IAEZvb,SAAU,CACR,CAAC,IAAYvpI,IACX,MAAM+kJ,EAAS,IAAI,KAAc/kJ,GAC3BglJ,EAAU,GAAOt6I,MAAMq6I,EAAOlmJ,MAAQkmJ,EAAOjmJ,OAAS,GAE5D,OADAimJ,EAAOx5H,uBAAuB,EAAGy5H,GAC1B,CACLhlJ,KAAMglJ,EACNnmJ,MAAOkmJ,EAAOlmJ,MACdC,OAAQimJ,EAAOjmJ,OAChB,GAGLsrI,SAAU,CACR,CAAC,IAAYpqI,IACX,MAAM2rB,EAAS,IAAI,GAAAH,YAAYxrB,EAAK2rB,QACpC,GAAAuE,QAAA,eAAuBvE,EAAQ,KAC/B,MAAMs5H,EAAW,IAAI,GAAA90H,SAASxE,GAE9B,OADiB,IAAI,GAAAmG,UACLS,UAAU,CAAC0yH,GAAW,CAAC,GAAGntH,MAAKotH,GACtCA,EAAOlnJ,QACd,M4BvBN09I,QAAS,CjBgBK7N,IACd,MAAMsX,EAAqBzJ,GAAQxjI,KAAIosI,IACrC,IAAIC,EAASD,EAAazW,IAAiB,CAAC,EAO5C,OANK0W,EAAO7U,OAAU6U,EAAO7uF,YAE3B6uF,EAAS,CACP7U,MAAO6U,IAGJA,CAAM,IAEf,OAAO,YAAaY,EACrB","sources":["webpack://jimp/../../node_modules/any-base/index.js","webpack://jimp/../../node_modules/any-base/src/converter.js","webpack://jimp/../../node_modules/base64-js/index.js","webpack://jimp/../../node_modules/bmp-js/index.js","webpack://jimp/../../node_modules/bmp-js/lib/decoder.js","webpack://jimp/../../node_modules/bmp-js/lib/encoder.js","webpack://jimp/../../node_modules/buffer-equal/index.js","webpack://jimp/../../node_modules/buffer/index.js","webpack://jimp/../../node_modules/buffer/node_modules/ieee754/index.js","webpack://jimp/../../node_modules/events/events.js","webpack://jimp/../../node_modules/exif-parser/index.js","webpack://jimp/../../node_modules/exif-parser/lib/bufferstream.js","webpack://jimp/../../node_modules/exif-parser/lib/date.js","webpack://jimp/../../node_modules/exif-parser/lib/dom-bufferstream.js","webpack://jimp/../../node_modules/exif-parser/lib/exif-tags.js","webpack://jimp/../../node_modules/exif-parser/lib/exif.js","webpack://jimp/../../node_modules/exif-parser/lib/jpeg.js","webpack://jimp/../../node_modules/exif-parser/lib/parser.js","webpack://jimp/../../node_modules/exif-parser/lib/simplify.js","webpack://jimp/../../node_modules/file-type/core.js","webpack://jimp/../../node_modules/file-type/index.js","webpack://jimp/../../node_modules/file-type/supported.js","webpack://jimp/../../node_modules/file-type/util.js","webpack://jimp/../../node_modules/for-each/index.js","webpack://jimp/../../node_modules/gifwrap/node_modules/omggif/omggif.js","webpack://jimp/../../node_modules/gifwrap/src/bitmapimage.js","webpack://jimp/../../node_modules/gifwrap/src/gif.js","webpack://jimp/../../node_modules/gifwrap/src/gifcodec.js","webpack://jimp/../../node_modules/gifwrap/src/gifframe.js","webpack://jimp/../../node_modules/gifwrap/src/gifutil.js","webpack://jimp/../../node_modules/gifwrap/src/index.js","webpack://jimp/../../node_modules/global/window.js","webpack://jimp/../../node_modules/ieee754/index.js","webpack://jimp/../../node_modules/is-callable/index.js","webpack://jimp/../../node_modules/is-function/index.js","webpack://jimp/../../node_modules/isomorphic-fetch/fetch-npm-browserify.js","webpack://jimp/../../node_modules/jpeg-js/index.js","webpack://jimp/../../node_modules/jpeg-js/lib/decoder.js","webpack://jimp/../../node_modules/jpeg-js/lib/encoder.js","webpack://jimp/../../node_modules/load-bmfont/browser.js","webpack://jimp/../../node_modules/load-bmfont/lib/is-binary.js","webpack://jimp/../../node_modules/omggif/omggif.js","webpack://jimp/../../node_modules/pako/index.js","webpack://jimp/../../node_modules/pako/lib/deflate.js","webpack://jimp/../../node_modules/pako/lib/inflate.js","webpack://jimp/../../node_modules/pako/lib/utils/common.js","webpack://jimp/../../node_modules/pako/lib/utils/strings.js","webpack://jimp/../../node_modules/pako/lib/zlib/adler32.js","webpack://jimp/../../node_modules/pako/lib/zlib/constants.js","webpack://jimp/../../node_modules/pako/lib/zlib/crc32.js","webpack://jimp/../../node_modules/pako/lib/zlib/deflate.js","webpack://jimp/../../node_modules/pako/lib/zlib/gzheader.js","webpack://jimp/../../node_modules/pako/lib/zlib/inffast.js","webpack://jimp/../../node_modules/pako/lib/zlib/inflate.js","webpack://jimp/../../node_modules/pako/lib/zlib/inftrees.js","webpack://jimp/../../node_modules/pako/lib/zlib/messages.js","webpack://jimp/../../node_modules/pako/lib/zlib/trees.js","webpack://jimp/../../node_modules/pako/lib/zlib/zstream.js","webpack://jimp/../../node_modules/parse-bmfont-ascii/index.js","webpack://jimp/../../node_modules/parse-bmfont-binary/index.js","webpack://jimp/../../node_modules/parse-bmfont-xml/lib/browser.js","webpack://jimp/../../node_modules/parse-bmfont-xml/lib/parse-attribs.js","webpack://jimp/../../node_modules/parse-headers/parse-headers.js","webpack://jimp/../../node_modules/path-browserify/index.js","webpack://jimp/../../node_modules/peek-readable/lib/Deferred.js","webpack://jimp/../../node_modules/peek-readable/lib/EndOfFileStream.js","webpack://jimp/../../node_modules/peek-readable/lib/StreamReader.js","webpack://jimp/../../node_modules/peek-readable/lib/index.js","webpack://jimp/../../node_modules/pixelmatch/index.js","webpack://jimp/../../node_modules/pngjs/browser.js","webpack://jimp/../../node_modules/process/browser.js","webpack://jimp/../../node_modules/strtok3/lib/AbstractTokenizer.js","webpack://jimp/../../node_modules/strtok3/lib/BufferTokenizer.js","webpack://jimp/../../node_modules/strtok3/lib/FileTokenizer.js","webpack://jimp/../../node_modules/strtok3/lib/FsPromise.js","webpack://jimp/../../node_modules/strtok3/lib/ReadStreamTokenizer.js","webpack://jimp/../../node_modules/strtok3/lib/core.js","webpack://jimp/../../node_modules/strtok3/lib/index.js","webpack://jimp/../../node_modules/timm/lib/timm.js","webpack://jimp/../../node_modules/token-types/lib/index.js","webpack://jimp/../../node_modules/trim/index.js","webpack://jimp/../../node_modules/utif2/UTIF.js","webpack://jimp/../../node_modules/whatwg-fetch/fetch.js","webpack://jimp/../../node_modules/xhr/index.js","webpack://jimp/../../node_modules/xml-parse-from-string/index.js","webpack://jimp/../../node_modules/xtend/immutable.js","webpack://jimp/../../node_modules/image-q/dist/cjs/image-q.cjs","webpack://jimp/webpack/bootstrap","webpack://jimp/webpack/runtime/compat get default export","webpack://jimp/webpack/runtime/define property getters","webpack://jimp/webpack/runtime/global","webpack://jimp/webpack/runtime/hasOwnProperty shorthand","webpack://jimp/webpack/runtime/make namespace object","webpack://jimp/../utils/es/index.js","webpack://jimp/../../node_modules/tinycolor2/esm/tinycolor.js","webpack://jimp/../core/es/modules/phash.js","webpack://jimp/../core/es/request.js","webpack://jimp/../core/es/constants.js","webpack://jimp/../core/es/composite/composite-modes.js","webpack://jimp/../core/es/utils/promisify.js","webpack://jimp/../core/es/utils/mime.js","webpack://jimp/../core/es/utils/image-bitmap.js","webpack://jimp/../core/es/index.js","webpack://jimp/../core/es/composite/index.js","webpack://jimp/../type-jpeg/es/index.js","webpack://jimp/../type-png/es/index.js","webpack://jimp/../type-bmp/es/index.js","webpack://jimp/../type-tiff/es/index.js","webpack://jimp/../type-gif/es/index.js","webpack://jimp/../plugin-blur/es/blur-tables.js","webpack://jimp/../plugin-color/es/index.js","webpack://jimp/../plugin-dither/es/index.js","webpack://jimp/../plugin-flip/es/index.js","webpack://jimp/../plugin-normalize/es/index.js","webpack://jimp/../plugin-print/es/measure-text.js","webpack://jimp/../plugin-print/es/index.js","webpack://jimp/../plugin-resize/es/modules/resize.js","webpack://jimp/../plugin-resize/es/modules/resize2.js","webpack://jimp/../plugin-rotate/es/index.js","webpack://jimp/../plugins/es/index.js","webpack://jimp/../plugin-blit/es/index.js","webpack://jimp/../plugin-blur/es/index.js","webpack://jimp/../plugin-circle/es/index.js","webpack://jimp/../plugin-contain/es/index.js","webpack://jimp/../plugin-cover/es/index.js","webpack://jimp/../plugin-crop/es/index.js","webpack://jimp/../plugin-displace/es/index.js","webpack://jimp/../plugin-fisheye/es/index.js","webpack://jimp/../plugin-gaussian/es/index.js","webpack://jimp/../plugin-invert/es/index.js","webpack://jimp/../plugin-mask/es/index.js","webpack://jimp/../plugin-resize/es/index.js","webpack://jimp/../plugin-scale/es/index.js","webpack://jimp/../plugin-shadow/es/index.js","webpack://jimp/../plugin-threshold/es/index.js","webpack://jimp/../custom/es/index.js","webpack://jimp/./src/index.js","webpack://jimp/../types/es/index.js"],"sourcesContent":["var Converter = require('./src/converter');\n\n/**\n * Function get source and destination alphabet and return convert function\n *\n * @param {string|Array} srcAlphabet\n * @param {string|Array} dstAlphabet\n *\n * @returns {function(number|Array)}\n */\nfunction anyBase(srcAlphabet, dstAlphabet) {\n var converter = new Converter(srcAlphabet, dstAlphabet);\n /**\n * Convert function\n *\n * @param {string|Array} number\n *\n * @return {string|Array} number\n */\n return function (number) {\n return converter.convert(number);\n }\n};\n\nanyBase.BIN = '01';\nanyBase.OCT = '01234567';\nanyBase.DEC = '0123456789';\nanyBase.HEX = '0123456789abcdef';\n\nmodule.exports = anyBase;","'use strict';\n\n/**\n * Converter\n *\n * @param {string|Array} srcAlphabet\n * @param {string|Array} dstAlphabet\n * @constructor\n */\nfunction Converter(srcAlphabet, dstAlphabet) {\n if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) {\n throw new Error('Bad alphabet');\n }\n this.srcAlphabet = srcAlphabet;\n this.dstAlphabet = dstAlphabet;\n}\n\n/**\n * Convert number from source alphabet to destination alphabet\n *\n * @param {string|Array} number - number represented as a string or array of points\n *\n * @returns {string|Array}\n */\nConverter.prototype.convert = function(number) {\n var i, divide, newlen,\n numberMap = {},\n fromBase = this.srcAlphabet.length,\n toBase = this.dstAlphabet.length,\n length = number.length,\n result = typeof number === 'string' ? '' : [];\n\n if (!this.isValid(number)) {\n throw new Error('Number \"' + number + '\" contains of non-alphabetic digits (' + this.srcAlphabet + ')');\n }\n\n if (this.srcAlphabet === this.dstAlphabet) {\n return number;\n }\n\n for (i = 0; i < length; i++) {\n numberMap[i] = this.srcAlphabet.indexOf(number[i]);\n }\n do {\n divide = 0;\n newlen = 0;\n for (i = 0; i < length; i++) {\n divide = divide * fromBase + numberMap[i];\n if (divide >= toBase) {\n numberMap[newlen++] = parseInt(divide / toBase, 10);\n divide = divide % toBase;\n } else if (newlen > 0) {\n numberMap[newlen++] = 0;\n }\n }\n length = newlen;\n result = this.dstAlphabet.slice(divide, divide + 1).concat(result);\n } while (newlen !== 0);\n\n return result;\n};\n\n/**\n * Valid number with source alphabet\n *\n * @param {number} number\n *\n * @returns {boolean}\n */\nConverter.prototype.isValid = function(number) {\n var i = 0;\n for (; i < number.length; ++i) {\n if (this.srcAlphabet.indexOf(number[i]) === -1) {\n return false;\n }\n }\n return true;\n};\n\nmodule.exports = Converter;","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(\n uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)\n ))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/**\n * @author shaozilee\n *\n * support 1bit 4bit 8bit 24bit decode\n * encode with 24bit\n * \n */\n\nvar encode = require('./lib/encoder'),\n decode = require('./lib/decoder');\n\nmodule.exports = {\n encode: encode,\n decode: decode\n};\n","/**\n * @author shaozilee\n *\n * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp\n *\n */\n\nfunction BmpDecoder(buffer,is_with_alpha) {\n this.pos = 0;\n this.buffer = buffer;\n this.is_with_alpha = !!is_with_alpha;\n this.bottom_up = true;\n this.flag = this.buffer.toString(\"utf-8\", 0, this.pos += 2);\n if (this.flag != \"BM\") throw new Error(\"Invalid BMP File\");\n this.parseHeader();\n this.parseRGBA();\n}\n\nBmpDecoder.prototype.parseHeader = function() {\n this.fileSize = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.reserved = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.offset = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.headerSize = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.width = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.height = this.buffer.readInt32LE(this.pos);\n this.pos += 4;\n this.planes = this.buffer.readUInt16LE(this.pos);\n this.pos += 2;\n this.bitPP = this.buffer.readUInt16LE(this.pos);\n this.pos += 2;\n this.compress = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.rawSize = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.hr = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.vr = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.colors = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n this.importantColors = this.buffer.readUInt32LE(this.pos);\n this.pos += 4;\n\n if(this.bitPP === 16 && this.is_with_alpha){\n this.bitPP = 15\n }\n if (this.bitPP < 15) {\n var len = this.colors === 0 ? 1 << this.bitPP : this.colors;\n this.palette = new Array(len);\n for (var i = 0; i < len; i++) {\n var blue = this.buffer.readUInt8(this.pos++);\n var green = this.buffer.readUInt8(this.pos++);\n var red = this.buffer.readUInt8(this.pos++);\n var quad = this.buffer.readUInt8(this.pos++);\n this.palette[i] = {\n red: red,\n green: green,\n blue: blue,\n quad: quad\n };\n }\n }\n if(this.height < 0) {\n this.height *= -1;\n this.bottom_up = false;\n }\n\n}\n\nBmpDecoder.prototype.parseRGBA = function() {\n var bitn = \"bit\" + this.bitPP;\n var len = this.width * this.height * 4;\n this.data = new Buffer(len);\n this[bitn]();\n};\n\nBmpDecoder.prototype.bit1 = function() {\n var xlen = Math.ceil(this.width / 8);\n var mode = xlen%4;\n var y = this.height >= 0 ? this.height - 1 : -this.height\n for (var y = this.height - 1; y >= 0; y--) {\n var line = this.bottom_up ? y : this.height - 1 - y\n for (var x = 0; x < xlen; x++) {\n var b = this.buffer.readUInt8(this.pos++);\n var location = line * this.width * 4 + x*8*4;\n for (var i = 0; i < 8; i++) {\n if(x*8+i>(7-i))&0x1)];\n\n this.data[location+i*4] = 0;\n this.data[location+i*4 + 1] = rgb.blue;\n this.data[location+i*4 + 2] = rgb.green;\n this.data[location+i*4 + 3] = rgb.red;\n\n }else{\n break;\n }\n }\n }\n\n if (mode != 0){\n this.pos+=(4 - mode);\n }\n }\n};\n\nBmpDecoder.prototype.bit4 = function() {\n //RLE-4\n if(this.compress == 2){\n this.data.fill(0xff);\n\n var location = 0;\n var lines = this.bottom_up?this.height-1:0;\n var low_nibble = false;//for all count of pixel\n\n while(location>4);\n }\n\n if ((i & 1) && (i+1 < b)){\n c = this.buffer.readUInt8(this.pos++);\n }\n\n low_nibble = !low_nibble;\n }\n\n if ((((b+1) >> 1) & 1 ) == 1){\n this.pos++\n }\n }\n\n }else{//encoded mode\n for (var i = 0; i < a; i++) {\n if (low_nibble) {\n setPixelData.call(this, (b & 0x0f));\n } else {\n setPixelData.call(this, (b & 0xf0)>>4);\n }\n low_nibble = !low_nibble;\n }\n }\n\n }\n\n\n\n\n function setPixelData(rgbIndex){\n var rgb = this.palette[rgbIndex];\n this.data[location] = 0;\n this.data[location + 1] = rgb.blue;\n this.data[location + 2] = rgb.green;\n this.data[location + 3] = rgb.red;\n location+=4;\n }\n }else{\n\n var xlen = Math.ceil(this.width/2);\n var mode = xlen%4;\n for (var y = this.height - 1; y >= 0; y--) {\n var line = this.bottom_up ? y : this.height - 1 - y\n for (var x = 0; x < xlen; x++) {\n var b = this.buffer.readUInt8(this.pos++);\n var location = line * this.width * 4 + x*2*4;\n\n var before = b>>4;\n var after = b&0x0F;\n\n var rgb = this.palette[before];\n this.data[location] = 0;\n this.data[location + 1] = rgb.blue;\n this.data[location + 2] = rgb.green;\n this.data[location + 3] = rgb.red;\n\n\n if(x*2+1>=this.width)break;\n\n rgb = this.palette[after];\n\n this.data[location+4] = 0;\n this.data[location+4 + 1] = rgb.blue;\n this.data[location+4 + 2] = rgb.green;\n this.data[location+4 + 3] = rgb.red;\n\n }\n\n if (mode != 0){\n this.pos+=(4 - mode);\n }\n }\n\n }\n\n};\n\nBmpDecoder.prototype.bit8 = function() {\n //RLE-8\n if(this.compress == 1){\n this.data.fill(0xff);\n\n var location = 0;\n var lines = this.bottom_up?this.height-1:0;\n\n while(location= 0; y--) {\n var line = this.bottom_up ? y : this.height - 1 - y\n for (var x = 0; x < this.width; x++) {\n var b = this.buffer.readUInt8(this.pos++);\n var location = line * this.width * 4 + x * 4;\n if (b < this.palette.length) {\n var rgb = this.palette[b];\n\n this.data[location] = 0;\n this.data[location + 1] = rgb.blue;\n this.data[location + 2] = rgb.green;\n this.data[location + 3] = rgb.red;\n\n } else {\n this.data[location] = 0;\n this.data[location + 1] = 0xFF;\n this.data[location + 2] = 0xFF;\n this.data[location + 3] = 0xFF;\n }\n }\n if (mode != 0) {\n this.pos += (4 - mode);\n }\n }\n }\n};\n\nBmpDecoder.prototype.bit15 = function() {\n var dif_w =this.width % 3;\n var _11111 = parseInt(\"11111\", 2),_1_5 = _11111;\n for (var y = this.height - 1; y >= 0; y--) {\n var line = this.bottom_up ? y : this.height - 1 - y\n for (var x = 0; x < this.width; x++) {\n\n var B = this.buffer.readUInt16LE(this.pos);\n this.pos+=2;\n var blue = (B & _1_5) / _1_5 * 255 | 0;\n var green = (B >> 5 & _1_5 ) / _1_5 * 255 | 0;\n var red = (B >> 10 & _1_5) / _1_5 * 255 | 0;\n var alpha = (B>>15)?0xFF:0x00;\n\n var location = line * this.width * 4 + x * 4;\n\n this.data[location] = alpha;\n this.data[location + 1] = blue;\n this.data[location + 2] = green;\n this.data[location + 3] = red;\n }\n //skip extra bytes\n this.pos += dif_w;\n }\n};\n\nBmpDecoder.prototype.bit16 = function() {\n var dif_w =(this.width % 2)*2;\n //default xrgb555\n this.maskRed = 0x7C00;\n this.maskGreen = 0x3E0;\n this.maskBlue =0x1F;\n this.mask0 = 0;\n\n if(this.compress == 3){\n this.maskRed = this.buffer.readUInt32LE(this.pos);\n this.pos+=4;\n this.maskGreen = this.buffer.readUInt32LE(this.pos);\n this.pos+=4;\n this.maskBlue = this.buffer.readUInt32LE(this.pos);\n this.pos+=4;\n this.mask0 = this.buffer.readUInt32LE(this.pos);\n this.pos+=4;\n }\n\n\n var ns=[0,0,0];\n for (var i=0;i<16;i++){\n if ((this.maskRed>>i)&0x01) ns[0]++;\n if ((this.maskGreen>>i)&0x01) ns[1]++;\n if ((this.maskBlue>>i)&0x01) ns[2]++;\n }\n ns[1]+=ns[0]; ns[2]+=ns[1];\tns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8;\n\n for (var y = this.height - 1; y >= 0; y--) {\n var line = this.bottom_up ? y : this.height - 1 - y;\n for (var x = 0; x < this.width; x++) {\n\n var B = this.buffer.readUInt16LE(this.pos);\n this.pos+=2;\n\n var blue = (B&this.maskBlue)<>ns[1];\n var red = (B&this.maskRed)>>ns[2];\n\n var location = line * this.width * 4 + x * 4;\n\n this.data[location] = 0;\n this.data[location + 1] = blue;\n this.data[location + 2] = green;\n this.data[location + 3] = red;\n }\n //skip extra bytes\n this.pos += dif_w;\n }\n};\n\nBmpDecoder.prototype.bit24 = function() {\n for (var y = this.height - 1; y >= 0; y--) {\n var line = this.bottom_up ? y : this.height - 1 - y\n for (var x = 0; x < this.width; x++) {\n //Little Endian rgb\n var blue = this.buffer.readUInt8(this.pos++);\n var green = this.buffer.readUInt8(this.pos++);\n var red = this.buffer.readUInt8(this.pos++);\n var location = line * this.width * 4 + x * 4;\n this.data[location] = 0;\n this.data[location + 1] = blue;\n this.data[location + 2] = green;\n this.data[location + 3] = red;\n }\n //skip extra bytes\n this.pos += (this.width % 4);\n }\n\n};\n\n/**\n * add 32bit decode func\n * @author soubok\n */\nBmpDecoder.prototype.bit32 = function() {\n //BI_BITFIELDS\n if(this.compress == 3){\n this.maskRed = this.buffer.readUInt32LE(this.pos);\n this.pos+=4;\n this.maskGreen = this.buffer.readUInt32LE(this.pos);\n this.pos+=4;\n this.maskBlue = this.buffer.readUInt32LE(this.pos);\n this.pos+=4;\n this.mask0 = this.buffer.readUInt32LE(this.pos);\n this.pos+=4;\n for (var y = this.height - 1; y >= 0; y--) {\n var line = this.bottom_up ? y : this.height - 1 - y;\n for (var x = 0; x < this.width; x++) {\n //Little Endian rgba\n var alpha = this.buffer.readUInt8(this.pos++);\n var blue = this.buffer.readUInt8(this.pos++);\n var green = this.buffer.readUInt8(this.pos++);\n var red = this.buffer.readUInt8(this.pos++);\n var location = line * this.width * 4 + x * 4;\n this.data[location] = alpha;\n this.data[location + 1] = blue;\n this.data[location + 2] = green;\n this.data[location + 3] = red;\n }\n }\n\n }else{\n for (var y = this.height - 1; y >= 0; y--) {\n var line = this.bottom_up ? y : this.height - 1 - y;\n for (var x = 0; x < this.width; x++) {\n //Little Endian argb\n var blue = this.buffer.readUInt8(this.pos++);\n var green = this.buffer.readUInt8(this.pos++);\n var red = this.buffer.readUInt8(this.pos++);\n var alpha = this.buffer.readUInt8(this.pos++);\n var location = line * this.width * 4 + x * 4;\n this.data[location] = alpha;\n this.data[location + 1] = blue;\n this.data[location + 2] = green;\n this.data[location + 3] = red;\n }\n }\n\n }\n\n\n\n\n};\n\nBmpDecoder.prototype.getData = function() {\n return this.data;\n};\n\nmodule.exports = function(bmpData) {\n var decoder = new BmpDecoder(bmpData);\n return decoder;\n};\n","/**\n * @author shaozilee\n *\n * BMP format encoder,encode 24bit BMP\n * Not support quality compression\n *\n */\n\nfunction BmpEncoder(imgData){\n\tthis.buffer = imgData.data;\n\tthis.width = imgData.width;\n\tthis.height = imgData.height;\n\tthis.extraBytes = this.width%4;\n\tthis.rgbSize = this.height*(3*this.width+this.extraBytes);\n\tthis.headerInfoSize = 40;\n\n\tthis.data = [];\n\t/******************header***********************/\n\tthis.flag = \"BM\";\n\tthis.reserved = 0;\n\tthis.offset = 54;\n\tthis.fileSize = this.rgbSize+this.offset;\n\tthis.planes = 1;\n\tthis.bitPP = 24;\n\tthis.compress = 0;\n\tthis.hr = 0;\n\tthis.vr = 0;\n\tthis.colors = 0;\n\tthis.importantColors = 0;\n}\n\nBmpEncoder.prototype.encode = function() {\n\tvar tempBuffer = new Buffer(this.offset+this.rgbSize);\n\tthis.pos = 0;\n\ttempBuffer.write(this.flag,this.pos,2);this.pos+=2;\n\ttempBuffer.writeUInt32LE(this.fileSize,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt32LE(this.reserved,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt32LE(this.offset,this.pos);this.pos+=4;\n\n\ttempBuffer.writeUInt32LE(this.headerInfoSize,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt32LE(this.width,this.pos);this.pos+=4;\n\ttempBuffer.writeInt32LE(-this.height,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt16LE(this.planes,this.pos);this.pos+=2;\n\ttempBuffer.writeUInt16LE(this.bitPP,this.pos);this.pos+=2;\n\ttempBuffer.writeUInt32LE(this.compress,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt32LE(this.rgbSize,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt32LE(this.hr,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt32LE(this.vr,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt32LE(this.colors,this.pos);this.pos+=4;\n\ttempBuffer.writeUInt32LE(this.importantColors,this.pos);this.pos+=4;\n\n\tvar i=0;\n\tvar rowBytes = 3*this.width+this.extraBytes;\n\n\tfor (var y = 0; y 0){\n\t\t\tvar fillOffset = this.pos+y*rowBytes+this.width*3;\n\t\t\ttempBuffer.fill(0,fillOffset,fillOffset+this.extraBytes);\n\t\t}\n\t}\n\n\treturn tempBuffer;\n};\n\nmodule.exports = function(imgData, quality) {\n if (typeof quality === 'undefined') quality = 100;\n \tvar encoder = new BmpEncoder(imgData);\n\tvar data = encoder.encode();\n return {\n data: data,\n width: imgData.width,\n height: imgData.height\n };\n};\n","var Buffer = require('buffer').Buffer; // for use with browserify\n\nmodule.exports = function (a, b) {\n if (!Buffer.isBuffer(a)) return undefined;\n if (!Buffer.isBuffer(b)) return undefined;\n if (typeof a.equals === 'function') return a.equals(b);\n if (a.length !== b.length) return false;\n \n for (var i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n \n return true;\n};\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\n// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\nif (typeof Symbol !== 'undefined' && Symbol.species != null &&\n Buffer[Symbol.species] === Buffer) {\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true,\n enumerable: false,\n writable: false\n })\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayLike(value)\n }\n\n if (value == null) {\n throw TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nBuffer.prototype.__proto__ = Uint8Array.prototype\nBuffer.__proto__ = Uint8Array\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n buf = Buffer.from(buf)\n }\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n newBuf.__proto__ = Buffer.prototype\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (var i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n","exports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","var Parser = require('./lib/parser');\n\nfunction getGlobal() {\n\treturn (1,eval)('this');\n}\n\nmodule.exports = {\n\tcreate: function(buffer, global) {\n\t\tglobal = global || getGlobal();\n\t\tif(buffer instanceof global.ArrayBuffer) {\n\t\t\tvar DOMBufferStream = require('./lib/dom-bufferstream');\n\t\t\treturn new Parser(new DOMBufferStream(buffer, 0, buffer.byteLength, true, global));\n\t\t} else {\n\t\t\tvar NodeBufferStream = require('./lib/bufferstream');\n\t\t\treturn new Parser(new NodeBufferStream(buffer, 0, buffer.length, true));\n\t\t}\n\t}\n};\n","function BufferStream(buffer, offset, length, bigEndian) {\n\tthis.buffer = buffer;\n\tthis.offset = offset || 0;\n\tlength = typeof length === 'number' ? length : buffer.length;\n\tthis.endPosition = this.offset + length;\n\tthis.setBigEndian(bigEndian);\n}\n\nBufferStream.prototype = {\n\tsetBigEndian: function(bigEndian) {\n\t\tthis.bigEndian = !!bigEndian;\n\t},\n\tnextUInt8: function() {\n\t\tvar value = this.buffer.readUInt8(this.offset);\n\t\tthis.offset += 1;\n\t\treturn value;\n\t},\n\tnextInt8: function() {\n\t\tvar value = this.buffer.readInt8(this.offset);\n\t\tthis.offset += 1;\n\t\treturn value;\n\t},\n\tnextUInt16: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readUInt16BE(this.offset) : this.buffer.readUInt16LE(this.offset);\n\t\tthis.offset += 2;\n\t\treturn value;\n\t},\n\tnextUInt32: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readUInt32BE(this.offset) : this.buffer.readUInt32LE(this.offset);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextInt16: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readInt16BE(this.offset) : this.buffer.readInt16LE(this.offset);\n\t\tthis.offset += 2;\n\t\treturn value;\n\t},\n\tnextInt32: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readInt32BE(this.offset) : this.buffer.readInt32LE(this.offset);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextFloat: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readFloatBE(this.offset) : this.buffer.readFloatLE(this.offset);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextDouble: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readDoubleBE(this.offset) : this.buffer.readDoubleLE(this.offset);\n\t\tthis.offset += 8;\n\t\treturn value;\n\t},\n\tnextBuffer: function(length) {\n\t\tvar value = this.buffer.slice(this.offset, this.offset + length);\n\t\tthis.offset += length;\n\t\treturn value;\n\t},\n\tremainingLength: function() {\n\t\treturn this.endPosition - this.offset;\n\t},\n\tnextString: function(length) {\n\t\tvar value = this.buffer.toString('utf8', this.offset, this.offset + length);\n\t\tthis.offset += length;\n\t\treturn value;\n\t},\n\tmark: function() {\n\t\tvar self = this;\n\t\treturn {\n\t\t\topenWithOffset: function(offset) {\n\t\t\t\toffset = (offset || 0) + this.offset;\n\t\t\t\treturn new BufferStream(self.buffer, offset, self.endPosition - offset, self.bigEndian);\n\t\t\t},\n\t\t\toffset: this.offset\n\t\t};\n\t},\n\toffsetFrom: function(marker) {\n\t\treturn this.offset - marker.offset;\n\t},\n\tskip: function(amount) {\n\t\tthis.offset += amount;\n\t},\n\tbranch: function(offset, length) {\n\t\tlength = typeof length === 'number' ? length : this.endPosition - (this.offset + offset);\n\t\treturn new BufferStream(this.buffer, this.offset + offset, length, this.bigEndian);\n\t}\n};\n\nmodule.exports = BufferStream;\n","function parseNumber(s) {\n\treturn parseInt(s, 10);\n}\n\n//in seconds\nvar hours = 3600;\nvar minutes = 60;\n\n//take date (year, month, day) and time (hour, minutes, seconds) digits in UTC\n//and return a timestamp in seconds\nfunction parseDateTimeParts(dateParts, timeParts) {\n\tdateParts = dateParts.map(parseNumber);\n\ttimeParts = timeParts.map(parseNumber);\n\tvar year = dateParts[0];\n\tvar month = dateParts[1] - 1;\n\tvar day = dateParts[2];\n\tvar hours = timeParts[0];\n\tvar minutes = timeParts[1];\n\tvar seconds = timeParts[2];\n\tvar date = Date.UTC(year, month, day, hours, minutes, seconds, 0);\n\tvar timestamp = date / 1000;\n\treturn timestamp;\n}\n\n//parse date with \"2004-09-04T23:39:06-08:00\" format,\n//one of the formats supported by ISO 8601, and\n//convert to utc timestamp in seconds\nfunction parseDateWithTimezoneFormat(dateTimeStr) {\n\n\tvar dateParts = dateTimeStr.substr(0, 10).split('-');\n\tvar timeParts = dateTimeStr.substr(11, 8).split(':');\n\tvar timezoneStr = dateTimeStr.substr(19, 6);\n\tvar timezoneParts = timezoneStr.split(':').map(parseNumber);\n\tvar timezoneOffset = (timezoneParts[0] * hours) +\n\t\t(timezoneParts[1] * minutes);\n\n\tvar timestamp = parseDateTimeParts(dateParts, timeParts);\n\t//minus because the timezoneOffset describes\n\t//how much the described time is ahead of UTC\n\ttimestamp -= timezoneOffset;\n\n\tif(typeof timestamp === 'number' && !isNaN(timestamp)) {\n\t\treturn timestamp;\n\t}\n}\n\n//parse date with \"YYYY:MM:DD hh:mm:ss\" format, convert to utc timestamp in seconds\nfunction parseDateWithSpecFormat(dateTimeStr) {\n\tvar parts = dateTimeStr.split(' '),\n\t\tdateParts = parts[0].split(':'),\n\t\ttimeParts = parts[1].split(':');\n\n\tvar timestamp = parseDateTimeParts(dateParts, timeParts);\n\n\tif(typeof timestamp === 'number' && !isNaN(timestamp)) {\n\t\treturn timestamp;\n\t}\n}\n\nfunction parseExifDate(dateTimeStr) {\n\t//some easy checks to determine two common date formats\n\n\t//is the date in the standard \"YYYY:MM:DD hh:mm:ss\" format?\n\tvar isSpecFormat = dateTimeStr.length === 19 &&\n\t\tdateTimeStr.charAt(4) === ':';\n\t//is the date in the non-standard format,\n\t//\"2004-09-04T23:39:06-08:00\" to include a timezone?\n\tvar isTimezoneFormat = dateTimeStr.length === 25 &&\n\t\tdateTimeStr.charAt(10) === 'T';\n\tvar timestamp;\n\n\tif(isTimezoneFormat) {\n\t\treturn parseDateWithTimezoneFormat(dateTimeStr);\n\t}\n\telse if(isSpecFormat) {\n\t\treturn parseDateWithSpecFormat(dateTimeStr);\n\t}\n}\n\nmodule.exports = {\n\tparseDateWithSpecFormat: parseDateWithSpecFormat,\n\tparseDateWithTimezoneFormat: parseDateWithTimezoneFormat,\n\tparseExifDate: parseExifDate\n};\n","/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */\n\nfunction DOMBufferStream(arrayBuffer, offset, length, bigEndian, global, parentOffset) {\n\tthis.global = global;\n\toffset = offset || 0;\n\tlength = length || (arrayBuffer.byteLength - offset);\n\tthis.arrayBuffer = arrayBuffer.slice(offset, offset + length);\n\tthis.view = new global.DataView(this.arrayBuffer, 0, this.arrayBuffer.byteLength);\n\tthis.setBigEndian(bigEndian);\n\tthis.offset = 0;\n\tthis.parentOffset = (parentOffset || 0) + offset;\n}\n\nDOMBufferStream.prototype = {\n\tsetBigEndian: function(bigEndian) {\n\t\tthis.littleEndian = !bigEndian;\n\t},\n\tnextUInt8: function() {\n\t\tvar value = this.view.getUint8(this.offset);\n\t\tthis.offset += 1;\n\t\treturn value;\n\t},\n\tnextInt8: function() {\n\t\tvar value = this.view.getInt8(this.offset);\n\t\tthis.offset += 1;\n\t\treturn value;\n\t},\n\tnextUInt16: function() {\n\t\tvar value = this.view.getUint16(this.offset, this.littleEndian);\n\t\tthis.offset += 2;\n\t\treturn value;\n\t},\n\tnextUInt32: function() {\n\t\tvar value = this.view.getUint32(this.offset, this.littleEndian);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextInt16: function() {\n\t\tvar value = this.view.getInt16(this.offset, this.littleEndian);\n\t\tthis.offset += 2;\n\t\treturn value;\n\t},\n\tnextInt32: function() {\n\t\tvar value = this.view.getInt32(this.offset, this.littleEndian);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextFloat: function() {\n\t\tvar value = this.view.getFloat32(this.offset, this.littleEndian);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextDouble: function() {\n\t\tvar value = this.view.getFloat64(this.offset, this.littleEndian);\n\t\tthis.offset += 8;\n\t\treturn value;\n\t},\n\tnextBuffer: function(length) {\n\t\t//this won't work in IE10\n\t\tvar value = this.arrayBuffer.slice(this.offset, this.offset + length);\n\t\tthis.offset += length;\n\t\treturn value;\n\t},\n\tremainingLength: function() {\n\t\treturn this.arrayBuffer.byteLength - this.offset;\n\t},\n\tnextString: function(length) {\n\t\tvar value = this.arrayBuffer.slice(this.offset, this.offset + length);\n\t\tvalue = String.fromCharCode.apply(null, new this.global.Uint8Array(value));\n\t\tthis.offset += length;\n\t\treturn value;\n\t},\n\tmark: function() {\n\t\tvar self = this;\n\t\treturn {\n\t\t\topenWithOffset: function(offset) {\n\t\t\t\toffset = (offset || 0) + this.offset;\n\t\t\t\treturn new DOMBufferStream(self.arrayBuffer, offset, self.arrayBuffer.byteLength - offset, !self.littleEndian, self.global, self.parentOffset);\n\t\t\t},\n\t\t\toffset: this.offset,\n\t\t\tgetParentOffset: function() {\n\t\t\t\treturn self.parentOffset;\n\t\t\t}\n\t\t};\n\t},\n\toffsetFrom: function(marker) {\n\t\treturn this.parentOffset + this.offset - (marker.offset + marker.getParentOffset());\n\t},\n\tskip: function(amount) {\n\t\tthis.offset += amount;\n\t},\n\tbranch: function(offset, length) {\n\t\tlength = typeof length === 'number' ? length : this.arrayBuffer.byteLength - (this.offset + offset);\n\t\treturn new DOMBufferStream(this.arrayBuffer, this.offset + offset, length, !this.littleEndian, this.global, this.parentOffset);\n\t}\n};\n\nmodule.exports = DOMBufferStream;\n","module.exports = {\n\texif : {\n\t\t0x0001 : \"InteropIndex\",\n\t\t0x0002 : \"InteropVersion\",\n\t\t0x000B : \"ProcessingSoftware\",\n\t\t0x00FE : \"SubfileType\",\n\t\t0x00FF : \"OldSubfileType\",\n\t\t0x0100 : \"ImageWidth\",\n\t\t0x0101 : \"ImageHeight\",\n\t\t0x0102 : \"BitsPerSample\",\n\t\t0x0103 : \"Compression\",\n\t\t0x0106 : \"PhotometricInterpretation\",\n\t\t0x0107 : \"Thresholding\",\n\t\t0x0108 : \"CellWidth\",\n\t\t0x0109 : \"CellLength\",\n\t\t0x010A : \"FillOrder\",\n\t\t0x010D : \"DocumentName\",\n\t\t0x010E : \"ImageDescription\",\n\t\t0x010F : \"Make\",\n\t\t0x0110 : \"Model\",\n\t\t0x0111 : \"StripOffsets\",\n\t\t0x0112 : \"Orientation\",\n\t\t0x0115 : \"SamplesPerPixel\",\n\t\t0x0116 : \"RowsPerStrip\",\n\t\t0x0117 : \"StripByteCounts\",\n\t\t0x0118 : \"MinSampleValue\",\n\t\t0x0119 : \"MaxSampleValue\",\n\t\t0x011A : \"XResolution\",\n\t\t0x011B : \"YResolution\",\n\t\t0x011C : \"PlanarConfiguration\",\n\t\t0x011D : \"PageName\",\n\t\t0x011E : \"XPosition\",\n\t\t0x011F : \"YPosition\",\n\t\t0x0120 : \"FreeOffsets\",\n\t\t0x0121 : \"FreeByteCounts\",\n\t\t0x0122 : \"GrayResponseUnit\",\n\t\t0x0123 : \"GrayResponseCurve\",\n\t\t0x0124 : \"T4Options\",\n\t\t0x0125 : \"T6Options\",\n\t\t0x0128 : \"ResolutionUnit\",\n\t\t0x0129 : \"PageNumber\",\n\t\t0x012C : \"ColorResponseUnit\",\n\t\t0x012D : \"TransferFunction\",\n\t\t0x0131 : \"Software\",\n\t\t0x0132 : \"ModifyDate\",\n\t\t0x013B : \"Artist\",\n\t\t0x013C : \"HostComputer\",\n\t\t0x013D : \"Predictor\",\n\t\t0x013E : \"WhitePoint\",\n\t\t0x013F : \"PrimaryChromaticities\",\n\t\t0x0140 : \"ColorMap\",\n\t\t0x0141 : \"HalftoneHints\",\n\t\t0x0142 : \"TileWidth\",\n\t\t0x0143 : \"TileLength\",\n\t\t0x0144 : \"TileOffsets\",\n\t\t0x0145 : \"TileByteCounts\",\n\t\t0x0146 : \"BadFaxLines\",\n\t\t0x0147 : \"CleanFaxData\",\n\t\t0x0148 : \"ConsecutiveBadFaxLines\",\n\t\t0x014A : \"SubIFD\",\n\t\t0x014C : \"InkSet\",\n\t\t0x014D : \"InkNames\",\n\t\t0x014E : \"NumberofInks\",\n\t\t0x0150 : \"DotRange\",\n\t\t0x0151 : \"TargetPrinter\",\n\t\t0x0152 : \"ExtraSamples\",\n\t\t0x0153 : \"SampleFormat\",\n\t\t0x0154 : \"SMinSampleValue\",\n\t\t0x0155 : \"SMaxSampleValue\",\n\t\t0x0156 : \"TransferRange\",\n\t\t0x0157 : \"ClipPath\",\n\t\t0x0158 : \"XClipPathUnits\",\n\t\t0x0159 : \"YClipPathUnits\",\n\t\t0x015A : \"Indexed\",\n\t\t0x015B : \"JPEGTables\",\n\t\t0x015F : \"OPIProxy\",\n\t\t0x0190 : \"GlobalParametersIFD\",\n\t\t0x0191 : \"ProfileType\",\n\t\t0x0192 : \"FaxProfile\",\n\t\t0x0193 : \"CodingMethods\",\n\t\t0x0194 : \"VersionYear\",\n\t\t0x0195 : \"ModeNumber\",\n\t\t0x01B1 : \"Decode\",\n\t\t0x01B2 : \"DefaultImageColor\",\n\t\t0x01B3 : \"T82Options\",\n\t\t0x01B5 : \"JPEGTables\",\n\t\t0x0200 : \"JPEGProc\",\n\t\t0x0201 : \"ThumbnailOffset\",\n\t\t0x0202 : \"ThumbnailLength\",\n\t\t0x0203 : \"JPEGRestartInterval\",\n\t\t0x0205 : \"JPEGLosslessPredictors\",\n\t\t0x0206 : \"JPEGPointTransforms\",\n\t\t0x0207 : \"JPEGQTables\",\n\t\t0x0208 : \"JPEGDCTables\",\n\t\t0x0209 : \"JPEGACTables\",\n\t\t0x0211 : \"YCbCrCoefficients\",\n\t\t0x0212 : \"YCbCrSubSampling\",\n\t\t0x0213 : \"YCbCrPositioning\",\n\t\t0x0214 : \"ReferenceBlackWhite\",\n\t\t0x022F : \"StripRowCounts\",\n\t\t0x02BC : \"ApplicationNotes\",\n\t\t0x03E7 : \"USPTOMiscellaneous\",\n\t\t0x1000 : \"RelatedImageFileFormat\",\n\t\t0x1001 : \"RelatedImageWidth\",\n\t\t0x1002 : \"RelatedImageHeight\",\n\t\t0x4746 : \"Rating\",\n\t\t0x4747 : \"XP_DIP_XML\",\n\t\t0x4748 : \"StitchInfo\",\n\t\t0x4749 : \"RatingPercent\",\n\t\t0x800D : \"ImageID\",\n\t\t0x80A3 : \"WangTag1\",\n\t\t0x80A4 : \"WangAnnotation\",\n\t\t0x80A5 : \"WangTag3\",\n\t\t0x80A6 : \"WangTag4\",\n\t\t0x80E3 : \"Matteing\",\n\t\t0x80E4 : \"DataType\",\n\t\t0x80E5 : \"ImageDepth\",\n\t\t0x80E6 : \"TileDepth\",\n\t\t0x827D : \"Model2\",\n\t\t0x828D : \"CFARepeatPatternDim\",\n\t\t0x828E : \"CFAPattern2\",\n\t\t0x828F : \"BatteryLevel\",\n\t\t0x8290 : \"KodakIFD\",\n\t\t0x8298 : \"Copyright\",\n\t\t0x829A : \"ExposureTime\",\n\t\t0x829D : \"FNumber\",\n\t\t0x82A5 : \"MDFileTag\",\n\t\t0x82A6 : \"MDScalePixel\",\n\t\t0x82A7 : \"MDColorTable\",\n\t\t0x82A8 : \"MDLabName\",\n\t\t0x82A9 : \"MDSampleInfo\",\n\t\t0x82AA : \"MDPrepDate\",\n\t\t0x82AB : \"MDPrepTime\",\n\t\t0x82AC : \"MDFileUnits\",\n\t\t0x830E : \"PixelScale\",\n\t\t0x8335 : \"AdventScale\",\n\t\t0x8336 : \"AdventRevision\",\n\t\t0x835C : \"UIC1Tag\",\n\t\t0x835D : \"UIC2Tag\",\n\t\t0x835E : \"UIC3Tag\",\n\t\t0x835F : \"UIC4Tag\",\n\t\t0x83BB : \"IPTC-NAA\",\n\t\t0x847E : \"IntergraphPacketData\",\n\t\t0x847F : \"IntergraphFlagRegisters\",\n\t\t0x8480 : \"IntergraphMatrix\",\n\t\t0x8481 : \"INGRReserved\",\n\t\t0x8482 : \"ModelTiePoint\",\n\t\t0x84E0 : \"Site\",\n\t\t0x84E1 : \"ColorSequence\",\n\t\t0x84E2 : \"IT8Header\",\n\t\t0x84E3 : \"RasterPadding\",\n\t\t0x84E4 : \"BitsPerRunLength\",\n\t\t0x84E5 : \"BitsPerExtendedRunLength\",\n\t\t0x84E6 : \"ColorTable\",\n\t\t0x84E7 : \"ImageColorIndicator\",\n\t\t0x84E8 : \"BackgroundColorIndicator\",\n\t\t0x84E9 : \"ImageColorValue\",\n\t\t0x84EA : \"BackgroundColorValue\",\n\t\t0x84EB : \"PixelIntensityRange\",\n\t\t0x84EC : \"TransparencyIndicator\",\n\t\t0x84ED : \"ColorCharacterization\",\n\t\t0x84EE : \"HCUsage\",\n\t\t0x84EF : \"TrapIndicator\",\n\t\t0x84F0 : \"CMYKEquivalent\",\n\t\t0x8546 : \"SEMInfo\",\n\t\t0x8568 : \"AFCP_IPTC\",\n\t\t0x85B8 : \"PixelMagicJBIGOptions\",\n\t\t0x85D8 : \"ModelTransform\",\n\t\t0x8602 : \"WB_GRGBLevels\",\n\t\t0x8606 : \"LeafData\",\n\t\t0x8649 : \"PhotoshopSettings\",\n\t\t0x8769 : \"ExifOffset\",\n\t\t0x8773 : \"ICC_Profile\",\n\t\t0x877F : \"TIFF_FXExtensions\",\n\t\t0x8780 : \"MultiProfiles\",\n\t\t0x8781 : \"SharedData\",\n\t\t0x8782 : \"T88Options\",\n\t\t0x87AC : \"ImageLayer\",\n\t\t0x87AF : \"GeoTiffDirectory\",\n\t\t0x87B0 : \"GeoTiffDoubleParams\",\n\t\t0x87B1 : \"GeoTiffAsciiParams\",\n\t\t0x8822 : \"ExposureProgram\",\n\t\t0x8824 : \"SpectralSensitivity\",\n\t\t0x8825 : \"GPSInfo\",\n\t\t0x8827 : \"ISO\",\n\t\t0x8828 : \"Opto-ElectricConvFactor\",\n\t\t0x8829 : \"Interlace\",\n\t\t0x882A : \"TimeZoneOffset\",\n\t\t0x882B : \"SelfTimerMode\",\n\t\t0x8830 : \"SensitivityType\",\n\t\t0x8831 : \"StandardOutputSensitivity\",\n\t\t0x8832 : \"RecommendedExposureIndex\",\n\t\t0x8833 : \"ISOSpeed\",\n\t\t0x8834 : \"ISOSpeedLatitudeyyy\",\n\t\t0x8835 : \"ISOSpeedLatitudezzz\",\n\t\t0x885C : \"FaxRecvParams\",\n\t\t0x885D : \"FaxSubAddress\",\n\t\t0x885E : \"FaxRecvTime\",\n\t\t0x888A : \"LeafSubIFD\",\n\t\t0x9000 : \"ExifVersion\",\n\t\t0x9003 : \"DateTimeOriginal\",\n\t\t0x9004 : \"CreateDate\",\n\t\t0x9101 : \"ComponentsConfiguration\",\n\t\t0x9102 : \"CompressedBitsPerPixel\",\n\t\t0x9201 : \"ShutterSpeedValue\",\n\t\t0x9202 : \"ApertureValue\",\n\t\t0x9203 : \"BrightnessValue\",\n\t\t0x9204 : \"ExposureCompensation\",\n\t\t0x9205 : \"MaxApertureValue\",\n\t\t0x9206 : \"SubjectDistance\",\n\t\t0x9207 : \"MeteringMode\",\n\t\t0x9208 : \"LightSource\",\n\t\t0x9209 : \"Flash\",\n\t\t0x920A : \"FocalLength\",\n\t\t0x920B : \"FlashEnergy\",\n\t\t0x920C : \"SpatialFrequencyResponse\",\n\t\t0x920D : \"Noise\",\n\t\t0x920E : \"FocalPlaneXResolution\",\n\t\t0x920F : \"FocalPlaneYResolution\",\n\t\t0x9210 : \"FocalPlaneResolutionUnit\",\n\t\t0x9211 : \"ImageNumber\",\n\t\t0x9212 : \"SecurityClassification\",\n\t\t0x9213 : \"ImageHistory\",\n\t\t0x9214 : \"SubjectArea\",\n\t\t0x9215 : \"ExposureIndex\",\n\t\t0x9216 : \"TIFF-EPStandardID\",\n\t\t0x9217 : \"SensingMethod\",\n\t\t0x923A : \"CIP3DataFile\",\n\t\t0x923B : \"CIP3Sheet\",\n\t\t0x923C : \"CIP3Side\",\n\t\t0x923F : \"StoNits\",\n\t\t0x927C : \"MakerNote\",\n\t\t0x9286 : \"UserComment\",\n\t\t0x9290 : \"SubSecTime\",\n\t\t0x9291 : \"SubSecTimeOriginal\",\n\t\t0x9292 : \"SubSecTimeDigitized\",\n\t\t0x932F : \"MSDocumentText\",\n\t\t0x9330 : \"MSPropertySetStorage\",\n\t\t0x9331 : \"MSDocumentTextPosition\",\n\t\t0x935C : \"ImageSourceData\",\n\t\t0x9C9B : \"XPTitle\",\n\t\t0x9C9C : \"XPComment\",\n\t\t0x9C9D : \"XPAuthor\",\n\t\t0x9C9E : \"XPKeywords\",\n\t\t0x9C9F : \"XPSubject\",\n\t\t0xA000 : \"FlashpixVersion\",\n\t\t0xA001 : \"ColorSpace\",\n\t\t0xA002 : \"ExifImageWidth\",\n\t\t0xA003 : \"ExifImageHeight\",\n\t\t0xA004 : \"RelatedSoundFile\",\n\t\t0xA005 : \"InteropOffset\",\n\t\t0xA20B : \"FlashEnergy\",\n\t\t0xA20C : \"SpatialFrequencyResponse\",\n\t\t0xA20D : \"Noise\",\n\t\t0xA20E : \"FocalPlaneXResolution\",\n\t\t0xA20F : \"FocalPlaneYResolution\",\n\t\t0xA210 : \"FocalPlaneResolutionUnit\",\n\t\t0xA211 : \"ImageNumber\",\n\t\t0xA212 : \"SecurityClassification\",\n\t\t0xA213 : \"ImageHistory\",\n\t\t0xA214 : \"SubjectLocation\",\n\t\t0xA215 : \"ExposureIndex\",\n\t\t0xA216 : \"TIFF-EPStandardID\",\n\t\t0xA217 : \"SensingMethod\",\n\t\t0xA300 : \"FileSource\",\n\t\t0xA301 : \"SceneType\",\n\t\t0xA302 : \"CFAPattern\",\n\t\t0xA401 : \"CustomRendered\",\n\t\t0xA402 : \"ExposureMode\",\n\t\t0xA403 : \"WhiteBalance\",\n\t\t0xA404 : \"DigitalZoomRatio\",\n\t\t0xA405 : \"FocalLengthIn35mmFormat\",\n\t\t0xA406 : \"SceneCaptureType\",\n\t\t0xA407 : \"GainControl\",\n\t\t0xA408 : \"Contrast\",\n\t\t0xA409 : \"Saturation\",\n\t\t0xA40A : \"Sharpness\",\n\t\t0xA40B : \"DeviceSettingDescription\",\n\t\t0xA40C : \"SubjectDistanceRange\",\n\t\t0xA420 : \"ImageUniqueID\",\n\t\t0xA430 : \"OwnerName\",\n\t\t0xA431 : \"SerialNumber\",\n\t\t0xA432 : \"LensInfo\",\n\t\t0xA433 : \"LensMake\",\n\t\t0xA434 : \"LensModel\",\n\t\t0xA435 : \"LensSerialNumber\",\n\t\t0xA480 : \"GDALMetadata\",\n\t\t0xA481 : \"GDALNoData\",\n\t\t0xA500 : \"Gamma\",\n\t\t0xAFC0 : \"ExpandSoftware\",\n\t\t0xAFC1 : \"ExpandLens\",\n\t\t0xAFC2 : \"ExpandFilm\",\n\t\t0xAFC3 : \"ExpandFilterLens\",\n\t\t0xAFC4 : \"ExpandScanner\",\n\t\t0xAFC5 : \"ExpandFlashLamp\",\n\t\t0xBC01 : \"PixelFormat\",\n\t\t0xBC02 : \"Transformation\",\n\t\t0xBC03 : \"Uncompressed\",\n\t\t0xBC04 : \"ImageType\",\n\t\t0xBC80 : \"ImageWidth\",\n\t\t0xBC81 : \"ImageHeight\",\n\t\t0xBC82 : \"WidthResolution\",\n\t\t0xBC83 : \"HeightResolution\",\n\t\t0xBCC0 : \"ImageOffset\",\n\t\t0xBCC1 : \"ImageByteCount\",\n\t\t0xBCC2 : \"AlphaOffset\",\n\t\t0xBCC3 : \"AlphaByteCount\",\n\t\t0xBCC4 : \"ImageDataDiscard\",\n\t\t0xBCC5 : \"AlphaDataDiscard\",\n\t\t0xC427 : \"OceScanjobDesc\",\n\t\t0xC428 : \"OceApplicationSelector\",\n\t\t0xC429 : \"OceIDNumber\",\n\t\t0xC42A : \"OceImageLogic\",\n\t\t0xC44F : \"Annotations\",\n\t\t0xC4A5 : \"PrintIM\",\n\t\t0xC580 : \"USPTOOriginalContentType\",\n\t\t0xC612 : \"DNGVersion\",\n\t\t0xC613 : \"DNGBackwardVersion\",\n\t\t0xC614 : \"UniqueCameraModel\",\n\t\t0xC615 : \"LocalizedCameraModel\",\n\t\t0xC616 : \"CFAPlaneColor\",\n\t\t0xC617 : \"CFALayout\",\n\t\t0xC618 : \"LinearizationTable\",\n\t\t0xC619 : \"BlackLevelRepeatDim\",\n\t\t0xC61A : \"BlackLevel\",\n\t\t0xC61B : \"BlackLevelDeltaH\",\n\t\t0xC61C : \"BlackLevelDeltaV\",\n\t\t0xC61D : \"WhiteLevel\",\n\t\t0xC61E : \"DefaultScale\",\n\t\t0xC61F : \"DefaultCropOrigin\",\n\t\t0xC620 : \"DefaultCropSize\",\n\t\t0xC621 : \"ColorMatrix1\",\n\t\t0xC622 : \"ColorMatrix2\",\n\t\t0xC623 : \"CameraCalibration1\",\n\t\t0xC624 : \"CameraCalibration2\",\n\t\t0xC625 : \"ReductionMatrix1\",\n\t\t0xC626 : \"ReductionMatrix2\",\n\t\t0xC627 : \"AnalogBalance\",\n\t\t0xC628 : \"AsShotNeutral\",\n\t\t0xC629 : \"AsShotWhiteXY\",\n\t\t0xC62A : \"BaselineExposure\",\n\t\t0xC62B : \"BaselineNoise\",\n\t\t0xC62C : \"BaselineSharpness\",\n\t\t0xC62D : \"BayerGreenSplit\",\n\t\t0xC62E : \"LinearResponseLimit\",\n\t\t0xC62F : \"CameraSerialNumber\",\n\t\t0xC630 : \"DNGLensInfo\",\n\t\t0xC631 : \"ChromaBlurRadius\",\n\t\t0xC632 : \"AntiAliasStrength\",\n\t\t0xC633 : \"ShadowScale\",\n\t\t0xC634 : \"DNGPrivateData\",\n\t\t0xC635 : \"MakerNoteSafety\",\n\t\t0xC640 : \"RawImageSegmentation\",\n\t\t0xC65A : \"CalibrationIlluminant1\",\n\t\t0xC65B : \"CalibrationIlluminant2\",\n\t\t0xC65C : \"BestQualityScale\",\n\t\t0xC65D : \"RawDataUniqueID\",\n\t\t0xC660 : \"AliasLayerMetadata\",\n\t\t0xC68B : \"OriginalRawFileName\",\n\t\t0xC68C : \"OriginalRawFileData\",\n\t\t0xC68D : \"ActiveArea\",\n\t\t0xC68E : \"MaskedAreas\",\n\t\t0xC68F : \"AsShotICCProfile\",\n\t\t0xC690 : \"AsShotPreProfileMatrix\",\n\t\t0xC691 : \"CurrentICCProfile\",\n\t\t0xC692 : \"CurrentPreProfileMatrix\",\n\t\t0xC6BF : \"ColorimetricReference\",\n\t\t0xC6D2 : \"PanasonicTitle\",\n\t\t0xC6D3 : \"PanasonicTitle2\",\n\t\t0xC6F3 : \"CameraCalibrationSig\",\n\t\t0xC6F4 : \"ProfileCalibrationSig\",\n\t\t0xC6F5 : \"ProfileIFD\",\n\t\t0xC6F6 : \"AsShotProfileName\",\n\t\t0xC6F7 : \"NoiseReductionApplied\",\n\t\t0xC6F8 : \"ProfileName\",\n\t\t0xC6F9 : \"ProfileHueSatMapDims\",\n\t\t0xC6FA : \"ProfileHueSatMapData1\",\n\t\t0xC6FB : \"ProfileHueSatMapData2\",\n\t\t0xC6FC : \"ProfileToneCurve\",\n\t\t0xC6FD : \"ProfileEmbedPolicy\",\n\t\t0xC6FE : \"ProfileCopyright\",\n\t\t0xC714 : \"ForwardMatrix1\",\n\t\t0xC715 : \"ForwardMatrix2\",\n\t\t0xC716 : \"PreviewApplicationName\",\n\t\t0xC717 : \"PreviewApplicationVersion\",\n\t\t0xC718 : \"PreviewSettingsName\",\n\t\t0xC719 : \"PreviewSettingsDigest\",\n\t\t0xC71A : \"PreviewColorSpace\",\n\t\t0xC71B : \"PreviewDateTime\",\n\t\t0xC71C : \"RawImageDigest\",\n\t\t0xC71D : \"OriginalRawFileDigest\",\n\t\t0xC71E : \"SubTileBlockSize\",\n\t\t0xC71F : \"RowInterleaveFactor\",\n\t\t0xC725 : \"ProfileLookTableDims\",\n\t\t0xC726 : \"ProfileLookTableData\",\n\t\t0xC740 : \"OpcodeList1\",\n\t\t0xC741 : \"OpcodeList2\",\n\t\t0xC74E : \"OpcodeList3\",\n\t\t0xC761 : \"NoiseProfile\",\n\t\t0xC763 : \"TimeCodes\",\n\t\t0xC764 : \"FrameRate\",\n\t\t0xC772 : \"TStop\",\n\t\t0xC789 : \"ReelName\",\n\t\t0xC791 : \"OriginalDefaultFinalSize\",\n\t\t0xC792 : \"OriginalBestQualitySize\",\n\t\t0xC793 : \"OriginalDefaultCropSize\",\n\t\t0xC7A1 : \"CameraLabel\",\n\t\t0xC7A3 : \"ProfileHueSatMapEncoding\",\n\t\t0xC7A4 : \"ProfileLookTableEncoding\",\n\t\t0xC7A5 : \"BaselineExposureOffset\",\n\t\t0xC7A6 : \"DefaultBlackRender\",\n\t\t0xC7A7 : \"NewRawImageDigest\",\n\t\t0xC7A8 : \"RawToPreviewGain\",\n\t\t0xC7B5 : \"DefaultUserCrop\",\n\t\t0xEA1C : \"Padding\",\n\t\t0xEA1D : \"OffsetSchema\",\n\t\t0xFDE8 : \"OwnerName\",\n\t\t0xFDE9 : \"SerialNumber\",\n\t\t0xFDEA : \"Lens\",\n\t\t0xFE00 : \"KDC_IFD\",\n\t\t0xFE4C : \"RawFile\",\n\t\t0xFE4D : \"Converter\",\n\t\t0xFE4E : \"WhiteBalance\",\n\t\t0xFE51 : \"Exposure\",\n\t\t0xFE52 : \"Shadows\",\n\t\t0xFE53 : \"Brightness\",\n\t\t0xFE54 : \"Contrast\",\n\t\t0xFE55 : \"Saturation\",\n\t\t0xFE56 : \"Sharpness\",\n\t\t0xFE57 : \"Smoothness\",\n\t\t0xFE58 : \"MoireFilter\"\n\t\t\n\t},\n\tgps : {\t\n\t\t0x0000 : 'GPSVersionID',\n\t\t0x0001 : 'GPSLatitudeRef',\n\t\t0x0002 : 'GPSLatitude',\n\t\t0x0003 : 'GPSLongitudeRef',\n\t\t0x0004 : 'GPSLongitude',\n\t\t0x0005 : 'GPSAltitudeRef',\n\t\t0x0006 : 'GPSAltitude',\n\t\t0x0007 : 'GPSTimeStamp',\n\t\t0x0008 : 'GPSSatellites',\n\t\t0x0009 : 'GPSStatus',\n\t\t0x000A : 'GPSMeasureMode',\n\t\t0x000B : 'GPSDOP',\n\t\t0x000C : 'GPSSpeedRef',\n\t\t0x000D : 'GPSSpeed',\n\t\t0x000E : 'GPSTrackRef',\n\t\t0x000F : 'GPSTrack',\n\t\t0x0010 : 'GPSImgDirectionRef',\n\t\t0x0011 : 'GPSImgDirection',\n\t\t0x0012 : 'GPSMapDatum',\n\t\t0x0013 : 'GPSDestLatitudeRef',\n\t\t0x0014 : 'GPSDestLatitude',\n\t\t0x0015 : 'GPSDestLongitudeRef',\n\t\t0x0016 : 'GPSDestLongitude',\n\t\t0x0017 : 'GPSDestBearingRef',\n\t\t0x0018 : 'GPSDestBearing',\n\t\t0x0019 : 'GPSDestDistanceRef',\n\t\t0x001A : 'GPSDestDistance',\n\t\t0x001B : 'GPSProcessingMethod',\n\t\t0x001C : 'GPSAreaInformation',\n\t\t0x001D : 'GPSDateStamp',\n\t\t0x001E : 'GPSDifferential',\n\t\t0x001F : 'GPSHPositioningError'\n\t}\n};","/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */\n\nfunction readExifValue(format, stream) {\n\tswitch(format) {\n\t\tcase 1: return stream.nextUInt8();\n\t\tcase 3: return stream.nextUInt16();\n\t\tcase 4: return stream.nextUInt32();\n\t\tcase 5: return [stream.nextUInt32(), stream.nextUInt32()];\n\t\tcase 6: return stream.nextInt8();\n\t\tcase 8: return stream.nextUInt16();\n\t\tcase 9: return stream.nextUInt32();\n\t\tcase 10: return [stream.nextInt32(), stream.nextInt32()];\n\t\tcase 11: return stream.nextFloat();\n\t\tcase 12: return stream.nextDouble();\n\t\tdefault: throw new Error('Invalid format while decoding: ' + format);\n\t}\n}\n\nfunction getBytesPerComponent(format) {\n\tswitch(format) {\n\t\tcase 1:\n\t\tcase 2:\n\t\tcase 6:\n\t\tcase 7:\n\t\t\treturn 1;\n\t\tcase 3:\n\t\tcase 8:\n\t\t\treturn 2;\n\t\tcase 4:\n\t\tcase 9:\n\t\tcase 11:\n\t\t\treturn 4;\n\t\tcase 5:\n\t\tcase 10:\n\t\tcase 12:\n\t\t\treturn 8;\n\t\tdefault:\n\t\t\treturn 0;\n\t}\n}\n\nfunction readExifTag(tiffMarker, stream) {\n\tvar tagType = stream.nextUInt16(),\n\t\tformat = stream.nextUInt16(),\n\t\tbytesPerComponent = getBytesPerComponent(format),\n\t\tcomponents = stream.nextUInt32(),\n\t\tvalueBytes = bytesPerComponent * components,\n\t\tvalues,\n\t\tvalue,\n\t\tc;\n\n\t/* if the value is bigger then 4 bytes, the value is in the data section of the IFD\n\tand the value present in the tag is the offset starting from the tiff header. So we replace the stream\n\twith a stream that is located at the given offset in the data section. s*/\n\tif(valueBytes > 4) {\n\t\tstream = tiffMarker.openWithOffset(stream.nextUInt32());\n\t}\n\t//we don't want to read strings as arrays\n\tif(format === 2) {\n\t\tvalues = stream.nextString(components);\n\t\t//cut off \\0 characters\n\t\tvar lastNull = values.indexOf('\\0');\n\t\tif(lastNull !== -1) {\n\t\t\tvalues = values.substr(0, lastNull);\n\t\t}\n\t}\n\telse if(format === 7) {\n\t\tvalues = stream.nextBuffer(components);\n\t}\n\telse if(format !== 0) {\n\t\tvalues = [];\n\t\tfor(c = 0; c < components; ++c) {\n\t\t\tvalues.push(readExifValue(format, stream));\n\t\t}\n\t}\n\t//since our stream is a stateful object, we need to skip remaining bytes\n\t//so our offset stays correct\n\tif(valueBytes < 4) {\n\t\tstream.skip(4 - valueBytes);\n\t}\n\n\treturn [tagType, values, format];\n}\n\nfunction readIFDSection(tiffMarker, stream, iterator) {\n\tvar numberOfEntries = stream.nextUInt16(), tag, i;\n\tfor(i = 0; i < numberOfEntries; ++i) {\n\t\ttag = readExifTag(tiffMarker, stream);\n\t\titerator(tag[0], tag[1], tag[2]);\n\t}\n}\n\nfunction readHeader(stream) {\n\tvar exifHeader = stream.nextString(6);\n\tif(exifHeader !== 'Exif\\0\\0') {\n\t\tthrow new Error('Invalid EXIF header');\n\t}\n\n\tvar tiffMarker = stream.mark();\n\tvar tiffHeader = stream.nextUInt16();\n\tif(tiffHeader === 0x4949) {\n\t\tstream.setBigEndian(false);\n\t} else if(tiffHeader === 0x4D4D) {\n\t\tstream.setBigEndian(true);\n\t} else {\n\t\tthrow new Error('Invalid TIFF header');\n\t}\n\tif(stream.nextUInt16() !== 0x002A) {\n\t\tthrow new Error('Invalid TIFF data');\n\t}\n\treturn tiffMarker;\n}\n\nmodule.exports = {\n\tIFD0: 1,\n\tIFD1: 2,\n\tGPSIFD: 3,\n\tSubIFD: 4,\n\tInteropIFD: 5,\n\tparseTags: function(stream, iterator) {\n\t\tvar tiffMarker;\n\t\ttry {\n\t\t\ttiffMarker = readHeader(stream);\n\t\t} catch(e) {\n\t\t\treturn false;\t//ignore APP1 sections with invalid headers\n\t\t}\n\t\tvar subIfdOffset, gpsOffset, interopOffset;\n\t\tvar ifd0Stream = tiffMarker.openWithOffset(stream.nextUInt32()),\n\t\t\tIFD0 = this.IFD0;\n\t\treadIFDSection(tiffMarker, ifd0Stream, function(tagType, value, format) {\n\t\t\tswitch(tagType) {\n\t\t\t\tcase 0x8825: gpsOffset = value[0]; break;\n\t\t\t\tcase 0x8769: subIfdOffset = value[0]; break;\n\t\t\t\tdefault: iterator(IFD0, tagType, value, format); break;\n\t\t\t}\n\t\t});\n\t\tvar ifd1Offset = ifd0Stream.nextUInt32();\n\t\tif(ifd1Offset !== 0) {\n\t\t\tvar ifd1Stream = tiffMarker.openWithOffset(ifd1Offset);\n\t\t\treadIFDSection(tiffMarker, ifd1Stream, iterator.bind(null, this.IFD1));\n\t\t}\n\n\t\tif(gpsOffset) {\n\t\t\tvar gpsStream = tiffMarker.openWithOffset(gpsOffset);\n\t\t\treadIFDSection(tiffMarker, gpsStream, iterator.bind(null, this.GPSIFD));\n\t\t}\n\n\t\tif(subIfdOffset) {\n\t\t\tvar subIfdStream = tiffMarker.openWithOffset(subIfdOffset), InteropIFD = this.InteropIFD;\n\t\t\treadIFDSection(tiffMarker, subIfdStream, function(tagType, value, format) {\n\t\t\t\tif(tagType === 0xA005) {\n\t\t\t\t\tinteropOffset = value[0];\n\t\t\t\t} else {\n\t\t\t\t\titerator(InteropIFD, tagType, value, format);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif(interopOffset) {\n\t\t\tvar interopStream = tiffMarker.openWithOffset(interopOffset);\n\t\t\treadIFDSection(tiffMarker, interopStream, iterator.bind(null, this.InteropIFD));\n\t\t}\n\t\treturn true;\n\t}\n};","/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */\n\nmodule.exports = {\n\tparseSections: function(stream, iterator) {\n\t\tvar len, markerType;\n\t\tstream.setBigEndian(true);\n\t\t//stop reading the stream at the SOS (Start of Stream) marker,\n\t\t//because its length is not stored in the header so we can't\n\t\t//know where to jump to. The only marker after that is just EOI (End Of Image) anyway\n\t\twhile(stream.remainingLength() > 0 && markerType !== 0xDA) {\n\t\t\tif(stream.nextUInt8() !== 0xFF) {\n\t\t\t\tthrow new Error('Invalid JPEG section offset');\n\t\t\t}\n\t\t\tmarkerType = stream.nextUInt8();\n\t\t\t//don't read size from markers that have no datas\n\t\t\tif((markerType >= 0xD0 && markerType <= 0xD9) || markerType === 0xDA) {\n\t\t\t\tlen = 0;\n\t\t\t} else {\n\t\t\t\tlen = stream.nextUInt16() - 2;\n\t\t\t}\n\t\t\titerator(markerType, stream.branch(0, len));\n\t\t\tstream.skip(len);\n\t\t}\n\t},\n\t//stream should be located after SOF section size and in big endian mode, like passed to parseSections iterator\n\tgetSizeFromSOFSection: function(stream) {\n\t\tstream.skip(1);\n\t\treturn {\n\t\t\theight: stream.nextUInt16(),\n\t\t\twidth: stream.nextUInt16()\n\t\t};\n\t},\n\tgetSectionName: function(markerType) {\n\t\tvar name, index;\n\t\tswitch(markerType) {\n\t\t\tcase 0xD8: name = 'SOI'; break;\n\t\t\tcase 0xC4: name = 'DHT'; break;\n\t\t\tcase 0xDB: name = 'DQT'; break;\n\t\t\tcase 0xDD: name = 'DRI'; break;\n\t\t\tcase 0xDA: name = 'SOS'; break;\n\t\t\tcase 0xFE: name = 'COM'; break;\n\t\t\tcase 0xD9: name = 'EOI'; break;\n\t\t\tdefault:\n\t\t\t\tif(markerType >= 0xE0 && markerType <= 0xEF) {\n\t\t\t\t\tname = 'APP';\n\t\t\t\t\tindex = markerType - 0xE0;\n\t\t\t\t}\n\t\t\t\telse if(markerType >= 0xC0 && markerType <= 0xCF && markerType !== 0xC4 && markerType !== 0xC8 && markerType !== 0xCC) {\n\t\t\t\t\tname = 'SOF';\n\t\t\t\t\tindex = markerType - 0xC0;\n\t\t\t\t}\n\t\t\t\telse if(markerType >= 0xD0 && markerType <= 0xD7) {\n\t\t\t\t\tname = 'RST';\n\t\t\t\t\tindex = markerType - 0xD0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t\tvar nameStruct = {\n\t\t\tname: name\n\t\t};\n\t\tif(typeof index === 'number') {\n\t\t\tnameStruct.index = index;\n\t\t}\n\t\treturn nameStruct;\n\t}\n};","/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */\n\nvar jpeg = require('./jpeg'),\n\texif = require('./exif'),\n\tsimplify = require('./simplify');\n\nfunction ExifResult(startMarker, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset) {\n\tthis.startMarker = startMarker;\n\tthis.tags = tags;\n\tthis.imageSize = imageSize;\n\tthis.thumbnailOffset = thumbnailOffset;\n\tthis.thumbnailLength = thumbnailLength;\n\tthis.thumbnailType = thumbnailType;\n\tthis.app1Offset = app1Offset;\n}\n\nExifResult.prototype = {\n\thasThumbnail: function(mime) {\n\t\tif(!this.thumbnailOffset || !this.thumbnailLength) {\n\t\t\treturn false;\n\t\t}\n\t\tif(typeof mime !== 'string') {\n\t\t\treturn true;\n\t\t}\n\t\tif(mime.toLowerCase().trim() === 'image/jpeg') {\n\t\t\treturn this.thumbnailType === 6;\n\t\t}\n\t\tif(mime.toLowerCase().trim() === 'image/tiff') {\n\t\t\treturn this.thumbnailType === 1;\n\t\t}\n\t\treturn false;\n\t},\n\tgetThumbnailOffset: function() {\n\t\treturn this.app1Offset + 6 + this.thumbnailOffset;\n\t},\n\tgetThumbnailLength: function() {\n\t\treturn this.thumbnailLength;\n\t},\n\tgetThumbnailBuffer: function() {\n\t\treturn this._getThumbnailStream().nextBuffer(this.thumbnailLength);\n\t},\n\t_getThumbnailStream: function() {\n\t\treturn this.startMarker.openWithOffset(this.getThumbnailOffset());\n\t},\n\tgetImageSize: function() {\n\t\treturn this.imageSize;\n\t},\n\tgetThumbnailSize: function() {\n\t\tvar stream = this._getThumbnailStream(), size;\n\t\tjpeg.parseSections(stream, function(sectionType, sectionStream) {\n\t\t\tif(jpeg.getSectionName(sectionType).name === 'SOF') {\n\t\t\t\tsize = jpeg.getSizeFromSOFSection(sectionStream);\n\t\t\t}\n\t\t});\n\t\treturn size;\n\t}\n};\n\nfunction Parser(stream) {\n\tthis.stream = stream;\n\tthis.flags = {\n\t\treadBinaryTags: false,\n\t\tresolveTagNames: true,\n\t\tsimplifyValues: true,\n\t\timageSize: true,\n\t\thidePointers: true,\n\t\treturnTags: true\n\t};\n}\n\nParser.prototype = {\n\tenableBinaryFields: function(enable) {\n\t\tthis.flags.readBinaryTags = !!enable;\n\t\treturn this;\n\t},\n\tenablePointers: function(enable) {\n\t\tthis.flags.hidePointers = !enable;\n\t\treturn this;\n\t},\n\tenableTagNames: function(enable) {\n\t\tthis.flags.resolveTagNames = !!enable;\n\t\treturn this;\n\t},\n\tenableImageSize: function(enable) {\n\t\tthis.flags.imageSize = !!enable;\n\t\treturn this;\n\t},\n\tenableReturnTags: function(enable) {\n\t\tthis.flags.returnTags = !!enable;\n\t\treturn this;\n\t},\n\tenableSimpleValues: function(enable) {\n\t\tthis.flags.simplifyValues = !!enable;\n\t\treturn this;\n\t},\n\tparse: function() {\n\t\tvar start = this.stream.mark(),\n\t\t\tstream = start.openWithOffset(0),\n\t\t\tflags = this.flags,\n\t\t\ttags,\n\t\t\timageSize,\n\t\t\tthumbnailOffset,\n\t\t\tthumbnailLength,\n\t\t\tthumbnailType,\n\t\t\tapp1Offset,\n\t\t\ttagNames,\n\t\t\tgetTagValue, setTagValue;\n\t\tif(flags.resolveTagNames) {\n\t\t\ttagNames = require('./exif-tags');\n\t\t}\n\t\tif(flags.resolveTagNames) {\n\t\t\ttags = {};\n\t\t\tgetTagValue = function(t) {\n\t\t\t\treturn tags[t.name];\n\t\t\t};\n\t\t\tsetTagValue = function(t, value) {\n\t\t\t\ttags[t.name] = value;\n\t\t\t};\n\t\t} else {\n\t\t\ttags = [];\n\t\t\tgetTagValue = function(t) {\n\t\t\t\tvar i;\n\t\t\t\tfor(i = 0; i < tags.length; ++i) {\n\t\t\t\t\tif(tags[i].type === t.type && tags[i].section === t.section) {\n\t\t\t\t\t\treturn tags.value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tsetTagValue = function(t, value) {\n\t\t\t\tvar i;\n\t\t\t\tfor(i = 0; i < tags.length; ++i) {\n\t\t\t\t\tif(tags[i].type === t.type && tags[i].section === t.section) {\n\t\t\t\t\t\ttags.value = value;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\n\t\tjpeg.parseSections(stream, function(sectionType, sectionStream) {\n\t\t\tvar validExifHeaders, sectionOffset = sectionStream.offsetFrom(start);\n\t\t\tif(sectionType === 0xE1) {\n\t\t\t\tvalidExifHeaders = exif.parseTags(sectionStream, function(ifdSection, tagType, value, format) {\n\t\t\t\t\t//ignore binary fields if disabled\n\t\t\t\t\tif(!flags.readBinaryTags && format === 7) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(tagType === 0x0201) {\n\t\t\t\t\t\tthumbnailOffset = value[0];\n\t\t\t\t\t\tif(flags.hidePointers) {return;}\n\t\t\t\t\t} else if(tagType === 0x0202) {\n\t\t\t\t\t\tthumbnailLength = value[0];\n\t\t\t\t\t\tif(flags.hidePointers) {return;}\n\t\t\t\t\t} else if(tagType === 0x0103) {\n\t\t\t\t\t\tthumbnailType = value[0];\n\t\t\t\t\t\tif(flags.hidePointers) {return;}\n\t\t\t\t\t}\n\t\t\t\t\t//if flag is set to not store tags, return here after storing pointers\n\t\t\t\t\tif(!flags.returnTags) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(flags.simplifyValues) {\n\t\t\t\t\t\tvalue = simplify.simplifyValue(value, format);\n\t\t\t\t\t}\n\t\t\t\t\tif(flags.resolveTagNames) {\n\t\t\t\t\t\tvar sectionTagNames = ifdSection === exif.GPSIFD ? tagNames.gps : tagNames.exif;\n\t\t\t\t\t\tvar name = sectionTagNames[tagType];\n\t\t\t\t\t\tif(!name) {\n\t\t\t\t\t\t\tname = tagNames.exif[tagType];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!tags.hasOwnProperty(name)) {\n\t\t\t\t\t\t\ttags[name] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttags.push({\n\t\t\t\t\t\t\tsection: ifdSection,\n\t\t\t\t\t\t\ttype: tagType,\n\t\t\t\t\t\t\tvalue: value\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif(validExifHeaders) {\n\t\t\t\t\tapp1Offset = sectionOffset;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(flags.imageSize && jpeg.getSectionName(sectionType).name === 'SOF') {\n\t\t\t\timageSize = jpeg.getSizeFromSOFSection(sectionStream);\n\t\t\t}\n\t\t});\n\n\t\tif(flags.simplifyValues) {\n\t\t\tsimplify.castDegreeValues(getTagValue, setTagValue);\n\t\t\tsimplify.castDateValues(getTagValue, setTagValue);\n\t\t}\n\n\t\treturn new ExifResult(start, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset);\n\t}\n};\n\n\n\nmodule.exports = Parser;\n","var exif = require('./exif');\nvar date = require('./date');\n\nvar degreeTags = [{\n\tsection: exif.GPSIFD,\n\ttype: 0x0002,\n\tname: 'GPSLatitude',\n\trefType: 0x0001,\n\trefName: 'GPSLatitudeRef',\n\tposVal: 'N'\n},\n{\n\tsection: exif.GPSIFD,\n\ttype: 0x0004,\n\tname: 'GPSLongitude',\n\trefType: 0x0003,\n\trefName: 'GPSLongitudeRef',\n\tposVal: 'E'\n}];\nvar dateTags = [{\n\tsection: exif.SubIFD,\n\ttype: 0x0132,\n\tname: 'ModifyDate'\n},\n{\n\tsection: exif.SubIFD,\n\ttype: 0x9003,\n\tname: 'DateTimeOriginal'\n},\n{\n\tsection: exif.SubIFD,\n\ttype: 0x9004,\n\tname: 'CreateDate'\n},\n{\n\tsection: exif.SubIFD,\n\ttype: 0x0132,\n\tname : 'ModifyDate',\n}];\n\nmodule.exports = {\n\tcastDegreeValues: function(getTagValue, setTagValue) {\n\t\tdegreeTags.forEach(function(t) {\n\t\t\tvar degreeVal = getTagValue(t);\n\t\t\tif(degreeVal) {\n\t\t\t\tvar degreeRef = getTagValue({section: t.section, type: t.refType, name: t.refName});\n\t\t\t\tvar degreeNumRef = degreeRef === t.posVal ? 1 : -1;\n\t\t\t\tvar degree = (degreeVal[0] + (degreeVal[1] / 60) + (degreeVal[2] / 3600)) * degreeNumRef;\n\t\t\t\tsetTagValue(t, degree);\n\t\t\t}\n\t\t});\n\t},\n\tcastDateValues: function(getTagValue, setTagValue) {\n\t\tdateTags.forEach(function(t) {\n\t\t\tvar dateStrVal = getTagValue(t);\n\t\t\tif(dateStrVal) {\n\t\t\t\t//some easy checks to determine two common date formats\n\t\t\t\tvar timestamp = date.parseExifDate(dateStrVal);\n\t\t\t\tif(typeof timestamp !== 'undefined') {\n\t\t\t\t\tsetTagValue(t, timestamp);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t},\n\tsimplifyValue: function(values, format) {\n\t\tif(Array.isArray(values)) {\n\t\t\tvalues = values.map(function(value) {\n\t\t\t\tif(format === 10 || format === 5) {\n\t\t\t\t\treturn value[0] / value[1];\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t});\n\t\t\tif(values.length === 1) {\n\t\t\t\tvalues = values[0];\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}\n};\n","'use strict';\nconst Token = require('token-types');\nconst strtok3 = require('strtok3/lib/core');\nconst {\n\tstringToBytes,\n\ttarHeaderChecksumMatches,\n\tuint32SyncSafeToken\n} = require('./util');\nconst supported = require('./supported');\n\nconst minimumBytes = 4100; // A fair amount of file-types are detectable within this range\n\nasync function fromStream(stream) {\n\tconst tokenizer = await strtok3.fromStream(stream);\n\ttry {\n\t\treturn await fromTokenizer(tokenizer);\n\t} finally {\n\t\tawait tokenizer.close();\n\t}\n}\n\nasync function fromBuffer(input) {\n\tif (!(input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer.isBuffer(input))) {\n\t\tthrow new TypeError(`Expected the \\`input\\` argument to be of type \\`Uint8Array\\` or \\`Buffer\\` or \\`ArrayBuffer\\`, got \\`${typeof input}\\``);\n\t}\n\n\tconst buffer = input instanceof Buffer ? input : Buffer.from(input);\n\n\tif (!(buffer && buffer.length > 1)) {\n\t\treturn;\n\t}\n\n\tconst tokenizer = strtok3.fromBuffer(buffer);\n\treturn fromTokenizer(tokenizer);\n}\n\nfunction _check(buffer, headers, options) {\n\toptions = {\n\t\toffset: 0,\n\t\t...options\n\t};\n\n\tfor (const [index, header] of headers.entries()) {\n\t\t// If a bitmask is set\n\t\tif (options.mask) {\n\t\t\t// If header doesn't equal `buf` with bits masked off\n\t\t\tif (header !== (options.mask[index] & buffer[index + options.offset])) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (header !== buffer[index + options.offset]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nasync function fromTokenizer(tokenizer) {\n\ttry {\n\t\treturn _fromTokenizer(tokenizer);\n\t} catch (error) {\n\t\tif (!(error instanceof strtok3.EndOfStreamError)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nasync function _fromTokenizer(tokenizer) {\n\tlet buffer = Buffer.alloc(minimumBytes);\n\tconst bytesRead = 12;\n\tconst check = (header, options) => _check(buffer, header, options);\n\tconst checkString = (header, options) => check(stringToBytes(header), options);\n\n\t// Keep reading until EOF if the file size is unknown.\n\tif (!tokenizer.fileInfo.size) {\n\t\ttokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER;\n\t}\n\n\tawait tokenizer.peekBuffer(buffer, {length: bytesRead, mayBeLess: true});\n\n\t// -- 2-byte signatures --\n\n\tif (check([0x42, 0x4D])) {\n\t\treturn {\n\t\t\text: 'bmp',\n\t\t\tmime: 'image/bmp'\n\t\t};\n\t}\n\n\tif (check([0x0B, 0x77])) {\n\t\treturn {\n\t\t\text: 'ac3',\n\t\t\tmime: 'audio/vnd.dolby.dd-raw'\n\t\t};\n\t}\n\n\tif (check([0x78, 0x01])) {\n\t\treturn {\n\t\t\text: 'dmg',\n\t\t\tmime: 'application/x-apple-diskimage'\n\t\t};\n\t}\n\n\tif (check([0x4D, 0x5A])) {\n\t\treturn {\n\t\t\text: 'exe',\n\t\t\tmime: 'application/x-msdownload'\n\t\t};\n\t}\n\n\tif (check([0x25, 0x21])) {\n\t\tawait tokenizer.peekBuffer(buffer, {length: 24, mayBeLess: true});\n\n\t\tif (checkString('PS-Adobe-', {offset: 2}) &&\n\t\t\tcheckString(' EPSF-', {offset: 14})) {\n\t\t\treturn {\n\t\t\t\text: 'eps',\n\t\t\t\tmime: 'application/eps'\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\text: 'ps',\n\t\t\tmime: 'application/postscript'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x1F, 0xA0]) ||\n\t\tcheck([0x1F, 0x9D])\n\t) {\n\t\treturn {\n\t\t\text: 'Z',\n\t\t\tmime: 'application/x-compress'\n\t\t};\n\t}\n\n\t// -- 3-byte signatures --\n\n\tif (check([0xFF, 0xD8, 0xFF])) {\n\t\treturn {\n\t\t\text: 'jpg',\n\t\t\tmime: 'image/jpeg'\n\t\t};\n\t}\n\n\tif (check([0x49, 0x49, 0xBC])) {\n\t\treturn {\n\t\t\text: 'jxr',\n\t\t\tmime: 'image/vnd.ms-photo'\n\t\t};\n\t}\n\n\tif (check([0x1F, 0x8B, 0x8])) {\n\t\treturn {\n\t\t\text: 'gz',\n\t\t\tmime: 'application/gzip'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x5A, 0x68])) {\n\t\treturn {\n\t\t\text: 'bz2',\n\t\t\tmime: 'application/x-bzip2'\n\t\t};\n\t}\n\n\tif (checkString('ID3')) {\n\t\tawait tokenizer.ignore(6); // Skip ID3 header until the header size\n\t\tconst id3HeaderLen = await tokenizer.readToken(uint32SyncSafeToken);\n\t\tif (tokenizer.position + id3HeaderLen > tokenizer.fileInfo.size) {\n\t\t\t// Guess file type based on ID3 header for backward compatibility\n\t\t\treturn {\n\t\t\t\text: 'mp3',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\tawait tokenizer.ignore(id3HeaderLen);\n\t\treturn fromTokenizer(tokenizer); // Skip ID3 header, recursion\n\t}\n\n\t// Musepack, SV7\n\tif (checkString('MP+')) {\n\t\treturn {\n\t\t\text: 'mpc',\n\t\t\tmime: 'audio/x-musepack'\n\t\t};\n\t}\n\n\tif (\n\t\t(buffer[0] === 0x43 || buffer[0] === 0x46) &&\n\t\tcheck([0x57, 0x53], {offset: 1})\n\t) {\n\t\treturn {\n\t\t\text: 'swf',\n\t\t\tmime: 'application/x-shockwave-flash'\n\t\t};\n\t}\n\n\t// -- 4-byte signatures --\n\n\tif (check([0x47, 0x49, 0x46])) {\n\t\treturn {\n\t\t\text: 'gif',\n\t\t\tmime: 'image/gif'\n\t\t};\n\t}\n\n\tif (checkString('FLIF')) {\n\t\treturn {\n\t\t\text: 'flif',\n\t\t\tmime: 'image/flif'\n\t\t};\n\t}\n\n\tif (checkString('8BPS')) {\n\t\treturn {\n\t\t\text: 'psd',\n\t\t\tmime: 'image/vnd.adobe.photoshop'\n\t\t};\n\t}\n\n\tif (checkString('WEBP', {offset: 8})) {\n\t\treturn {\n\t\t\text: 'webp',\n\t\t\tmime: 'image/webp'\n\t\t};\n\t}\n\n\t// Musepack, SV8\n\tif (checkString('MPCK')) {\n\t\treturn {\n\t\t\text: 'mpc',\n\t\t\tmime: 'audio/x-musepack'\n\t\t};\n\t}\n\n\tif (checkString('FORM')) {\n\t\treturn {\n\t\t\text: 'aif',\n\t\t\tmime: 'audio/aiff'\n\t\t};\n\t}\n\n\tif (checkString('icns', {offset: 0})) {\n\t\treturn {\n\t\t\text: 'icns',\n\t\t\tmime: 'image/icns'\n\t\t};\n\t}\n\n\t// Zip-based file formats\n\t// Need to be before the `zip` check\n\tif (check([0x50, 0x4B, 0x3, 0x4])) { // Local file header signature\n\t\ttry {\n\t\t\twhile (tokenizer.position + 30 < tokenizer.fileInfo.size) {\n\t\t\t\tawait tokenizer.readBuffer(buffer, {length: 30});\n\n\t\t\t\t// https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers\n\t\t\t\tconst zipHeader = {\n\t\t\t\t\tcompressedSize: buffer.readUInt32LE(18),\n\t\t\t\t\tuncompressedSize: buffer.readUInt32LE(22),\n\t\t\t\t\tfilenameLength: buffer.readUInt16LE(26),\n\t\t\t\t\textraFieldLength: buffer.readUInt16LE(28)\n\t\t\t\t};\n\n\t\t\t\tzipHeader.filename = await tokenizer.readToken(new Token.StringType(zipHeader.filenameLength, 'utf-8'));\n\t\t\t\tawait tokenizer.ignore(zipHeader.extraFieldLength);\n\n\t\t\t\t// Assumes signed `.xpi` from addons.mozilla.org\n\t\t\t\tif (zipHeader.filename === 'META-INF/mozilla.rsa') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'xpi',\n\t\t\t\t\t\tmime: 'application/x-xpinstall'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (zipHeader.filename.endsWith('.rels') || zipHeader.filename.endsWith('.xml')) {\n\t\t\t\t\tconst type = zipHeader.filename.split('/')[0];\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase '_rels':\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'word':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'docx',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'ppt':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'pptx',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'xl':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'xlsx',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (zipHeader.filename.startsWith('xl/')) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'xlsx',\n\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (zipHeader.filename.startsWith('3D/') && zipHeader.filename.endsWith('.model')) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: '3mf',\n\t\t\t\t\t\tmime: 'model/3mf'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// The docx, xlsx and pptx file types extend the Office Open XML file format:\n\t\t\t\t// https://en.wikipedia.org/wiki/Office_Open_XML_file_formats\n\t\t\t\t// We look for:\n\t\t\t\t// - one entry named '[Content_Types].xml' or '_rels/.rels',\n\t\t\t\t// - one entry indicating specific type of file.\n\t\t\t\t// MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it.\n\t\t\t\tif (zipHeader.filename === 'mimetype' && zipHeader.compressedSize === zipHeader.uncompressedSize) {\n\t\t\t\t\tconst mimeType = await tokenizer.readToken(new Token.StringType(zipHeader.compressedSize, 'utf-8'));\n\n\t\t\t\t\tswitch (mimeType) {\n\t\t\t\t\t\tcase 'application/epub+zip':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'epub',\n\t\t\t\t\t\t\t\tmime: 'application/epub+zip'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'application/vnd.oasis.opendocument.text':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'odt',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.oasis.opendocument.text'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'application/vnd.oasis.opendocument.spreadsheet':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'ods',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.oasis.opendocument.spreadsheet'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'application/vnd.oasis.opendocument.presentation':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'odp',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.oasis.opendocument.presentation'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Try to find next header manually when current one is corrupted\n\t\t\t\tif (zipHeader.compressedSize === 0) {\n\t\t\t\t\tlet nextHeaderIndex = -1;\n\n\t\t\t\t\twhile (nextHeaderIndex < 0 && (tokenizer.position < tokenizer.fileInfo.size)) {\n\t\t\t\t\t\tawait tokenizer.peekBuffer(buffer, {mayBeLess: true});\n\n\t\t\t\t\t\tnextHeaderIndex = buffer.indexOf('504B0304', 0, 'hex');\n\t\t\t\t\t\t// Move position to the next header if found, skip the whole buffer otherwise\n\t\t\t\t\t\tawait tokenizer.ignore(nextHeaderIndex >= 0 ? nextHeaderIndex : buffer.length);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tawait tokenizer.ignore(zipHeader.compressedSize);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof strtok3.EndOfStreamError)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\text: 'zip',\n\t\t\tmime: 'application/zip'\n\t\t};\n\t}\n\n\tif (checkString('OggS')) {\n\t\t// This is an OGG container\n\t\tawait tokenizer.ignore(28);\n\t\tconst type = Buffer.alloc(8);\n\t\tawait tokenizer.readBuffer(type);\n\n\t\t// Needs to be before `ogg` check\n\t\tif (_check(type, [0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64])) {\n\t\t\treturn {\n\t\t\t\text: 'opus',\n\t\t\t\tmime: 'audio/opus'\n\t\t\t};\n\t\t}\n\n\t\t// If ' theora' in header.\n\t\tif (_check(type, [0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61])) {\n\t\t\treturn {\n\t\t\t\text: 'ogv',\n\t\t\t\tmime: 'video/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If '\\x01video' in header.\n\t\tif (_check(type, [0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00])) {\n\t\t\treturn {\n\t\t\t\text: 'ogm',\n\t\t\t\tmime: 'video/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If ' FLAC' in header https://xiph.org/flac/faq.html\n\t\tif (_check(type, [0x7F, 0x46, 0x4C, 0x41, 0x43])) {\n\t\t\treturn {\n\t\t\t\text: 'oga',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// 'Speex ' in header https://en.wikipedia.org/wiki/Speex\n\t\tif (_check(type, [0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20])) {\n\t\t\treturn {\n\t\t\t\text: 'spx',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If '\\x01vorbis' in header\n\t\tif (_check(type, [0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73])) {\n\t\t\treturn {\n\t\t\t\text: 'ogg',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// Default OGG container https://www.iana.org/assignments/media-types/application/ogg\n\t\treturn {\n\t\t\text: 'ogx',\n\t\t\tmime: 'application/ogg'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x50, 0x4B]) &&\n\t\t(buffer[2] === 0x3 || buffer[2] === 0x5 || buffer[2] === 0x7) &&\n\t\t(buffer[3] === 0x4 || buffer[3] === 0x6 || buffer[3] === 0x8)\n\t) {\n\t\treturn {\n\t\t\text: 'zip',\n\t\t\tmime: 'application/zip'\n\t\t};\n\t}\n\n\t//\n\n\t// File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)\n\t// It's not required to be first, but it's recommended to be. Almost all ISO base media files start with `ftyp` box.\n\t// `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters.\n\t// Here we check for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character).\n\tif (\n\t\tcheckString('ftyp', {offset: 4}) &&\n\t\t(buffer[8] & 0x60) !== 0x00 // Brand major, first character ASCII?\n\t) {\n\t\t// They all can have MIME `video/mp4` except `application/mp4` special-case which is hard to detect.\n\t\t// For some cases, we're specific, everything else falls to `video/mp4` with `mp4` extension.\n\t\tconst brandMajor = buffer.toString('binary', 8, 12).replace('\\0', ' ').trim();\n\t\tswitch (brandMajor) {\n\t\t\tcase 'avif':\n\t\t\t\treturn {ext: 'avif', mime: 'image/avif'};\n\t\t\tcase 'mif1':\n\t\t\t\treturn {ext: 'heic', mime: 'image/heif'};\n\t\t\tcase 'msf1':\n\t\t\t\treturn {ext: 'heic', mime: 'image/heif-sequence'};\n\t\t\tcase 'heic':\n\t\t\tcase 'heix':\n\t\t\t\treturn {ext: 'heic', mime: 'image/heic'};\n\t\t\tcase 'hevc':\n\t\t\tcase 'hevx':\n\t\t\t\treturn {ext: 'heic', mime: 'image/heic-sequence'};\n\t\t\tcase 'qt':\n\t\t\t\treturn {ext: 'mov', mime: 'video/quicktime'};\n\t\t\tcase 'M4V':\n\t\t\tcase 'M4VH':\n\t\t\tcase 'M4VP':\n\t\t\t\treturn {ext: 'm4v', mime: 'video/x-m4v'};\n\t\t\tcase 'M4P':\n\t\t\t\treturn {ext: 'm4p', mime: 'video/mp4'};\n\t\t\tcase 'M4B':\n\t\t\t\treturn {ext: 'm4b', mime: 'audio/mp4'};\n\t\t\tcase 'M4A':\n\t\t\t\treturn {ext: 'm4a', mime: 'audio/x-m4a'};\n\t\t\tcase 'F4V':\n\t\t\t\treturn {ext: 'f4v', mime: 'video/mp4'};\n\t\t\tcase 'F4P':\n\t\t\t\treturn {ext: 'f4p', mime: 'video/mp4'};\n\t\t\tcase 'F4A':\n\t\t\t\treturn {ext: 'f4a', mime: 'audio/mp4'};\n\t\t\tcase 'F4B':\n\t\t\t\treturn {ext: 'f4b', mime: 'audio/mp4'};\n\t\t\tcase 'crx':\n\t\t\t\treturn {ext: 'cr3', mime: 'image/x-canon-cr3'};\n\t\t\tdefault:\n\t\t\t\tif (brandMajor.startsWith('3g')) {\n\t\t\t\t\tif (brandMajor.startsWith('3g2')) {\n\t\t\t\t\t\treturn {ext: '3g2', mime: 'video/3gpp2'};\n\t\t\t\t\t}\n\n\t\t\t\t\treturn {ext: '3gp', mime: 'video/3gpp'};\n\t\t\t\t}\n\n\t\t\t\treturn {ext: 'mp4', mime: 'video/mp4'};\n\t\t}\n\t}\n\n\tif (checkString('MThd')) {\n\t\treturn {\n\t\t\text: 'mid',\n\t\t\tmime: 'audio/midi'\n\t\t};\n\t}\n\n\tif (\n\t\tcheckString('wOFF') &&\n\t\t(\n\t\t\tcheck([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||\n\t\t\tcheckString('OTTO', {offset: 4})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'woff',\n\t\t\tmime: 'font/woff'\n\t\t};\n\t}\n\n\tif (\n\t\tcheckString('wOF2') &&\n\t\t(\n\t\t\tcheck([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||\n\t\t\tcheckString('OTTO', {offset: 4})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'woff2',\n\t\t\tmime: 'font/woff2'\n\t\t};\n\t}\n\n\tif (check([0xD4, 0xC3, 0xB2, 0xA1]) || check([0xA1, 0xB2, 0xC3, 0xD4])) {\n\t\treturn {\n\t\t\text: 'pcap',\n\t\t\tmime: 'application/vnd.tcpdump.pcap'\n\t\t};\n\t}\n\n\t// Sony DSD Stream File (DSF)\n\tif (checkString('DSD ')) {\n\t\treturn {\n\t\t\text: 'dsf',\n\t\t\tmime: 'audio/x-dsf' // Non-standard\n\t\t};\n\t}\n\n\tif (checkString('LZIP')) {\n\t\treturn {\n\t\t\text: 'lz',\n\t\t\tmime: 'application/x-lzip'\n\t\t};\n\t}\n\n\tif (checkString('fLaC')) {\n\t\treturn {\n\t\t\text: 'flac',\n\t\t\tmime: 'audio/x-flac'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x50, 0x47, 0xFB])) {\n\t\treturn {\n\t\t\text: 'bpg',\n\t\t\tmime: 'image/bpg'\n\t\t};\n\t}\n\n\tif (checkString('wvpk')) {\n\t\treturn {\n\t\t\text: 'wv',\n\t\t\tmime: 'audio/wavpack'\n\t\t};\n\t}\n\n\tif (checkString('%PDF')) {\n\t\tawait tokenizer.ignore(1350);\n\t\tconst maxBufferSize = 10 * 1024 * 1024;\n\t\tconst buffer = Buffer.alloc(Math.min(maxBufferSize, tokenizer.fileInfo.size));\n\t\tawait tokenizer.readBuffer(buffer, {mayBeLess: true});\n\n\t\t// Check if this is an Adobe Illustrator file\n\t\tif (buffer.includes(Buffer.from('AIPrivateData'))) {\n\t\t\treturn {\n\t\t\t\text: 'ai',\n\t\t\t\tmime: 'application/postscript'\n\t\t\t};\n\t\t}\n\n\t\t// Assume this is just a normal PDF\n\t\treturn {\n\t\t\text: 'pdf',\n\t\t\tmime: 'application/pdf'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x61, 0x73, 0x6D])) {\n\t\treturn {\n\t\t\text: 'wasm',\n\t\t\tmime: 'application/wasm'\n\t\t};\n\t}\n\n\t// TIFF, little-endian type\n\tif (check([0x49, 0x49, 0x2A, 0x0])) {\n\t\tif (checkString('CR', {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'cr2',\n\t\t\t\tmime: 'image/x-canon-cr2'\n\t\t\t};\n\t\t}\n\n\t\tif (check([0x1C, 0x00, 0xFE, 0x00], {offset: 8}) || check([0x1F, 0x00, 0x0B, 0x00], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'nef',\n\t\t\t\tmime: 'image/x-nikon-nef'\n\t\t\t};\n\t\t}\n\n\t\tif (\n\t\t\tcheck([0x08, 0x00, 0x00, 0x00], {offset: 4}) &&\n\t\t\t(check([0x2D, 0x00, 0xFE, 0x00], {offset: 8}) ||\n\t\t\t\tcheck([0x27, 0x00, 0xFE, 0x00], {offset: 8}))\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'dng',\n\t\t\t\tmime: 'image/x-adobe-dng'\n\t\t\t};\n\t\t}\n\n\t\tbuffer = Buffer.alloc(24);\n\t\tawait tokenizer.peekBuffer(buffer);\n\t\tif (\n\t\t\t(check([0x10, 0xFB, 0x86, 0x01], {offset: 4}) || check([0x08, 0x00, 0x00, 0x00], {offset: 4})) &&\n\t\t\t// This pattern differentiates ARW from other TIFF-ish file types:\n\t\t\tcheck([0x00, 0xFE, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x01], {offset: 9})\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'arw',\n\t\t\t\tmime: 'image/x-sony-arw'\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\text: 'tif',\n\t\t\tmime: 'image/tiff'\n\t\t};\n\t}\n\n\t// TIFF, big-endian type\n\tif (check([0x4D, 0x4D, 0x0, 0x2A])) {\n\t\treturn {\n\t\t\text: 'tif',\n\t\t\tmime: 'image/tiff'\n\t\t};\n\t}\n\n\tif (checkString('MAC ')) {\n\t\treturn {\n\t\t\text: 'ape',\n\t\t\tmime: 'audio/ape'\n\t\t};\n\t}\n\n\t// https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska\n\tif (check([0x1A, 0x45, 0xDF, 0xA3])) { // Root element: EBML\n\t\tasync function readField() {\n\t\t\tconst msb = await tokenizer.peekNumber(Token.UINT8);\n\t\t\tlet mask = 0x80;\n\t\t\tlet ic = 0; // 0 = A, 1 = B, 2 = C, 3 = D\n\n\t\t\twhile ((msb & mask) === 0 && mask !== 0) {\n\t\t\t\t++ic;\n\t\t\t\tmask >>= 1;\n\t\t\t}\n\n\t\t\tconst id = Buffer.alloc(ic + 1);\n\t\t\tawait tokenizer.readBuffer(id);\n\t\t\treturn id;\n\t\t}\n\n\t\tasync function readElement() {\n\t\t\tconst id = await readField();\n\t\t\tconst lenField = await readField();\n\t\t\tlenField[0] ^= 0x80 >> (lenField.length - 1);\n\t\t\tconst nrLen = Math.min(6, lenField.length); // JavaScript can max read 6 bytes integer\n\t\t\treturn {\n\t\t\t\tid: id.readUIntBE(0, id.length),\n\t\t\t\tlen: lenField.readUIntBE(lenField.length - nrLen, nrLen)\n\t\t\t};\n\t\t}\n\n\t\tasync function readChildren(level, children) {\n\t\t\twhile (children > 0) {\n\t\t\t\tconst e = await readElement();\n\t\t\t\tif (e.id === 0x4282) {\n\t\t\t\t\treturn tokenizer.readToken(new Token.StringType(e.len, 'utf-8')); // Return DocType\n\t\t\t\t}\n\n\t\t\t\tawait tokenizer.ignore(e.len); // ignore payload\n\t\t\t\t--children;\n\t\t\t}\n\t\t}\n\n\t\tconst re = await readElement();\n\t\tconst docType = await readChildren(1, re.len);\n\n\t\tswitch (docType) {\n\t\t\tcase 'webm':\n\t\t\t\treturn {\n\t\t\t\t\text: 'webm',\n\t\t\t\t\tmime: 'video/webm'\n\t\t\t\t};\n\n\t\t\tcase 'matroska':\n\t\t\t\treturn {\n\t\t\t\t\text: 'mkv',\n\t\t\t\t\tmime: 'video/x-matroska'\n\t\t\t\t};\n\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\t// RIFF file format which might be AVI, WAV, QCP, etc\n\tif (check([0x52, 0x49, 0x46, 0x46])) {\n\t\tif (check([0x41, 0x56, 0x49], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'avi',\n\t\t\t\tmime: 'video/vnd.avi'\n\t\t\t};\n\t\t}\n\n\t\tif (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'wav',\n\t\t\t\tmime: 'audio/vnd.wave'\n\t\t\t};\n\t\t}\n\n\t\t// QLCM, QCP file\n\t\tif (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'qcp',\n\t\t\t\tmime: 'audio/qcelp'\n\t\t\t};\n\t\t}\n\t}\n\n\tif (checkString('SQLi')) {\n\t\treturn {\n\t\t\text: 'sqlite',\n\t\t\tmime: 'application/x-sqlite3'\n\t\t};\n\t}\n\n\tif (check([0x4E, 0x45, 0x53, 0x1A])) {\n\t\treturn {\n\t\t\text: 'nes',\n\t\t\tmime: 'application/x-nintendo-nes-rom'\n\t\t};\n\t}\n\n\tif (checkString('Cr24')) {\n\t\treturn {\n\t\t\text: 'crx',\n\t\t\tmime: 'application/x-google-chrome-extension'\n\t\t};\n\t}\n\n\tif (\n\t\tcheckString('MSCF') ||\n\t\tcheckString('ISc(')\n\t) {\n\t\treturn {\n\t\t\text: 'cab',\n\t\t\tmime: 'application/vnd.ms-cab-compressed'\n\t\t};\n\t}\n\n\tif (check([0xED, 0xAB, 0xEE, 0xDB])) {\n\t\treturn {\n\t\t\text: 'rpm',\n\t\t\tmime: 'application/x-rpm'\n\t\t};\n\t}\n\n\tif (check([0xC5, 0xD0, 0xD3, 0xC6])) {\n\t\treturn {\n\t\t\text: 'eps',\n\t\t\tmime: 'application/eps'\n\t\t};\n\t}\n\n\tif (check([0x28, 0xB5, 0x2F, 0xFD])) {\n\t\treturn {\n\t\t\text: 'zst',\n\t\t\tmime: 'application/zstd'\n\t\t};\n\t}\n\n\t// -- 5-byte signatures --\n\n\tif (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {\n\t\treturn {\n\t\t\text: 'otf',\n\t\t\tmime: 'font/otf'\n\t\t};\n\t}\n\n\tif (checkString('#!AMR')) {\n\t\treturn {\n\t\t\text: 'amr',\n\t\t\tmime: 'audio/amr'\n\t\t};\n\t}\n\n\tif (checkString('{\\\\rtf')) {\n\t\treturn {\n\t\t\text: 'rtf',\n\t\t\tmime: 'application/rtf'\n\t\t};\n\t}\n\n\tif (check([0x46, 0x4C, 0x56, 0x01])) {\n\t\treturn {\n\t\t\text: 'flv',\n\t\t\tmime: 'video/x-flv'\n\t\t};\n\t}\n\n\tif (checkString('IMPM')) {\n\t\treturn {\n\t\t\text: 'it',\n\t\t\tmime: 'audio/x-it'\n\t\t};\n\t}\n\n\tif (\n\t\tcheckString('-lh0-', {offset: 2}) ||\n\t\tcheckString('-lh1-', {offset: 2}) ||\n\t\tcheckString('-lh2-', {offset: 2}) ||\n\t\tcheckString('-lh3-', {offset: 2}) ||\n\t\tcheckString('-lh4-', {offset: 2}) ||\n\t\tcheckString('-lh5-', {offset: 2}) ||\n\t\tcheckString('-lh6-', {offset: 2}) ||\n\t\tcheckString('-lh7-', {offset: 2}) ||\n\t\tcheckString('-lzs-', {offset: 2}) ||\n\t\tcheckString('-lz4-', {offset: 2}) ||\n\t\tcheckString('-lz5-', {offset: 2}) ||\n\t\tcheckString('-lhd-', {offset: 2})\n\t) {\n\t\treturn {\n\t\t\text: 'lzh',\n\t\t\tmime: 'application/x-lzh-compressed'\n\t\t};\n\t}\n\n\t// MPEG program stream (PS or MPEG-PS)\n\tif (check([0x00, 0x00, 0x01, 0xBA])) {\n\t\t// MPEG-PS, MPEG-1 Part 1\n\t\tif (check([0x21], {offset: 4, mask: [0xF1]})) {\n\t\t\treturn {\n\t\t\t\text: 'mpg', // May also be .ps, .mpeg\n\t\t\t\tmime: 'video/MP1S'\n\t\t\t};\n\t\t}\n\n\t\t// MPEG-PS, MPEG-2 Part 1\n\t\tif (check([0x44], {offset: 4, mask: [0xC4]})) {\n\t\t\treturn {\n\t\t\t\text: 'mpg', // May also be .mpg, .m2p, .vob or .sub\n\t\t\t\tmime: 'video/MP2P'\n\t\t\t};\n\t\t}\n\t}\n\n\tif (checkString('ITSF')) {\n\t\treturn {\n\t\t\text: 'chm',\n\t\t\tmime: 'application/vnd.ms-htmlhelp'\n\t\t};\n\t}\n\n\t// -- 6-byte signatures --\n\n\tif (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {\n\t\treturn {\n\t\t\text: 'xz',\n\t\t\tmime: 'application/x-xz'\n\t\t};\n\t}\n\n\tif (checkString('')) {\n\t\tawait tokenizer.ignore(8);\n\t\tconst str = await tokenizer.readToken(new Token.StringType(13, 'ascii'));\n\t\tif (str === 'debian-binary') {\n\t\t\treturn {\n\t\t\t\text: 'deb',\n\t\t\t\tmime: 'application/x-deb'\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\text: 'ar',\n\t\t\tmime: 'application/x-unix-archive'\n\t\t};\n\t}\n\n\t// -- 8-byte signatures --\n\n\tif (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {\n\t\t// APNG format (https://wiki.mozilla.org/APNG_Specification)\n\t\t// 1. Find the first IDAT (image data) chunk (49 44 41 54)\n\t\t// 2. Check if there is an \"acTL\" chunk before the IDAT one (61 63 54 4C)\n\n\t\t// Offset calculated as follows:\n\t\t// - 8 bytes: PNG signature\n\t\t// - 4 (length) + 4 (chunk type) + 13 (chunk data) + 4 (CRC): IHDR chunk\n\n\t\tawait tokenizer.ignore(8); // ignore PNG signature\n\n\t\tasync function readChunkHeader() {\n\t\t\treturn {\n\t\t\t\tlength: await tokenizer.readToken(Token.INT32_BE),\n\t\t\t\ttype: await tokenizer.readToken(new Token.StringType(4, 'binary'))\n\t\t\t};\n\t\t}\n\n\t\tdo {\n\t\t\tconst chunk = await readChunkHeader();\n\t\t\tif (chunk.length < 0) {\n\t\t\t\treturn; // Invalid chunk length\n\t\t\t}\n\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase 'IDAT':\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'png',\n\t\t\t\t\t\tmime: 'image/png'\n\t\t\t\t\t};\n\t\t\t\tcase 'acTL':\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'apng',\n\t\t\t\t\t\tmime: 'image/apng'\n\t\t\t\t\t};\n\t\t\t\tdefault:\n\t\t\t\t\tawait tokenizer.ignore(chunk.length + 4); // Ignore chunk-data + CRC\n\t\t\t}\n\t\t} while (tokenizer.position + 8 < tokenizer.fileInfo.size);\n\n\t\treturn {\n\t\t\text: 'png',\n\t\t\tmime: 'image/png'\n\t\t};\n\t}\n\n\tif (check([0x41, 0x52, 0x52, 0x4F, 0x57, 0x31, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'arrow',\n\t\t\tmime: 'application/x-apache-arrow'\n\t\t};\n\t}\n\n\tif (check([0x67, 0x6C, 0x54, 0x46, 0x02, 0x00, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'glb',\n\t\t\tmime: 'model/gltf-binary'\n\t\t};\n\t}\n\n\t// `mov` format variants\n\tif (\n\t\tcheck([0x66, 0x72, 0x65, 0x65], {offset: 4}) || // `free`\n\t\tcheck([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // `mdat` MJPEG\n\t\tcheck([0x6D, 0x6F, 0x6F, 0x76], {offset: 4}) || // `moov`\n\t\tcheck([0x77, 0x69, 0x64, 0x65], {offset: 4}) // `wide`\n\t) {\n\t\treturn {\n\t\t\text: 'mov',\n\t\t\tmime: 'video/quicktime'\n\t\t};\n\t}\n\n\t// -- 9-byte signatures --\n\n\tif (check([0x49, 0x49, 0x52, 0x4F, 0x08, 0x00, 0x00, 0x00, 0x18])) {\n\t\treturn {\n\t\t\text: 'orf',\n\t\t\tmime: 'image/x-olympus-orf'\n\t\t};\n\t}\n\n\tif (checkString('gimp xcf ')) {\n\t\treturn {\n\t\t\text: 'xcf',\n\t\t\tmime: 'image/x-xcf'\n\t\t};\n\t}\n\n\t// -- 12-byte signatures --\n\n\tif (check([0x49, 0x49, 0x55, 0x00, 0x18, 0x00, 0x00, 0x00, 0x88, 0xE7, 0x74, 0xD8])) {\n\t\treturn {\n\t\t\text: 'rw2',\n\t\t\tmime: 'image/x-panasonic-rw2'\n\t\t};\n\t}\n\n\t// ASF_Header_Object first 80 bytes\n\tif (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {\n\t\tasync function readHeader() {\n\t\t\tconst guid = Buffer.alloc(16);\n\t\t\tawait tokenizer.readBuffer(guid);\n\t\t\treturn {\n\t\t\t\tid: guid,\n\t\t\t\tsize: Number(await tokenizer.readToken(Token.UINT64_LE))\n\t\t\t};\n\t\t}\n\n\t\tawait tokenizer.ignore(30);\n\t\t// Search for header should be in first 1KB of file.\n\t\twhile (tokenizer.position + 24 < tokenizer.fileInfo.size) {\n\t\t\tconst header = await readHeader();\n\t\t\tlet payload = header.size - 24;\n\t\t\tif (_check(header.id, [0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65])) {\n\t\t\t\t// Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365)\n\t\t\t\tconst typeId = Buffer.alloc(16);\n\t\t\t\tpayload -= await tokenizer.readBuffer(typeId);\n\n\t\t\t\tif (_check(typeId, [0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {\n\t\t\t\t\t// Found audio:\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'asf',\n\t\t\t\t\t\tmime: 'audio/x-ms-asf'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (_check(typeId, [0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {\n\t\t\t\t\t// Found video:\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'asf',\n\t\t\t\t\t\tmime: 'video/x-ms-asf'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tawait tokenizer.ignore(payload);\n\t\t}\n\n\t\t// Default to ASF generic extension\n\t\treturn {\n\t\t\text: 'asf',\n\t\t\tmime: 'application/vnd.ms-asf'\n\t\t};\n\t}\n\n\tif (check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {\n\t\treturn {\n\t\t\text: 'ktx',\n\t\t\tmime: 'image/ktx'\n\t\t};\n\t}\n\n\tif ((check([0x7E, 0x10, 0x04]) || check([0x7E, 0x18, 0x04])) && check([0x30, 0x4D, 0x49, 0x45], {offset: 4})) {\n\t\treturn {\n\t\t\text: 'mie',\n\t\t\tmime: 'application/x-mie'\n\t\t};\n\t}\n\n\tif (check([0x27, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], {offset: 2})) {\n\t\treturn {\n\t\t\text: 'shp',\n\t\t\tmime: 'application/x-esri-shape'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {\n\t\t// JPEG-2000 family\n\n\t\tawait tokenizer.ignore(20);\n\t\tconst type = await tokenizer.readToken(new Token.StringType(4, 'ascii'));\n\t\tswitch (type) {\n\t\t\tcase 'jp2 ':\n\t\t\t\treturn {\n\t\t\t\t\text: 'jp2',\n\t\t\t\t\tmime: 'image/jp2'\n\t\t\t\t};\n\t\t\tcase 'jpx ':\n\t\t\t\treturn {\n\t\t\t\t\text: 'jpx',\n\t\t\t\t\tmime: 'image/jpx'\n\t\t\t\t};\n\t\t\tcase 'jpm ':\n\t\t\t\treturn {\n\t\t\t\t\text: 'jpm',\n\t\t\t\t\tmime: 'image/jpm'\n\t\t\t\t};\n\t\t\tcase 'mjp2':\n\t\t\t\treturn {\n\t\t\t\t\text: 'mj2',\n\t\t\t\t\tmime: 'image/mj2'\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\tif (\n\t\tcheck([0xFF, 0x0A]) ||\n\t\tcheck([0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x4C, 0x20, 0x0D, 0x0A, 0x87, 0x0A])\n\t) {\n\t\treturn {\n\t\t\text: 'jxl',\n\t\t\tmime: 'image/jxl'\n\t\t};\n\t}\n\n\t// -- Unsafe signatures --\n\n\tif (\n\t\tcheck([0x0, 0x0, 0x1, 0xBA]) ||\n\t\tcheck([0x0, 0x0, 0x1, 0xB3])\n\t) {\n\t\treturn {\n\t\t\text: 'mpg',\n\t\t\tmime: 'video/mpeg'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x01, 0x00, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'ttf',\n\t\t\tmime: 'font/ttf'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x01, 0x00])) {\n\t\treturn {\n\t\t\text: 'ico',\n\t\t\tmime: 'image/x-icon'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x02, 0x00])) {\n\t\treturn {\n\t\t\text: 'cur',\n\t\t\tmime: 'image/x-icon'\n\t\t};\n\t}\n\n\tif (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {\n\t\t// Detected Microsoft Compound File Binary File (MS-CFB) Format.\n\t\treturn {\n\t\t\text: 'cfb',\n\t\t\tmime: 'application/x-cfb'\n\t\t};\n\t}\n\n\t// Increase sample size from 12 to 256.\n\tawait tokenizer.peekBuffer(buffer, {length: Math.min(256, tokenizer.fileInfo.size), mayBeLess: true});\n\n\t// -- 15-byte signatures --\n\n\tif (checkString('BEGIN:')) {\n\t\tif (checkString('VCARD', {offset: 6})) {\n\t\t\treturn {\n\t\t\t\text: 'vcf',\n\t\t\t\tmime: 'text/vcard'\n\t\t\t};\n\t\t}\n\n\t\tif (checkString('VCALENDAR', {offset: 6})) {\n\t\t\treturn {\n\t\t\t\text: 'ics',\n\t\t\t\tmime: 'text/calendar'\n\t\t\t};\n\t\t}\n\t}\n\n\t// `raf` is here just to keep all the raw image detectors together.\n\tif (checkString('FUJIFILMCCD-RAW')) {\n\t\treturn {\n\t\t\text: 'raf',\n\t\t\tmime: 'image/x-fujifilm-raf'\n\t\t};\n\t}\n\n\tif (checkString('Extended Module:')) {\n\t\treturn {\n\t\t\text: 'xm',\n\t\t\tmime: 'audio/x-xm'\n\t\t};\n\t}\n\n\tif (checkString('Creative Voice File')) {\n\t\treturn {\n\t\t\text: 'voc',\n\t\t\tmime: 'audio/x-voc'\n\t\t};\n\t}\n\n\tif (check([0x04, 0x00, 0x00, 0x00]) && buffer.length >= 16) { // Rough & quick check Pickle/ASAR\n\t\tconst jsonSize = buffer.readUInt32LE(12);\n\t\tif (jsonSize > 12 && buffer.length >= jsonSize + 16) {\n\t\t\ttry {\n\t\t\t\tconst header = buffer.slice(16, jsonSize + 16).toString();\n\t\t\t\tconst json = JSON.parse(header);\n\t\t\t\t// Check if Pickle is ASAR\n\t\t\t\tif (json.files) { // Final check, assuring Pickle/ASAR format\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'asar',\n\t\t\t\t\t\tmime: 'application/x-asar'\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch (_) {\n\t\t\t}\n\t\t}\n\t}\n\n\tif (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {\n\t\treturn {\n\t\t\text: 'mxf',\n\t\t\tmime: 'application/mxf'\n\t\t};\n\t}\n\n\tif (checkString('SCRM', {offset: 44})) {\n\t\treturn {\n\t\t\text: 's3m',\n\t\t\tmime: 'audio/x-s3m'\n\t\t};\n\t}\n\n\tif (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) {\n\t\treturn {\n\t\t\text: 'mts',\n\t\t\tmime: 'video/mp2t'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) {\n\t\treturn {\n\t\t\text: 'mobi',\n\t\t\tmime: 'application/x-mobipocket-ebook'\n\t\t};\n\t}\n\n\tif (check([0x44, 0x49, 0x43, 0x4D], {offset: 128})) {\n\t\treturn {\n\t\t\text: 'dcm',\n\t\t\tmime: 'application/dicom'\n\t\t};\n\t}\n\n\tif (check([0x4C, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46])) {\n\t\treturn {\n\t\t\text: 'lnk',\n\t\t\tmime: 'application/x.ms.shortcut' // Invented by us\n\t\t};\n\t}\n\n\tif (check([0x62, 0x6F, 0x6F, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x72, 0x6B, 0x00, 0x00, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'alias',\n\t\t\tmime: 'application/x.apple.alias' // Invented by us\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x4C, 0x50], {offset: 34}) &&\n\t\t(\n\t\t\tcheck([0x00, 0x00, 0x01], {offset: 8}) ||\n\t\t\tcheck([0x01, 0x00, 0x02], {offset: 8}) ||\n\t\t\tcheck([0x02, 0x00, 0x02], {offset: 8})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'eot',\n\t\t\tmime: 'application/vnd.ms-fontobject'\n\t\t};\n\t}\n\n\tif (check([0x06, 0x06, 0xED, 0xF5, 0xD8, 0x1D, 0x46, 0xE5, 0xBD, 0x31, 0xEF, 0xE7, 0xFE, 0x74, 0xB7, 0x1D])) {\n\t\treturn {\n\t\t\text: 'indd',\n\t\t\tmime: 'application/x-indesign'\n\t\t};\n\t}\n\n\t// Increase sample size from 256 to 512\n\tawait tokenizer.peekBuffer(buffer, {length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true});\n\n\t// Requires a buffer size of 512 bytes\n\tif (tarHeaderChecksumMatches(buffer)) {\n\t\treturn {\n\t\t\text: 'tar',\n\t\t\tmime: 'application/x-tar'\n\t\t};\n\t}\n\n\tif (check([0xFF, 0xFE, 0xFF, 0x0E, 0x53, 0x00, 0x6B, 0x00, 0x65, 0x00, 0x74, 0x00, 0x63, 0x00, 0x68, 0x00, 0x55, 0x00, 0x70, 0x00, 0x20, 0x00, 0x4D, 0x00, 0x6F, 0x00, 0x64, 0x00, 0x65, 0x00, 0x6C, 0x00])) {\n\t\treturn {\n\t\t\text: 'skp',\n\t\t\tmime: 'application/vnd.sketchup.skp'\n\t\t};\n\t}\n\n\tif (checkString('-----BEGIN PGP MESSAGE-----')) {\n\t\treturn {\n\t\t\text: 'pgp',\n\t\t\tmime: 'application/pgp-encrypted'\n\t\t};\n\t}\n\n\t// Check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE)\n\tif (buffer.length >= 2 && check([0xFF, 0xE0], {offset: 0, mask: [0xFF, 0xE0]})) {\n\t\tif (check([0x10], {offset: 1, mask: [0x16]})) {\n\t\t\t// Check for (ADTS) MPEG-2\n\t\t\tif (check([0x08], {offset: 1, mask: [0x08]})) {\n\t\t\t\treturn {\n\t\t\t\t\text: 'aac',\n\t\t\t\t\tmime: 'audio/aac'\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Must be (ADTS) MPEG-4\n\t\t\treturn {\n\t\t\t\text: 'aac',\n\t\t\t\tmime: 'audio/aac'\n\t\t\t};\n\t\t}\n\n\t\t// MPEG 1 or 2 Layer 3 header\n\t\t// Check for MPEG layer 3\n\t\tif (check([0x02], {offset: 1, mask: [0x06]})) {\n\t\t\treturn {\n\t\t\t\text: 'mp3',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\t// Check for MPEG layer 2\n\t\tif (check([0x04], {offset: 1, mask: [0x06]})) {\n\t\t\treturn {\n\t\t\t\text: 'mp2',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\t// Check for MPEG layer 1\n\t\tif (check([0x06], {offset: 1, mask: [0x06]})) {\n\t\t\treturn {\n\t\t\t\text: 'mp1',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\t}\n}\n\nconst stream = readableStream => new Promise((resolve, reject) => {\n\t// Using `eval` to work around issues when bundling with Webpack\n\tconst stream = eval('require')('stream'); // eslint-disable-line no-eval\n\n\treadableStream.on('error', reject);\n\treadableStream.once('readable', async () => {\n\t\t// Set up output stream\n\t\tconst pass = new stream.PassThrough();\n\t\tlet outputStream;\n\t\tif (stream.pipeline) {\n\t\t\toutputStream = stream.pipeline(readableStream, pass, () => {\n\t\t\t});\n\t\t} else {\n\t\t\toutputStream = readableStream.pipe(pass);\n\t\t}\n\n\t\t// Read the input stream and detect the filetype\n\t\tconst chunk = readableStream.read(minimumBytes) || readableStream.read() || Buffer.alloc(0);\n\t\ttry {\n\t\t\tconst fileType = await fromBuffer(chunk);\n\t\t\tpass.fileType = fileType;\n\t\t} catch (error) {\n\t\t\treject(error);\n\t\t}\n\n\t\tresolve(outputStream);\n\t});\n});\n\nconst fileType = {\n\tfromStream,\n\tfromTokenizer,\n\tfromBuffer,\n\tstream\n};\n\nObject.defineProperty(fileType, 'extensions', {\n\tget() {\n\t\treturn new Set(supported.extensions);\n\t}\n});\n\nObject.defineProperty(fileType, 'mimeTypes', {\n\tget() {\n\t\treturn new Set(supported.mimeTypes);\n\t}\n});\n\nmodule.exports = fileType;\n","'use strict';\nconst strtok3 = require('strtok3');\nconst core = require('./core');\n\nasync function fromFile(path) {\n\tconst tokenizer = await strtok3.fromFile(path);\n\ttry {\n\t\treturn await core.fromTokenizer(tokenizer);\n\t} finally {\n\t\tawait tokenizer.close();\n\t}\n}\n\nconst fileType = {\n\tfromFile\n};\n\nObject.assign(fileType, core);\n\nObject.defineProperty(fileType, 'extensions', {\n\tget() {\n\t\treturn core.extensions;\n\t}\n});\n\nObject.defineProperty(fileType, 'mimeTypes', {\n\tget() {\n\t\treturn core.mimeTypes;\n\t}\n});\n\nmodule.exports = fileType;\n","'use strict';\n\nmodule.exports = {\n\textensions: [\n\t\t'jpg',\n\t\t'png',\n\t\t'apng',\n\t\t'gif',\n\t\t'webp',\n\t\t'flif',\n\t\t'xcf',\n\t\t'cr2',\n\t\t'cr3',\n\t\t'orf',\n\t\t'arw',\n\t\t'dng',\n\t\t'nef',\n\t\t'rw2',\n\t\t'raf',\n\t\t'tif',\n\t\t'bmp',\n\t\t'icns',\n\t\t'jxr',\n\t\t'psd',\n\t\t'indd',\n\t\t'zip',\n\t\t'tar',\n\t\t'rar',\n\t\t'gz',\n\t\t'bz2',\n\t\t'7z',\n\t\t'dmg',\n\t\t'mp4',\n\t\t'mid',\n\t\t'mkv',\n\t\t'webm',\n\t\t'mov',\n\t\t'avi',\n\t\t'mpg',\n\t\t'mp2',\n\t\t'mp3',\n\t\t'm4a',\n\t\t'oga',\n\t\t'ogg',\n\t\t'ogv',\n\t\t'opus',\n\t\t'flac',\n\t\t'wav',\n\t\t'spx',\n\t\t'amr',\n\t\t'pdf',\n\t\t'epub',\n\t\t'exe',\n\t\t'swf',\n\t\t'rtf',\n\t\t'wasm',\n\t\t'woff',\n\t\t'woff2',\n\t\t'eot',\n\t\t'ttf',\n\t\t'otf',\n\t\t'ico',\n\t\t'flv',\n\t\t'ps',\n\t\t'xz',\n\t\t'sqlite',\n\t\t'nes',\n\t\t'crx',\n\t\t'xpi',\n\t\t'cab',\n\t\t'deb',\n\t\t'ar',\n\t\t'rpm',\n\t\t'Z',\n\t\t'lz',\n\t\t'cfb',\n\t\t'mxf',\n\t\t'mts',\n\t\t'blend',\n\t\t'bpg',\n\t\t'docx',\n\t\t'pptx',\n\t\t'xlsx',\n\t\t'3gp',\n\t\t'3g2',\n\t\t'jp2',\n\t\t'jpm',\n\t\t'jpx',\n\t\t'mj2',\n\t\t'aif',\n\t\t'qcp',\n\t\t'odt',\n\t\t'ods',\n\t\t'odp',\n\t\t'xml',\n\t\t'mobi',\n\t\t'heic',\n\t\t'cur',\n\t\t'ktx',\n\t\t'ape',\n\t\t'wv',\n\t\t'dcm',\n\t\t'ics',\n\t\t'glb',\n\t\t'pcap',\n\t\t'dsf',\n\t\t'lnk',\n\t\t'alias',\n\t\t'voc',\n\t\t'ac3',\n\t\t'm4v',\n\t\t'm4p',\n\t\t'm4b',\n\t\t'f4v',\n\t\t'f4p',\n\t\t'f4b',\n\t\t'f4a',\n\t\t'mie',\n\t\t'asf',\n\t\t'ogm',\n\t\t'ogx',\n\t\t'mpc',\n\t\t'arrow',\n\t\t'shp',\n\t\t'aac',\n\t\t'mp1',\n\t\t'it',\n\t\t's3m',\n\t\t'xm',\n\t\t'ai',\n\t\t'skp',\n\t\t'avif',\n\t\t'eps',\n\t\t'lzh',\n\t\t'pgp',\n\t\t'asar',\n\t\t'stl',\n\t\t'chm',\n\t\t'3mf',\n\t\t'zst',\n\t\t'jxl',\n\t\t'vcf'\n\t],\n\tmimeTypes: [\n\t\t'image/jpeg',\n\t\t'image/png',\n\t\t'image/gif',\n\t\t'image/webp',\n\t\t'image/flif',\n\t\t'image/x-xcf',\n\t\t'image/x-canon-cr2',\n\t\t'image/x-canon-cr3',\n\t\t'image/tiff',\n\t\t'image/bmp',\n\t\t'image/vnd.ms-photo',\n\t\t'image/vnd.adobe.photoshop',\n\t\t'application/x-indesign',\n\t\t'application/epub+zip',\n\t\t'application/x-xpinstall',\n\t\t'application/vnd.oasis.opendocument.text',\n\t\t'application/vnd.oasis.opendocument.spreadsheet',\n\t\t'application/vnd.oasis.opendocument.presentation',\n\t\t'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n\t\t'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n\t\t'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n\t\t'application/zip',\n\t\t'application/x-tar',\n\t\t'application/x-rar-compressed',\n\t\t'application/gzip',\n\t\t'application/x-bzip2',\n\t\t'application/x-7z-compressed',\n\t\t'application/x-apple-diskimage',\n\t\t'application/x-apache-arrow',\n\t\t'video/mp4',\n\t\t'audio/midi',\n\t\t'video/x-matroska',\n\t\t'video/webm',\n\t\t'video/quicktime',\n\t\t'video/vnd.avi',\n\t\t'audio/vnd.wave',\n\t\t'audio/qcelp',\n\t\t'audio/x-ms-asf',\n\t\t'video/x-ms-asf',\n\t\t'application/vnd.ms-asf',\n\t\t'video/mpeg',\n\t\t'video/3gpp',\n\t\t'audio/mpeg',\n\t\t'audio/mp4', // RFC 4337\n\t\t'audio/opus',\n\t\t'video/ogg',\n\t\t'audio/ogg',\n\t\t'application/ogg',\n\t\t'audio/x-flac',\n\t\t'audio/ape',\n\t\t'audio/wavpack',\n\t\t'audio/amr',\n\t\t'application/pdf',\n\t\t'application/x-msdownload',\n\t\t'application/x-shockwave-flash',\n\t\t'application/rtf',\n\t\t'application/wasm',\n\t\t'font/woff',\n\t\t'font/woff2',\n\t\t'application/vnd.ms-fontobject',\n\t\t'font/ttf',\n\t\t'font/otf',\n\t\t'image/x-icon',\n\t\t'video/x-flv',\n\t\t'application/postscript',\n\t\t'application/eps',\n\t\t'application/x-xz',\n\t\t'application/x-sqlite3',\n\t\t'application/x-nintendo-nes-rom',\n\t\t'application/x-google-chrome-extension',\n\t\t'application/vnd.ms-cab-compressed',\n\t\t'application/x-deb',\n\t\t'application/x-unix-archive',\n\t\t'application/x-rpm',\n\t\t'application/x-compress',\n\t\t'application/x-lzip',\n\t\t'application/x-cfb',\n\t\t'application/x-mie',\n\t\t'application/mxf',\n\t\t'video/mp2t',\n\t\t'application/x-blender',\n\t\t'image/bpg',\n\t\t'image/jp2',\n\t\t'image/jpx',\n\t\t'image/jpm',\n\t\t'image/mj2',\n\t\t'audio/aiff',\n\t\t'application/xml',\n\t\t'application/x-mobipocket-ebook',\n\t\t'image/heif',\n\t\t'image/heif-sequence',\n\t\t'image/heic',\n\t\t'image/heic-sequence',\n\t\t'image/icns',\n\t\t'image/ktx',\n\t\t'application/dicom',\n\t\t'audio/x-musepack',\n\t\t'text/calendar',\n\t\t'text/vcard',\n\t\t'model/gltf-binary',\n\t\t'application/vnd.tcpdump.pcap',\n\t\t'audio/x-dsf', // Non-standard\n\t\t'application/x.ms.shortcut', // Invented by us\n\t\t'application/x.apple.alias', // Invented by us\n\t\t'audio/x-voc',\n\t\t'audio/vnd.dolby.dd-raw',\n\t\t'audio/x-m4a',\n\t\t'image/apng',\n\t\t'image/x-olympus-orf',\n\t\t'image/x-sony-arw',\n\t\t'image/x-adobe-dng',\n\t\t'image/x-nikon-nef',\n\t\t'image/x-panasonic-rw2',\n\t\t'image/x-fujifilm-raf',\n\t\t'video/x-m4v',\n\t\t'video/3gpp2',\n\t\t'application/x-esri-shape',\n\t\t'audio/aac',\n\t\t'audio/x-it',\n\t\t'audio/x-s3m',\n\t\t'audio/x-xm',\n\t\t'video/MP1S',\n\t\t'video/MP2P',\n\t\t'application/vnd.sketchup.skp',\n\t\t'image/avif',\n\t\t'application/x-lzh-compressed',\n\t\t'application/pgp-encrypted',\n\t\t'application/x-asar',\n\t\t'model/stl',\n\t\t'application/vnd.ms-htmlhelp',\n\t\t'model/3mf',\n\t\t'image/jxl',\n\t\t'application/zstd'\n\t]\n};\n","'use strict';\n\nexports.stringToBytes = string => [...string].map(character => character.charCodeAt(0));\n\n/**\nChecks whether the TAR checksum is valid.\n\n@param {Buffer} buffer - The TAR header `[offset ... offset + 512]`.\n@param {number} offset - TAR header offset.\n@returns {boolean} `true` if the TAR checksum is valid, otherwise `false`.\n*/\nexports.tarHeaderChecksumMatches = (buffer, offset = 0) => {\n\tconst readSum = parseInt(buffer.toString('utf8', 148, 154).replace(/\\0.*$/, '').trim(), 8); // Read sum in header\n\tif (isNaN(readSum)) {\n\t\treturn false;\n\t}\n\n\tlet sum = 8 * 0x20; // Initialize signed bit sum\n\n\tfor (let i = offset; i < offset + 148; i++) {\n\t\tsum += buffer[i];\n\t}\n\n\tfor (let i = offset + 156; i < offset + 512; i++) {\n\t\tsum += buffer[i];\n\t}\n\n\treturn readSum === sum;\n};\n\n/**\nID3 UINT32 sync-safe tokenizer token.\n28 bits (representing up to 256MB) integer, the msb is 0 to avoid \"false syncsignals\".\n*/\nexports.uint32SyncSafeToken = {\n\tget: (buffer, offset) => {\n\t\treturn (buffer[offset + 3] & 0x7F) | ((buffer[offset + 2]) << 7) | ((buffer[offset + 1]) << 14) | ((buffer[offset]) << 21);\n\t},\n\tlen: 4\n};\n","'use strict';\n\nvar isCallable = require('is-callable');\n\nvar toStr = Object.prototype.toString;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar forEachArray = function forEachArray(array, iterator, receiver) {\n for (var i = 0, len = array.length; i < len; i++) {\n if (hasOwnProperty.call(array, i)) {\n if (receiver == null) {\n iterator(array[i], i, array);\n } else {\n iterator.call(receiver, array[i], i, array);\n }\n }\n }\n};\n\nvar forEachString = function forEachString(string, iterator, receiver) {\n for (var i = 0, len = string.length; i < len; i++) {\n // no such thing as a sparse string.\n if (receiver == null) {\n iterator(string.charAt(i), i, string);\n } else {\n iterator.call(receiver, string.charAt(i), i, string);\n }\n }\n};\n\nvar forEachObject = function forEachObject(object, iterator, receiver) {\n for (var k in object) {\n if (hasOwnProperty.call(object, k)) {\n if (receiver == null) {\n iterator(object[k], k, object);\n } else {\n iterator.call(receiver, object[k], k, object);\n }\n }\n }\n};\n\nvar forEach = function forEach(list, iterator, thisArg) {\n if (!isCallable(iterator)) {\n throw new TypeError('iterator must be a function');\n }\n\n var receiver;\n if (arguments.length >= 3) {\n receiver = thisArg;\n }\n\n if (toStr.call(list) === '[object Array]') {\n forEachArray(list, iterator, receiver);\n } else if (typeof list === 'string') {\n forEachString(list, iterator, receiver);\n } else {\n forEachObject(list, iterator, receiver);\n }\n};\n\nmodule.exports = forEach;\n","// (c) Dean McNamee , 2013.\n//\n// https://github.com/deanm/omggif\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n//\n// omggif is a JavaScript implementation of a GIF 89a encoder and decoder,\n// including animation and compression. It does not rely on any specific\n// underlying system, so should run in the browser, Node, or Plask.\n\n\"use strict\";\n\nfunction GifWriter(buf, width, height, gopts) {\n var p = 0;\n\n var gopts = gopts === undefined ? { } : gopts;\n var loop_count = gopts.loop === undefined ? null : gopts.loop;\n var global_palette = gopts.palette === undefined ? null : gopts.palette;\n\n if (width <= 0 || height <= 0 || width > 65535 || height > 65535)\n throw new Error(\"Width/Height invalid.\");\n\n function check_palette_and_num_colors(palette) {\n var num_colors = palette.length;\n if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) {\n throw new Error(\n \"Invalid code/color length, must be power of 2 and 2 .. 256.\");\n }\n return num_colors;\n }\n\n // - Header.\n buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF\n buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a\n\n // Handling of Global Color Table (palette) and background index.\n var gp_num_colors_pow2 = 0;\n var background = 0;\n if (global_palette !== null) {\n var gp_num_colors = check_palette_and_num_colors(global_palette);\n while (gp_num_colors >>= 1) ++gp_num_colors_pow2;\n gp_num_colors = 1 << gp_num_colors_pow2;\n --gp_num_colors_pow2;\n if (gopts.background !== undefined) {\n background = gopts.background;\n if (background >= gp_num_colors)\n throw new Error(\"Background index out of range.\");\n // The GIF spec states that a background index of 0 should be ignored, so\n // this is probably a mistake and you really want to set it to another\n // slot in the palette. But actually in the end most browsers, etc end\n // up ignoring this almost completely (including for dispose background).\n if (background === 0)\n throw new Error(\"Background index explicitly passed as 0.\");\n }\n }\n\n // - Logical Screen Descriptor.\n // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.\n buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff;\n buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff;\n // NOTE: Indicates 0-bpp original color resolution (unused?).\n buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.\n gp_num_colors_pow2; // NOTE: No sort flag (unused?).\n buf[p++] = background; // Background Color Index.\n buf[p++] = 0; // Pixel aspect ratio (unused?).\n\n // - Global Color Table\n if (global_palette !== null) {\n for (var i = 0, il = global_palette.length; i < il; ++i) {\n var rgb = global_palette[i];\n buf[p++] = rgb >> 16 & 0xff;\n buf[p++] = rgb >> 8 & 0xff;\n buf[p++] = rgb & 0xff;\n }\n }\n\n if (loop_count !== null) { // Netscape block for looping.\n if (loop_count < 0 || loop_count > 65535)\n throw new Error(\"Loop count invalid.\")\n // Extension code, label, and length.\n buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b;\n // NETSCAPE2.0\n buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53;\n buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45;\n buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30;\n // Sub-block\n buf[p++] = 0x03; buf[p++] = 0x01;\n buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff;\n buf[p++] = 0x00; // Terminator.\n }\n\n\n var ended = false;\n\n this.addFrame = function(x, y, w, h, indexed_pixels, opts) {\n if (ended === true) { --p; ended = false; } // Un-end.\n\n opts = opts === undefined ? { } : opts;\n\n // TODO(deanm): Bounds check x, y. Do they need to be within the virtual\n // canvas width/height, I imagine?\n if (x < 0 || y < 0 || x > 65535 || y > 65535)\n throw new Error(\"x/y invalid.\")\n\n if (w <= 0 || h <= 0 || w > 65535 || h > 65535)\n throw new Error(\"Width/Height invalid.\")\n\n if (indexed_pixels.length < w * h)\n throw new Error(\"Not enough pixels for the frame size.\");\n\n var using_local_palette = true;\n var palette = opts.palette;\n if (palette === undefined || palette === null) {\n using_local_palette = false;\n palette = global_palette;\n }\n\n if (palette === undefined || palette === null)\n throw new Error(\"Must supply either a local or global palette.\");\n\n var num_colors = check_palette_and_num_colors(palette);\n\n // Compute the min_code_size (power of 2), destroying num_colors.\n var min_code_size = 0;\n while (num_colors >>= 1) ++min_code_size;\n num_colors = 1 << min_code_size; // Now we can easily get it back.\n\n var delay = opts.delay === undefined ? 0 : opts.delay;\n\n // From the spec:\n // 0 - No disposal specified. The decoder is\n // not required to take any action.\n // 1 - Do not dispose. The graphic is to be left\n // in place.\n // 2 - Restore to background color. The area used by the\n // graphic must be restored to the background color.\n // 3 - Restore to previous. The decoder is required to\n // restore the area overwritten by the graphic with\n // what was there prior to rendering the graphic.\n // 4-7 - To be defined.\n // NOTE(deanm): Dispose background doesn't really work, apparently most\n // browsers ignore the background palette index and clear to transparency.\n var disposal = opts.disposal === undefined ? 0 : opts.disposal;\n if (disposal < 0 || disposal > 3) // 4-7 is reserved.\n throw new Error(\"Disposal out of range.\");\n\n var use_transparency = false;\n var transparent_index = 0;\n if (opts.transparent !== undefined && opts.transparent !== null) {\n use_transparency = true;\n transparent_index = opts.transparent;\n if (transparent_index < 0 || transparent_index >= num_colors)\n throw new Error(\"Transparent color index.\");\n }\n\n if (disposal !== 0 || use_transparency || delay !== 0) {\n // - Graphics Control Extension\n buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label.\n buf[p++] = 4; // Byte size.\n\n buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);\n buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff;\n buf[p++] = transparent_index; // Transparent color index.\n buf[p++] = 0; // Block Terminator.\n }\n\n // - Image Descriptor\n buf[p++] = 0x2c; // Image Seperator.\n buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left.\n buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top.\n buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff;\n buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff;\n // NOTE: No sort flag (unused?).\n // TODO(deanm): Support interlace.\n buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0;\n\n // - Local Color Table\n if (using_local_palette === true) {\n for (var i = 0, il = palette.length; i < il; ++i) {\n var rgb = palette[i];\n buf[p++] = rgb >> 16 & 0xff;\n buf[p++] = rgb >> 8 & 0xff;\n buf[p++] = rgb & 0xff;\n }\n }\n\n p = GifWriterOutputLZWCodeStream(\n buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);\n\n return p;\n };\n\n this.end = function() {\n if (ended === false) {\n buf[p++] = 0x3b; // Trailer.\n ended = true;\n }\n return p;\n };\n\n this.getOutputBuffer = function() { return buf; };\n this.setOutputBuffer = function(v) { buf = v; };\n this.getOutputBufferPosition = function() { return p; };\n this.setOutputBufferPosition = function(v) { p = v; };\n}\n\n// Main compression routine, palette indexes -> LZW code stream.\n// |index_stream| must have at least one entry.\nfunction GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {\n buf[p++] = min_code_size;\n var cur_subblock = p++; // Pointing at the length field.\n\n var clear_code = 1 << min_code_size;\n var code_mask = clear_code - 1;\n var eoi_code = clear_code + 1;\n var next_code = eoi_code + 1;\n\n var cur_code_size = min_code_size + 1; // Number of bits per code.\n var cur_shift = 0;\n // We have at most 12-bit codes, so we should have to hold a max of 19\n // bits here (and then we would write out).\n var cur = 0;\n\n function emit_bytes_to_buffer(bit_block_size) {\n while (cur_shift >= bit_block_size) {\n buf[p++] = cur & 0xff;\n cur >>= 8; cur_shift -= 8;\n if (p === cur_subblock + 256) { // Finished a subblock.\n buf[cur_subblock] = 255;\n cur_subblock = p++;\n }\n }\n }\n\n function emit_code(c) {\n cur |= c << cur_shift;\n cur_shift += cur_code_size;\n emit_bytes_to_buffer(8);\n }\n\n // I am not an expert on the topic, and I don't want to write a thesis.\n // However, it is good to outline here the basic algorithm and the few data\n // structures and optimizations here that make this implementation fast.\n // The basic idea behind LZW is to build a table of previously seen runs\n // addressed by a short id (herein called output code). All data is\n // referenced by a code, which represents one or more values from the\n // original input stream. All input bytes can be referenced as the same\n // value as an output code. So if you didn't want any compression, you\n // could more or less just output the original bytes as codes (there are\n // some details to this, but it is the idea). In order to achieve\n // compression, values greater then the input range (codes can be up to\n // 12-bit while input only 8-bit) represent a sequence of previously seen\n // inputs. The decompressor is able to build the same mapping while\n // decoding, so there is always a shared common knowledge between the\n // encoding and decoder, which is also important for \"timing\" aspects like\n // how to handle variable bit width code encoding.\n //\n // One obvious but very important consequence of the table system is there\n // is always a unique id (at most 12-bits) to map the runs. 'A' might be\n // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship\n // can be used for an effecient lookup strategy for the code mapping. We\n // need to know if a run has been seen before, and be able to map that run\n // to the output code. Since we start with known unique ids (input bytes),\n // and then from those build more unique ids (table entries), we can\n // continue this chain (almost like a linked list) to always have small\n // integer values that represent the current byte chains in the encoder.\n // This means instead of tracking the input bytes (AAAABCD) to know our\n // current state, we can track the table entry for AAAABC (it is guaranteed\n // to exist by the nature of the algorithm) and the next character D.\n // Therefor the tuple of (table_entry, byte) is guaranteed to also be\n // unique. This allows us to create a simple lookup key for mapping input\n // sequences to codes (table indices) without having to store or search\n // any of the code sequences. So if 'AAAA' has a table entry of 12, the\n // tuple of ('AAAA', K) for any input byte K will be unique, and can be our\n // key. This leads to a integer value at most 20-bits, which can always\n // fit in an SMI value and be used as a fast sparse array / object key.\n\n // Output code for the current contents of the index buffer.\n var ib_code = index_stream[0] & code_mask; // Load first input index.\n var code_table = { }; // Key'd on our 20-bit \"tuple\".\n\n emit_code(clear_code); // Spec says first code should be a clear code.\n\n // First index already loaded, process the rest of the stream.\n for (var i = 1, il = index_stream.length; i < il; ++i) {\n var k = index_stream[i] & code_mask;\n var cur_key = ib_code << 8 | k; // (prev, k) unique tuple.\n var cur_code = code_table[cur_key]; // buffer + k.\n\n // Check if we have to create a new code table entry.\n if (cur_code === undefined) { // We don't have buffer + k.\n // Emit index buffer (without k).\n // This is an inline version of emit_code, because this is the core\n // writing routine of the compressor (and V8 cannot inline emit_code\n // because it is a closure here in a different context). Additionally\n // we can call emit_byte_to_buffer less often, because we can have\n // 30-bits (from our 31-bit signed SMI), and we know our codes will only\n // be 12-bits, so can safely have 18-bits there without overflow.\n // emit_code(ib_code);\n cur |= ib_code << cur_shift;\n cur_shift += cur_code_size;\n while (cur_shift >= 8) {\n buf[p++] = cur & 0xff;\n cur >>= 8; cur_shift -= 8;\n if (p === cur_subblock + 256) { // Finished a subblock.\n buf[cur_subblock] = 255;\n cur_subblock = p++;\n }\n }\n\n if (next_code === 4096) { // Table full, need a clear.\n emit_code(clear_code);\n next_code = eoi_code + 1;\n cur_code_size = min_code_size + 1;\n code_table = { };\n } else { // Table not full, insert a new entry.\n // Increase our variable bit code sizes if necessary. This is a bit\n // tricky as it is based on \"timing\" between the encoding and\n // decoder. From the encoders perspective this should happen after\n // we've already emitted the index buffer and are about to create the\n // first table entry that would overflow our current code bit size.\n if (next_code >= (1 << cur_code_size)) ++cur_code_size;\n code_table[cur_key] = next_code++; // Insert into code table.\n }\n\n ib_code = k; // Index buffer to single input k.\n } else {\n ib_code = cur_code; // Index buffer to sequence in code table.\n }\n }\n\n emit_code(ib_code); // There will still be something in the index buffer.\n emit_code(eoi_code); // End Of Information.\n\n // Flush / finalize the sub-blocks stream to the buffer.\n emit_bytes_to_buffer(1);\n\n // Finish the sub-blocks, writing out any unfinished lengths and\n // terminating with a sub-block of length 0. If we have already started\n // but not yet used a sub-block it can just become the terminator.\n if (cur_subblock + 1 === p) { // Started but unused.\n buf[cur_subblock] = 0;\n } else { // Started and used, write length and additional terminator block.\n buf[cur_subblock] = p - cur_subblock - 1;\n buf[p++] = 0;\n }\n return p;\n}\n\nfunction GifReader(buf) {\n var p = 0;\n\n // - Header (GIF87a or GIF89a).\n if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 ||\n buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) {\n throw new Error(\"Invalid GIF 87a/89a header.\");\n }\n\n // - Logical Screen Descriptor.\n var width = buf[p++] | buf[p++] << 8;\n var height = buf[p++] | buf[p++] << 8;\n var pf0 = buf[p++]; // .\n var global_palette_flag = pf0 >> 7;\n var num_global_colors_pow2 = pf0 & 0x7;\n var num_global_colors = 1 << (num_global_colors_pow2 + 1);\n var background = buf[p++];\n buf[p++]; // Pixel aspect ratio (unused?).\n\n var global_palette_offset = null;\n var global_palette_size = null;\n\n if (global_palette_flag) {\n global_palette_offset = p;\n global_palette_size = num_global_colors;\n p += num_global_colors * 3; // Seek past palette.\n }\n\n var no_eof = true;\n\n var frames = [ ];\n\n var delay = 0;\n var transparent_index = null;\n var disposal = 0; // 0 - No disposal specified.\n var loop_count = null;\n\n this.width = width;\n this.height = height;\n\n while (no_eof && p < buf.length) {\n switch (buf[p++]) {\n case 0x21: // Graphics Control Extension Block\n switch (buf[p++]) {\n case 0xff: // Application specific block\n // Try if it's a Netscape block (with animation loop counter).\n if (buf[p ] !== 0x0b || // 21 FF already read, check block size.\n // NETSCAPE2.0\n buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 &&\n buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 &&\n buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 &&\n buf[p+10] == 0x2e && buf[p+11] == 0x30 &&\n // Sub-block\n buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) {\n p += 14;\n loop_count = buf[p++] | buf[p++] << 8;\n p++; // Skip terminator.\n } else { // We don't know what it is, just try to get past it.\n p += 12;\n while (true) { // Seek through subblocks.\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n p += block_size;\n }\n }\n break;\n\n case 0xf9: // Graphics Control Extension\n if (buf[p++] !== 0x4 || buf[p+4] !== 0)\n throw new Error(\"Invalid graphics extension block.\");\n var pf1 = buf[p++];\n delay = buf[p++] | buf[p++] << 8;\n transparent_index = buf[p++];\n if ((pf1 & 1) === 0) transparent_index = null;\n disposal = pf1 >> 2 & 0x7;\n p++; // Skip terminator.\n break;\n\n case 0xfe: // Comment Extension.\n while (true) { // Seek through subblocks.\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n // console.log(buf.slice(p, p+block_size).toString('ascii'));\n p += block_size;\n }\n break;\n\n default:\n throw new Error(\n \"Unknown graphic control label: 0x\" + buf[p-1].toString(16));\n }\n break;\n\n case 0x2c: // Image Descriptor.\n var x = buf[p++] | buf[p++] << 8;\n var y = buf[p++] | buf[p++] << 8;\n var w = buf[p++] | buf[p++] << 8;\n var h = buf[p++] | buf[p++] << 8;\n var pf2 = buf[p++];\n var local_palette_flag = pf2 >> 7;\n var interlace_flag = pf2 >> 6 & 1;\n var num_local_colors_pow2 = pf2 & 0x7;\n var num_local_colors = 1 << (num_local_colors_pow2 + 1);\n var palette_offset = global_palette_offset;\n var palette_size = global_palette_size;\n var has_local_palette = false;\n if (local_palette_flag) {\n var has_local_palette = true;\n palette_offset = p; // Override with local palette.\n palette_size = num_local_colors;\n p += num_local_colors * 3; // Seek past palette.\n }\n\n var data_offset = p;\n\n p++; // codesize\n while (true) {\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n p += block_size;\n }\n\n frames.push({x: x, y: y, width: w, height: h,\n has_local_palette: has_local_palette,\n palette_offset: palette_offset,\n palette_size: palette_size,\n data_offset: data_offset,\n data_length: p - data_offset,\n transparent_index: transparent_index,\n interlaced: !!interlace_flag,\n delay: delay,\n disposal: disposal});\n break;\n\n case 0x3b: // Trailer Marker (end of file).\n no_eof = false;\n break;\n\n default:\n throw new Error(\"Unknown gif block: 0x\" + buf[p-1].toString(16));\n break;\n }\n }\n\n this.numFrames = function() {\n return frames.length;\n };\n\n this.loopCount = function() {\n return loop_count;\n };\n\n this.frameInfo = function(frame_num) {\n if (frame_num < 0 || frame_num >= frames.length)\n throw new Error(\"Frame index out of range.\");\n return frames[frame_num];\n }\n\n this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {\n var frame = this.frameInfo(frame_num);\n var num_pixels = frame.width * frame.height;\n var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.\n GifReaderLZWOutputIndexStream(\n buf, frame.data_offset, index_stream, num_pixels);\n var palette_offset = frame.palette_offset;\n\n // NOTE(deanm): It seems to be much faster to compare index to 256 than\n // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in\n // the profile, not sure if it's related to using a Uint8Array.\n var trans = frame.transparent_index;\n if (trans === null) trans = 256;\n\n // We are possibly just blitting to a portion of the entire frame.\n // That is a subrect within the framerect, so the additional pixels\n // must be skipped over after we finished a scanline.\n var framewidth = frame.width;\n var framestride = width - framewidth;\n var xleft = framewidth; // Number of subrect pixels left in scanline.\n\n // Output indicies of the top left and bottom right corners of the subrect.\n var opbeg = ((frame.y * width) + frame.x) * 4;\n var opend = ((frame.y + frame.height) * width + frame.x) * 4;\n var op = opbeg;\n\n var scanstride = framestride * 4;\n\n // Use scanstride to skip past the rows when interlacing. This is skipping\n // 7 rows for the first two passes, then 3 then 1.\n if (frame.interlaced === true) {\n scanstride += width * 4 * 7; // Pass 1.\n }\n\n var interlaceskip = 8; // Tracking the row interval in the current pass.\n\n for (var i = 0, il = index_stream.length; i < il; ++i) {\n var index = index_stream[i];\n\n if (xleft === 0) { // Beginning of new scan line\n op += scanstride;\n xleft = framewidth;\n if (op >= opend) { // Catch the wrap to switch passes when interlacing.\n scanstride = framestride * 4 + width * 4 * (interlaceskip-1);\n // interlaceskip / 2 * 4 is interlaceskip << 1.\n op = opbeg + (framewidth + framestride) * (interlaceskip << 1);\n interlaceskip >>= 1;\n }\n }\n\n if (index === trans) {\n op += 4;\n } else {\n var r = buf[palette_offset + index * 3];\n var g = buf[palette_offset + index * 3 + 1];\n var b = buf[palette_offset + index * 3 + 2];\n pixels[op++] = b;\n pixels[op++] = g;\n pixels[op++] = r;\n pixels[op++] = 255;\n }\n --xleft;\n }\n };\n\n // I will go to copy and paste hell one day...\n this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {\n var frame = this.frameInfo(frame_num);\n var num_pixels = frame.width * frame.height;\n var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.\n GifReaderLZWOutputIndexStream(\n buf, frame.data_offset, index_stream, num_pixels);\n var palette_offset = frame.palette_offset;\n\n // NOTE(deanm): It seems to be much faster to compare index to 256 than\n // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in\n // the profile, not sure if it's related to using a Uint8Array.\n var trans = frame.transparent_index;\n if (trans === null) trans = 256;\n\n // We are possibly just blitting to a portion of the entire frame.\n // That is a subrect within the framerect, so the additional pixels\n // must be skipped over after we finished a scanline.\n var framewidth = frame.width;\n var framestride = width - framewidth;\n var xleft = framewidth; // Number of subrect pixels left in scanline.\n\n // Output indicies of the top left and bottom right corners of the subrect.\n var opbeg = ((frame.y * width) + frame.x) * 4;\n var opend = ((frame.y + frame.height) * width + frame.x) * 4;\n var op = opbeg;\n\n var scanstride = framestride * 4;\n\n // Use scanstride to skip past the rows when interlacing. This is skipping\n // 7 rows for the first two passes, then 3 then 1.\n if (frame.interlaced === true) {\n scanstride += width * 4 * 7; // Pass 1.\n }\n\n var interlaceskip = 8; // Tracking the row interval in the current pass.\n\n for (var i = 0, il = index_stream.length; i < il; ++i) {\n var index = index_stream[i];\n\n if (xleft === 0) { // Beginning of new scan line\n op += scanstride;\n xleft = framewidth;\n if (op >= opend) { // Catch the wrap to switch passes when interlacing.\n scanstride = framestride * 4 + width * 4 * (interlaceskip-1);\n // interlaceskip / 2 * 4 is interlaceskip << 1.\n op = opbeg + (framewidth + framestride) * (interlaceskip << 1);\n interlaceskip >>= 1;\n }\n }\n\n if (index === trans) {\n op += 4;\n } else {\n var r = buf[palette_offset + index * 3];\n var g = buf[palette_offset + index * 3 + 1];\n var b = buf[palette_offset + index * 3 + 2];\n pixels[op++] = r;\n pixels[op++] = g;\n pixels[op++] = b;\n pixels[op++] = 255;\n }\n --xleft;\n }\n };\n}\n\nfunction GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {\n var min_code_size = code_stream[p++];\n\n var clear_code = 1 << min_code_size;\n var eoi_code = clear_code + 1;\n var next_code = eoi_code + 1;\n\n var cur_code_size = min_code_size + 1; // Number of bits per code.\n // NOTE: This shares the same name as the encoder, but has a different\n // meaning here. Here this masks each code coming from the code stream.\n var code_mask = (1 << cur_code_size) - 1;\n var cur_shift = 0;\n var cur = 0;\n\n var op = 0; // Output pointer.\n\n var subblock_size = code_stream[p++];\n\n // TODO(deanm): Would using a TypedArray be any faster? At least it would\n // solve the fast mode / backing store uncertainty.\n // var code_table = Array(4096);\n var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.\n\n var prev_code = null; // Track code-1.\n\n while (true) {\n // Read up to two bytes, making sure we always 12-bits for max sized code.\n while (cur_shift < 16) {\n if (subblock_size === 0) break; // No more data to be read.\n\n cur |= code_stream[p++] << cur_shift;\n cur_shift += 8;\n\n if (subblock_size === 1) { // Never let it get to 0 to hold logic above.\n subblock_size = code_stream[p++]; // Next subblock.\n } else {\n --subblock_size;\n }\n }\n\n // TODO(deanm): We should never really get here, we should have received\n // and EOI.\n if (cur_shift < cur_code_size)\n break;\n\n var code = cur & code_mask;\n cur >>= cur_code_size;\n cur_shift -= cur_code_size;\n\n // TODO(deanm): Maybe should check that the first code was a clear code,\n // at least this is what you're supposed to do. But actually our encoder\n // now doesn't emit a clear code first anyway.\n if (code === clear_code) {\n // We don't actually have to clear the table. This could be a good idea\n // for greater error checking, but we don't really do any anyway. We\n // will just track it with next_code and overwrite old entries.\n\n next_code = eoi_code + 1;\n cur_code_size = min_code_size + 1;\n code_mask = (1 << cur_code_size) - 1;\n\n // Don't update prev_code ?\n prev_code = null;\n continue;\n } else if (code === eoi_code) {\n break;\n }\n\n // We have a similar situation as the decoder, where we want to store\n // variable length entries (code table entries), but we want to do in a\n // faster manner than an array of arrays. The code below stores sort of a\n // linked list within the code table, and then \"chases\" through it to\n // construct the dictionary entries. When a new entry is created, just the\n // last byte is stored, and the rest (prefix) of the entry is only\n // referenced by its table entry. Then the code chases through the\n // prefixes until it reaches a single byte code. We have to chase twice,\n // first to compute the length, and then to actually copy the data to the\n // output (backwards, since we know the length). The alternative would be\n // storing something in an intermediate stack, but that doesn't make any\n // more sense. I implemented an approach where it also stored the length\n // in the code table, although it's a bit tricky because you run out of\n // bits (12 + 12 + 8), but I didn't measure much improvements (the table\n // entries are generally not the long). Even when I created benchmarks for\n // very long table entries the complexity did not seem worth it.\n // The code table stores the prefix entry in 12 bits and then the suffix\n // byte in 8 bits, so each entry is 20 bits.\n\n var chase_code = code < next_code ? code : prev_code;\n\n // Chase what we will output, either {CODE} or {CODE-1}.\n var chase_length = 0;\n var chase = chase_code;\n while (chase > clear_code) {\n chase = code_table[chase] >> 8;\n ++chase_length;\n }\n\n var k = chase;\n\n var op_end = op + chase_length + (chase_code !== code ? 1 : 0);\n if (op_end > output_length) {\n console.log(\"Warning, gif stream longer than expected.\");\n return;\n }\n\n // Already have the first byte from the chase, might as well write it fast.\n output[op++] = k;\n\n op += chase_length;\n var b = op; // Track pointer, writing backwards.\n\n if (chase_code !== code) // The case of emitting {CODE-1} + k.\n output[op++] = k;\n\n chase = chase_code;\n while (chase_length--) {\n chase = code_table[chase];\n output[--b] = chase & 0xff; // Write backwards.\n chase >>= 8; // Pull down to the prefix code.\n }\n\n if (prev_code !== null && next_code < 4096) {\n code_table[next_code++] = prev_code << 8 | k;\n // TODO(deanm): Figure out this clearing vs code growth logic better. I\n // have an feeling that it should just happen somewhere else, for now it\n // is awkward between when we grow past the max and then hit a clear code.\n // For now just check if we hit the max 12-bits (then a clear code should\n // follow, also of course encoded in 12-bits).\n if (next_code >= code_mask+1 && cur_code_size < 12) {\n ++cur_code_size;\n code_mask = code_mask << 1 | 1;\n }\n }\n\n prev_code = code;\n }\n\n if (op !== output_length) {\n console.log(\"Warning, gif stream shorter than expected.\");\n }\n\n return output;\n}\n\n// CommonJS.\ntry { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) {}\n","'use strict';\n\n/** @class BitmapImage */\n\nclass BitmapImage {\n\n /**\n * BitmapImage is a class that hold an RGBA (red, green, blue, alpha) representation of an image. It's shape is borrowed from the Jimp package to make it easy to transfer GIF image frames into Jimp and Jimp images into GIF image frames. Each instance has a `bitmap` property having the following properties:\n * \n * Property | Description\n * --- | ---\n * bitmap.width | width of image in pixels\n * bitmap.height | height of image in pixels\n * bitmap.data | a Buffer whose every four bytes represents a pixel, each sequential byte of a pixel corresponding to the red, green, blue, and alpha values of the pixel\n *\n * Its constructor supports the following signatures:\n *\n * * new BitmapImage(bitmap: { width: number, height: number, data: Buffer })\n * * new BitmapImage(bitmapImage: BitmapImage)\n * * new BitmapImage(width: number, height: number, buffer: Buffer)\n * * new BitmapImage(width: number, height: number, backgroundRGBA?: number)\n * \n * When a `BitmapImage` is provided, the constructed `BitmapImage` is a deep clone of the provided one, so that each image's pixel data can subsequently be modified without affecting each other.\n *\n * `backgroundRGBA` is an optional parameter representing a pixel as a single number. In hex, the number is as follows: 0xRRGGBBAA, where RR is the red byte, GG the green byte, BB, the blue byte, and AA the alpha value. An AA of 0x00 is considered transparent, and all non-zero AA values are treated as opaque.\n */\n\n constructor(...args) {\n // don't confirm the number of args, because a subclass may have\n // additional args and pass them all to the superclass\n if (args.length === 0) {\n throw new Error(\"constructor requires parameters\");\n }\n const firstArg = args[0];\n if (firstArg !== null && typeof firstArg === 'object') {\n if (firstArg instanceof BitmapImage) {\n // copy a provided BitmapImage\n const sourceBitmap = firstArg.bitmap;\n this.bitmap = {\n width: sourceBitmap.width,\n height: sourceBitmap.height,\n data: new Buffer(sourceBitmap.width * sourceBitmap.height * 4)\n };\n sourceBitmap.data.copy(this.bitmap.data);\n }\n else if (firstArg.width && firstArg.height && firstArg.data) {\n // share a provided bitmap\n this.bitmap = firstArg;\n }\n else {\n throw new Error(\"unrecognized constructor parameters\");\n }\n }\n else if (typeof firstArg === 'number' && typeof args[1] === 'number')\n {\n const width = firstArg;\n const height = args[1];\n const thirdArg = args[2];\n this.bitmap = { width, height };\n\n if (Buffer.isBuffer(thirdArg)) {\n this.bitmap.data = thirdArg;\n }\n else {\n this.bitmap.data = new Buffer(width * height * 4);\n if (typeof thirdArg === 'number') {\n this.fillRGBA(thirdArg);\n }\n }\n }\n else {\n throw new Error(\"unrecognized constructor parameters\");\n }\n }\n\n /**\n * Copy a square portion of this image into another image. \n * \n * @param {BitmapImage} toImage Image into which to copy the square\n * @param {number} toX x-coord in toImage of upper-left corner of receiving square\n * @param {number} toY y-coord in toImage of upper-left corner of receiving square\n * @param {number} fromX x-coord in this image of upper-left corner of source square\n * @param {number} fromY y-coord in this image of upper-left corner of source square\n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n blit(toImage, toX, toY, fromX, fromY, fromWidth, fromHeight) {\n if (fromX + fromWidth > this.bitmap.width) {\n throw new Error(\"copy exceeds width of source bitmap\");\n }\n if (toX + fromWidth > toImage.bitmap.width) {\n throw new Error(\"copy exceeds width of target bitmap\");\n }\n if (fromY + fromHeight > this.bitmap.height) {\n throw new Error(\"copy exceeds height of source bitmap\");\n }\n if (toY + fromHeight > toImage.bitmap.height) {\n throw new Erro(\"copy exceeds height of target bitmap\");\n }\n \n const sourceBuf = this.bitmap.data;\n const targetBuf = toImage.bitmap.data;\n const sourceByteWidth = this.bitmap.width * 4;\n const targetByteWidth = toImage.bitmap.width * 4;\n const copyByteWidth = fromWidth * 4;\n let si = fromY * sourceByteWidth + fromX * 4;\n let ti = toY * targetByteWidth + toX * 4;\n\n while (--fromHeight >= 0) {\n sourceBuf.copy(targetBuf, ti, si, si + copyByteWidth);\n si += sourceByteWidth;\n ti += targetByteWidth;\n }\n return this;\n }\n\n /**\n * Fills the image with a single color.\n * \n * @param {number} rgba Color with which to fill image, expressed as a singlenumber in the form 0xRRGGBBAA, where AA is 0x00 for transparent and any other value for opaque.\n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n fillRGBA(rgba) {\n const buf = this.bitmap.data;\n const bufByteWidth = this.bitmap.height * 4;\n \n let bi = 0;\n while (bi < bufByteWidth) {\n buf.writeUInt32BE(rgba, bi);\n bi += 4;\n }\n while (bi < buf.length) {\n buf.copy(buf, bi, 0, bufByteWidth);\n bi += bufByteWidth;\n }\n return this;\n }\n\n /**\n * Gets the RGBA number of the pixel at the given coordinate in the form 0xRRGGBBAA, where AA is the alpha value, with alpha 0x00 encoding to transparency in GIFs.\n * \n * @param {number} x x-coord of pixel\n * @param {number} y y-coord of pixel\n * @return {number} RGBA of pixel in 0xRRGGBBAA form\n */\n\n getRGBA(x, y) {\n const bi = (y * this.bitmap.width + x) * 4;\n return this.bitmap.data.readUInt32BE(bi);\n }\n\n /**\n * Gets a set of all RGBA colors found within the image.\n * \n * @return {Set} Set of all RGBA colors that the image contains.\n */\n\n getRGBASet() {\n const rgbaSet = new Set();\n const buf = this.bitmap.data;\n for (let bi = 0; bi < buf.length; bi += 4) {\n rgbaSet.add(buf.readUInt32BE(bi, true));\n }\n return rgbaSet;\n }\n\n /**\n * Converts the image to greyscale using inferred Adobe metrics.\n * \n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n greyscale() {\n const buf = this.bitmap.data;\n this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {\n const grey = Math.round(\n 0.299 * buf[idx] +\n 0.587 * buf[idx + 1] +\n 0.114 * buf[idx + 2]\n );\n buf[idx] = grey;\n buf[idx + 1] = grey;\n buf[idx + 2] = grey;\n });\n return this;\n }\n\n /**\n * Reframes the image as if placing a frame around the original image and replacing the original image with the newly framed image. When the new frame is strictly within the boundaries of the original image, this method crops the image. When any of the new boundaries exceed those of the original image, the `fillRGBA` must be provided to indicate the color with which to fill the extra space added to the image.\n * \n * @param {number} xOffset The x-coord offset of the upper-left pixel of the desired image relative to the present image.\n * @param {number} yOffset The y-coord offset of the upper-left pixel of the desired image relative to the present image.\n * @param {number} width The width of the new image after reframing\n * @param {number} height The height of the new image after reframing\n * @param {number} fillRGBA The color with which to fill space added to the image as a result of the reframing, in 0xRRGGBBAA format, where AA is 0x00 to indicate transparent and a non-zero value to indicate opaque. This parameter is only required when the reframing exceeds the original boundaries (i.e. does not simply perform a crop).\n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n reframe(xOffset, yOffset, width, height, fillRGBA) {\n const cropX = (xOffset < 0 ? 0 : xOffset);\n const cropY = (yOffset < 0 ? 0 : yOffset);\n const cropWidth = (width + cropX > this.bitmap.width ?\n this.bitmap.width - cropX : width);\n const cropHeight = (height + cropY > this.bitmap.height ?\n this.bitmap.height - cropY : height);\n const newX = (xOffset < 0 ? -xOffset : 0);\n const newY = (yOffset < 0 ? -yOffset : 0);\n\n let image;\n if (fillRGBA === undefined) {\n if (cropX !== xOffset || cropY != yOffset ||\n cropWidth !== width || cropHeight !== height)\n {\n throw new GifError(`fillRGBA required for this reframing`);\n }\n image = new BitmapImage(width, height);\n }\n else {\n image = new BitmapImage(width, height, fillRGBA);\n }\n this.blit(image, newX, newY, cropX, cropY, cropWidth, cropHeight);\n this.bitmap = image.bitmap;\n return this;\n }\n\n /**\n * Scales the image size up by an integer factor. Each pixel of the original image becomes a square of the same color in the new image having a size of `factor` x `factor` pixels.\n * \n * @param {number} factor The factor by which to scale up the image. Must be an integer >= 1.\n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n scale(factor) {\n if (factor === 1) {\n return;\n }\n if (!Number.isInteger(factor) || factor < 1) {\n throw new Error(\"the scale must be an integer >= 1\");\n }\n const sourceWidth = this.bitmap.width;\n const sourceHeight = this.bitmap.height;\n const destByteWidth = sourceWidth * factor * 4;\n const sourceBuf = this.bitmap.data;\n const destBuf = new Buffer(sourceHeight * destByteWidth * factor);\n let sourceIndex = 0;\n let priorDestRowIndex;\n let destIndex = 0;\n for (let y = 0; y < sourceHeight; ++y) {\n priorDestRowIndex = destIndex;\n for (let x = 0; x < sourceWidth; ++x) {\n const color = sourceBuf.readUInt32BE(sourceIndex, true);\n for (let cx = 0; cx < factor; ++cx) {\n destBuf.writeUInt32BE(color, destIndex);\n destIndex += 4;\n }\n sourceIndex += 4;\n }\n for (let cy = 1; cy < factor; ++cy) {\n destBuf.copy(destBuf, destIndex, priorDestRowIndex, destIndex);\n destIndex += destByteWidth;\n priorDestRowIndex += destByteWidth;\n }\n }\n this.bitmap = {\n width: sourceWidth * factor,\n height: sourceHeight * factor,\n data: destBuf\n };\n return this;\n }\n\n /**\n * Scans all coordinates of the image, handing each in turn to the provided handler function.\n *\n * @param {function} scanHandler A function(x: number, y: number, bi: number) to be called for each pixel of the image with that pixel's x-coord, y-coord, and index into the `data` buffer. The function accesses the pixel at this coordinate by accessing the `this.data` at index `bi`.\n * @see scanAllIndexes\n */\n\n scanAllCoords(scanHandler) {\n const width = this.bitmap.width;\n const bufferLength = this.bitmap.data.length;\n let x = 0;\n let y = 0;\n\n for (let bi = 0; bi < bufferLength; bi += 4) {\n scanHandler(x, y, bi);\n if (++x === width) {\n x = 0;\n ++y;\n }\n }\n }\n\n /**\n * Scans all pixels of the image, handing the index of each in turn to the provided handler function. Runs a bit faster than `scanAllCoords()`, should the handler not need pixel coordinates.\n *\n * @param {function} scanHandler A function(bi: number) to be called for each pixel of the image with that pixel's index into the `data` buffer. The pixels is found at index 'bi' within `this.data`.\n * @see scanAllCoords\n */\n\n scanAllIndexes(scanHandler) {\n const bufferLength = this.bitmap.data.length;\n for (let bi = 0; bi < bufferLength; bi += 4) {\n scanHandler(bi);\n }\n }\n}\n\nmodule.exports = BitmapImage;\n","'use strict';\n\n/** @class Gif */\n\nclass Gif {\n\n // width - width of GIF in pixels\n // height - height of GIF in pixels\n // loops - 0 = unending; (n > 0) = iterate n times\n // usesTransparency - whether any frames have transparent pixels\n // colorScope - scope of color tables in GIF\n // frames - array of frames\n // buffer - GIF-formatted data\n\n /**\n * Gif is a class representing an encoded GIF. It is intended to be a read-only representation of a byte-encoded GIF. Only encoders and decoders should be creating instances of this class.\n * \n * Property | Description\n * --- | ---\n * width | width of the GIF at its widest\n * height | height of the GIF at its highest\n * loops | the number of times the GIF should loop before stopping; 0 => loop indefinitely\n * usesTransparency | boolean indicating whether at least one frame contains at least one transparent pixel\n * colorScope | the scope of the color tables as encoded within the GIF; either Gif.GlobalColorsOnly (== 1) or Gif.LocalColorsOnly (== 2).\n * frames | a array of GifFrame instances, one for each frame of the GIF\n * buffer | a Buffer holding the encoding's byte data\n * \n * Its constructor should only ever be called by the GIF encoder or decoder.\n *\n * @param {Buffer} buffer A Buffer containing the encoded bytes\n * @param {GifFrame[]} frames Array of frames found in the encoding\n * @param {object} spec Properties of the encoding as listed above\n */\n\n constructor(buffer, frames, spec) {\n this.width = spec.width;\n this.height = spec.height;\n this.loops = spec.loops;\n this.usesTransparency = spec.usesTransparency;\n this.colorScope = spec.colorScope;\n this.frames = frames;\n this.buffer = buffer;\n }\n}\n\nGif.GlobalColorsPreferred = 0;\nGif.GlobalColorsOnly = 1;\nGif.LocalColorsOnly = 2;\n\n/** @class GifError */\n\nclass GifError extends Error {\n\n /**\n * GifError is a class representing a GIF-related error\n * \n * @param {string|Error} messageOrError\n */\n\n constructor(messageOrError) {\n super(messageOrError);\n if (messageOrError instanceof Error) {\n this.stack = 'Gif' + messageOrError.stack;\n }\n }\n}\n\nexports.Gif = Gif;\nexports.GifError = GifError;\n","'use strict';\n\nconst Omggif = require('omggif');\nconst { Gif, GifError } = require('./gif');\n\n// allow circular dependency with GifUtil\nfunction GifUtil() {\n const data = require('./gifutil');\n\n GifUtil = function () {\n return data;\n };\n\n return data;\n}\n\nconst { GifFrame } = require('./gifframe');\n\nconst PER_GIF_OVERHEAD = 200; // these are guesses at upper limits\nconst PER_FRAME_OVERHEAD = 100;\n\n// Note: I experimented with accepting a global color table when encoding and returning the global color table when decoding. Doing this properly greatly increased the complexity of the code and the amount of clock cycles required. The main issue is that each frame can specify any color of the global color table to be transparent within the frame, while this GIF library strives to hide GIF formatting details from its clients. E.g. it's possible to have 256 colors in the global color table and different transparencies in each frame, requiring clients to either provide per-frame transparency indexes, or for arcane reasons that won't be apparent to client developers, encode some GIFs with local color tables that previously decoded with global tables.\n\n/** @class GifCodec */\n\nclass GifCodec\n{\n // _transparentRGBA - RGB given to transparent pixels (alpha=0) on decode; defaults to null indicating 0x000000, which is fastest\n\n /**\n * GifCodec is a class that both encodes and decodes GIFs. It implements both the `encode()` method expected of an encoder and the `decode()` method expected of a decoder, and it wraps the `omggif` GIF encoder/decoder package. GifCodec serves as this library's default encoder and decoder, but it's possible to wrap other GIF encoders and decoders for use by `gifwrap` as well. GifCodec will not encode GIFs with interlacing.\n * \n * Instances of this class are stateless and can be shared across multiple encodings and decodings.\n * \n * Its constructor takes one option argument:\n * \n * @param {object} options Optionally takes an objection whose only possible property is `transparentRGB`. Images are internally represented in RGBA format, where A is the alpha value of a pixel. When `transparentRGB` is provided, this RGB value (excluding alpha) is assigned to transparent pixels, which are also given alpha value 0x00. (All opaque pixels are given alpha value 0xFF). The RGB color of transparent pixels shouldn't matter for most applications. Defaults to 0x000000.\n */\n\n constructor(options = {}) {\n this._transparentRGB = null; // 0x000000\n if (typeof options.transparentRGB === 'number' &&\n options.transparentRGB !== 0)\n {\n this._transparentRGBA = options.transparentRGB * 256;\n }\n this._testInitialBufferSize = 0; // assume no buffer scaling test\n }\n\n /**\n * Decodes a GIF from a Buffer to yield an instance of Gif. Transparent pixels of the GIF are given alpha values of 0x00, and opaque pixels are given alpha values of 0xFF. The RGB values of transparent pixels default to 0x000000 but can be overridden by the constructor's `transparentRGB` option.\n * \n * @param {Buffer} buffer Bytes of an encoded GIF to decode.\n * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.\n * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.\n */\n\n decodeGif(buffer) {\n try {\n let reader;\n try {\n reader = new Omggif.GifReader(buffer);\n }\n catch (err) {\n throw new GifError(err);\n }\n const frameCount = reader.numFrames();\n const frames = [];\n const spec = {\n width: reader.width,\n height: reader.height,\n loops: reader.loopCount()\n };\n\n spec.usesTransparency = false;\n for (let i = 0; i < frameCount; ++i) {\n const frameInfo =\n this._decodeFrame(reader, i, spec.usesTransparency);\n frames.push(frameInfo.frame);\n if (frameInfo.usesTransparency) {\n spec.usesTransparency = true;\n }\n }\n return Promise.resolve(new Gif(buffer, frames, spec));\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n\n /**\n * Encodes a GIF from provided frames. Each pixel having an alpha value of 0x00 renders as transparent within the encoding, while all pixels of non-zero alpha value render as opaque.\n * \n * @param {GifFrame[]} frames Array of frames to encode\n * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely. Set `loop` to null to disable looping, playing only once. `colorScope` defaults to Gif.GlobalColorsPreferred.\n * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.\n * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.\n */\n\n encodeGif(frames, spec = {}) {\n try {\n if (frames === null || frames.length === 0) {\n throw new GifError(\"there are no frames\");\n }\n const dims = GifUtil().getMaxDimensions(frames);\n\n spec = Object.assign({}, spec); // don't munge caller's spec\n spec.width = dims.maxWidth;\n spec.height = dims.maxHeight;\n if (spec.loops === undefined) {\n spec.loops = 0;\n }\n spec.colorScope = spec.colorScope || Gif.GlobalColorsPreferred;\n\n return Promise.resolve(this._encodeGif(frames, spec));\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n\n _decodeFrame(reader, frameIndex, alreadyUsedTransparency) {\n let info, buffer;\n try {\n info = reader.frameInfo(frameIndex);\n buffer = new Buffer(reader.width * reader.height * 4);\n reader.decodeAndBlitFrameRGBA(frameIndex, buffer);\n if (info.width !== reader.width || info.height !== reader.height) {\n if (info.y) {\n // skip unused rows\n buffer = buffer.slice(info.y * reader.width * 4);\n }\n if (reader.width > info.width) {\n // skip scanstride\n for (let ii = 0; ii < info.height; ++ii) {\n buffer.copy(buffer, ii * info.width * 4,\n (info.x + ii * reader.width) * 4,\n (info.x + ii * reader.width) * 4 + info.width * 4);\n }\n }\n // trim buffer to size\n buffer = buffer.slice(0, info.width * info.height * 4);\n }\n }\n catch (err) {\n throw new GifError(err);\n }\n\n let usesTransparency = false;\n if (this._transparentRGBA === null) {\n if (!alreadyUsedTransparency) {\n for (let i = 3; i < buffer.length; i += 4) {\n if (buffer[i] === 0) {\n usesTransparency = true;\n i = buffer.length;\n }\n }\n }\n }\n else {\n for (let i = 3; i < buffer.length; i += 4) {\n if (buffer[i] === 0) {\n buffer.writeUInt32BE(this._transparentRGBA, i - 3);\n usesTransparency = true; // GIF might encode unused index\n }\n }\n }\n\n const frame = new GifFrame(info.width, info.height, buffer, {\n xOffset: info.x,\n yOffset: info.y,\n disposalMethod: info.disposal,\n interlaced: info.interlaced,\n delayCentisecs: info.delay\n });\n return { frame, usesTransparency };\n }\n\n _encodeGif(frames, spec) {\n let colorInfo;\n if (spec.colorScope === Gif.LocalColorsOnly) {\n colorInfo = GifUtil().getColorInfo(frames, 0);\n }\n else {\n colorInfo = GifUtil().getColorInfo(frames, 256);\n if (!colorInfo.colors) { // if global palette impossible\n if (spec.colorScope === Gif.GlobalColorsOnly) {\n throw new GifError(\n \"Too many color indexes for global color table\");\n }\n spec.colorScope = Gif.LocalColorsOnly\n }\n }\n spec.usesTransparency = colorInfo.usesTransparency;\n\n const localPalettes = colorInfo.palettes;\n if (spec.colorScope === Gif.LocalColorsOnly) {\n const localSizeEst = 2000; //this._getSizeEstimateLocal(localPalettes, frames);\n return _encodeLocal(frames, spec, localSizeEst, localPalettes);\n }\n\n const globalSizeEst = 2000; //this._getSizeEstimateGlobal(colorInfo, frames);\n return _encodeGlobal(frames, spec, globalSizeEst, colorInfo);\n }\n\n _getSizeEstimateGlobal(globalPalette, frames) {\n if (this._testInitialBufferSize > 0) {\n return this._testInitialBufferSize;\n }\n let sizeEst = PER_GIF_OVERHEAD + 3*256 /* max palette size*/;\n const pixelBitWidth = _getPixelBitWidth(globalPalette);\n frames.forEach(frame => {\n sizeEst += _getFrameSizeEst(frame, pixelBitWidth);\n });\n return sizeEst; // should be the upper limit\n }\n\n _getSizeEstimateLocal(palettes, frames) {\n if (this._testInitialBufferSize > 0) {\n return this._testInitialBufferSize;\n }\n let sizeEst = PER_GIF_OVERHEAD;\n for (let i = 0; i < frames.length; ++i ) {\n const palette = palettes[i];\n const pixelBitWidth = _getPixelBitWidth(palette);\n sizeEst += _getFrameSizeEst(frames[i], pixelBitWidth);\n }\n return sizeEst; // should be the upper limit\n }\n}\nexports.GifCodec = GifCodec;\n\nfunction _colorLookupLinear(colors, color) {\n const index = colors.indexOf(color);\n return (index === -1 ? null : index);\n}\n\nfunction _colorLookupBinary(colors, color) {\n // adapted from https://stackoverflow.com/a/10264318/650894\n var lo = 0, hi = colors.length - 1, mid;\n while (lo <= hi) {\n mid = Math.floor((lo + hi)/2);\n if (colors[mid] > color)\n hi = mid - 1;\n else if (colors[mid] < color)\n lo = mid + 1;\n else\n return mid;\n }\n return null;\n}\n\nfunction _encodeGlobal(frames, spec, bufferSizeEst, globalPalette) {\n // would be inefficient for frames to lookup colors in extended palette \n const extendedGlobalPalette = {\n colors: globalPalette.colors.slice(),\n usesTransparency: globalPalette.usesTransparency\n };\n _extendPaletteToPowerOf2(extendedGlobalPalette);\n const options = {\n palette: extendedGlobalPalette.colors,\n loop: spec.loops\n };\n let buffer = new Buffer(bufferSizeEst);\n let gifWriter;\n try {\n gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height,\n options);\n }\n catch (err) {\n throw new GifError(err);\n }\n for (let i = 0; i < frames.length; ++i) {\n buffer = _writeFrame(gifWriter, i, frames[i], globalPalette, false);\n }\n return new Gif(buffer.slice(0, gifWriter.end()), frames, spec);\n}\n\nfunction _encodeLocal(frames, spec, bufferSizeEst, localPalettes) {\n const options = {\n loop: spec.loops\n };\n let buffer = new Buffer(bufferSizeEst);\n let gifWriter;\n try {\n gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height,\n options);\n } \n catch (err) {\n throw new GifError(err);\n }\n for (let i = 0; i < frames.length; ++i) {\n buffer = _writeFrame(gifWriter, i, frames[i], localPalettes[i], true);\n }\n return new Gif(buffer.slice(0, gifWriter.end()), frames, spec);\n}\n\nfunction _extendPaletteToPowerOf2(palette) {\n const colors = palette.colors;\n if (palette.usesTransparency) {\n colors.push(0);\n }\n const colorCount = colors.length;\n let powerOf2 = 2;\n while (colorCount > powerOf2) {\n powerOf2 <<= 1;\n }\n colors.length = powerOf2;\n colors.fill(0, colorCount);\n}\n\nfunction _getFrameSizeEst(frame, pixelBitWidth) {\n let byteLength = frame.bitmap.width * frame.bitmap.height;\n byteLength = Math.ceil(byteLength * pixelBitWidth / 8);\n byteLength += Math.ceil(byteLength / 255); // add block size bytes\n // assume maximum palete size because it might get extended for power of 2\n return (PER_FRAME_OVERHEAD + byteLength + 3 * 256 /* largest palette */);\n}\n\nfunction _getIndexedImage(frameIndex, frame, palette) {\n const colors = palette.colors;\n const colorToIndexFunc = (colors.length <= 8 ? // guess at the break-even\n _colorLookupLinear : _colorLookupBinary);\n const colorBuffer = frame.bitmap.data;\n const indexBuffer = new Buffer(colorBuffer.length/4);\n let transparentIndex = colors.length;\n let i = 0, j = 0;\n\n while (i < colorBuffer.length) {\n if (colorBuffer[i + 3] !== 0) {\n const color = (colorBuffer.readUInt32BE(i, true) >> 8) & 0xFFFFFF;\n // caller guarantees that the color will be in the palette\n indexBuffer[j] = colorToIndexFunc(colors, color);\n }\n else {\n indexBuffer[j] = transparentIndex;\n }\n i += 4; // skip alpha\n ++j;\n }\n\n if (palette.usesTransparency) {\n if (transparentIndex === 256) {\n throw new GifError(`Frame ${frameIndex} already has 256 colors` +\n `and so can't use transparency`);\n }\n }\n else {\n transparentIndex = null;\n }\n\n return { buffer: indexBuffer, transparentIndex };\n}\n\nfunction _getPixelBitWidth(palette) {\n let indexCount = palette.indexCount;\n let pixelBitWidth = 0;\n --indexCount; // start at maximum index\n while (indexCount) {\n ++pixelBitWidth;\n indexCount >>= 1;\n }\n return (pixelBitWidth > 0 ? pixelBitWidth : 1);\n}\n\nfunction _writeFrame(gifWriter, frameIndex, frame, palette, isLocalPalette) {\n if (frame.interlaced) {\n throw new GifError(\"writing interlaced GIFs is not supported\");\n }\n const frameInfo = _getIndexedImage(frameIndex, frame, palette);\n const options = {\n delay: frame.delayCentisecs,\n disposal: frame.disposalMethod,\n transparent: frameInfo.transparentIndex\n };\n if (isLocalPalette) {\n _extendPaletteToPowerOf2(palette); // ok 'cause palette never used again\n options.palette = palette.colors;\n }\n try {\n let buffer = gifWriter.getOutputBuffer();\n let startOfFrame = gifWriter.getOutputBufferPosition();\n let endOfFrame;\n let tryAgain = true;\n\n while (tryAgain) {\n endOfFrame = gifWriter.addFrame(frame.xOffset, frame.yOffset,\n frame.bitmap.width, frame.bitmap.height, frameInfo.buffer, options);\n tryAgain = false;\n if (endOfFrame >= buffer.length - 1) {\n const biggerBuffer = new Buffer(buffer.length * 1.5);\n buffer.copy(biggerBuffer);\n gifWriter.setOutputBuffer(biggerBuffer);\n gifWriter.setOutputBufferPosition(startOfFrame);\n buffer = biggerBuffer;\n tryAgain = true;\n }\n }\n return buffer;\n }\n catch (err) {\n throw new GifError(err);\n }\n}\n","'use strict';\n\nconst BitmapImage = require('./bitmapimage');\nconst { GifError } = require('./gif');\n\n/** @class GifFrame */\n\nclass GifFrame extends BitmapImage {\n\n // xOffset - x offset of bitmap on GIF (defaults to 0)\n // yOffset - y offset of bitmap on GIF (defaults to 0)\n // disposalMethod - pixel disposal method when handling partial images\n // delayCentisecs - duration of frame in hundredths of a second\n // interlaced - whether the image is interlaced (defaults to false)\n\n /**\n * GifFrame is a class representing an image frame of a GIF. GIFs contain one or more instances of GifFrame.\n * \n * Property | Description\n * --- | ---\n * xOffset | x-coord of position within GIF at which to render the image (defaults to 0)\n * yOffset | y-coord of position within GIF at which to render the image (defaults to 0)\n * disposalMethod | GIF disposal method; only relevant when the frames aren't all the same size (defaults to 2, disposing to background color)\n * delayCentisecs | duration of the frame in hundreths of a second\n * interlaced | boolean indicating whether the frame renders interlaced\n * \n * Its constructor supports the following signatures:\n * \n * * new GifFrame(bitmap: {width: number, height: number, data: Buffer}, options?)\n * * new GifFrame(bitmapImage: BitmapImage, options?)\n * * new GifFrame(width: number, height: number, buffer: Buffer, options?)\n * * new GifFrame(width: number, height: number, backgroundRGBA?: number, options?)\n * * new GifFrame(frame: GifFrame)\n * \n * See the base class BitmapImage for a discussion of all parameters but `options` and `frame`. `options` is an optional argument providing initial values for the above-listed GifFrame properties. Each property within option is itself optional.\n * \n * Provide a `frame` to the constructor to create a clone of the provided frame. The new frame includes a copy of the provided frame's pixel data so that each can subsequently be modified without affecting each other.\n */\n\n constructor(...args) {\n super(...args);\n if (args[0] instanceof GifFrame) {\n // copy a provided GifFrame\n const source = args[0];\n this.xOffset = source.xOffset;\n this.yOffset = source.yOffset;\n this.disposalMethod = source.disposalMethod;\n this.delayCentisecs = source.delayCentisecs;\n this.interlaced = source.interlaced;\n }\n else {\n const lastArg = args[args.length - 1];\n let options = {};\n if (typeof lastArg === 'object' && !(lastArg instanceof BitmapImage)) {\n options = lastArg;\n }\n this.xOffset = options.xOffset || 0;\n this.yOffset = options.yOffset || 0;\n this.disposalMethod = (options.disposalMethod !== undefined ?\n options.disposalMethod : GifFrame.DisposeToBackgroundColor);\n this.delayCentisecs = options.delayCentisecs || 8;\n this.interlaced = options.interlaced || false;\n }\n }\n\n /**\n * Get a summary of the colors found within the frame. The return value is an object of the following form:\n * \n * Property | Description\n * --- | ---\n * colors | An array of all the opaque colors found within the frame. Each color is given as an RGB number of the form 0xRRGGBB. The array is sorted by increasing number. Will be an empty array when the image is completely transparent.\n * usesTransparency | boolean indicating whether there are any transparent pixels within the frame. A pixel is considered transparent if its alpha value is 0x00.\n * indexCount | The number of color indexes required to represent this palette of colors. It is equal to the number of opaque colors plus one if the image includes transparency.\n * \n * @return {object} An object representing a color palette as described above.\n */\n\n getPalette() {\n // returns with colors sorted low to high\n const colorSet = new Set();\n const buf = this.bitmap.data;\n let i = 0;\n let usesTransparency = false;\n while (i < buf.length) {\n if (buf[i + 3] === 0) {\n usesTransparency = true;\n }\n else {\n // can eliminate the bitshift by starting one byte prior\n const color = (buf.readUInt32BE(i, true) >> 8) & 0xFFFFFF;\n colorSet.add(color);\n }\n i += 4; // skip alpha\n }\n const colors = new Array(colorSet.size);\n const iter = colorSet.values();\n for (i = 0; i < colors.length; ++i) {\n colors[i] = iter.next().value;\n }\n colors.sort((a, b) => (a - b));\n let indexCount = colors.length;\n if (usesTransparency) {\n ++indexCount;\n }\n return { colors, usesTransparency, indexCount };\n }\n}\n\nGifFrame.DisposeToAnything = 0;\nGifFrame.DisposeNothing = 1;\nGifFrame.DisposeToBackgroundColor = 2;\nGifFrame.DisposeToPrevious = 3;\n\nexports.GifFrame = GifFrame;\n","'use strict';\n\n/** @namespace GifUtil */\n\nconst fs = require('fs');\nconst ImageQ = require('image-q');\n\nconst BitmapImage = require('./bitmapimage');\nconst { GifFrame } = require('./gifframe');\nconst { GifError } = require('./gif');\nconst { GifCodec } = require('./gifcodec');\n\nconst INVALID_SUFFIXES = ['.jpg', '.jpeg', '.png', '.bmp'];\n\nconst defaultCodec = new GifCodec();\n\n/**\n * cloneFrames() clones provided frames. It's a utility method for cloning an entire array of frames at once.\n * \n * @function cloneFrames\n * @memberof GifUtil\n * @param {GifFrame[]} frames An array of GifFrame instances to clone\n * @return {GifFrame[]} An array of GifFrame clones of the provided frames.\n */\n\nexports.cloneFrames = function (frames) {\n let clones = [];\n frames.forEach(frame => {\n\n clones.push(new GifFrame(frame));\n });\n return clones;\n}\n\n/**\n * getColorInfo() gets information about the colors used in the provided frames. The method is able to return an array of all colors found across all frames.\n * \n * `maxGlobalIndex` controls whether the computation short-circuits to avoid doing work that the caller doesn't need. The method only returns `colors` and `indexCount` for the colors across all frames when the number of indexes required to store the colors and transparency in a GIF (which is the value of `indexCount`) is less than or equal to `maxGlobalIndex`. Such short-circuiting is useful when the caller just needs to determine whether any frame includes transparency.\n * \n * @function getColorInfo\n * @memberof GifUtil\n * @param {GifFrame[]} frames Frames to examine for color and transparency.\n * @param {number} maxGlobalIndex Maximum number of color indexes (including one for transparency) allowed among the returned compilation of colors. `colors` and `indexCount` are not returned if the number of color indexes required to accommodate all frames exceeds this number. Returns `colors` and `indexCount` by default.\n * @returns {object} Object containing at least `palettes` and `usesTransparency`. `palettes` is an array of all the palettes returned by GifFrame#getPalette(). `usesTransparency` indicates whether at least one frame uses transparency. If `maxGlobalIndex` is not exceeded, the object also contains `colors`, an array of all colors (RGB) found across all palettes, sorted by increasing value, and `indexCount` indicating the number of indexes required to store the colors and the transparency in a GIF.\n * @throws {GifError} When any frame requires more than 256 color indexes.\n */\n\nexports.getColorInfo = function (frames, maxGlobalIndex) {\n let usesTransparency = false;\n const palettes = [];\n for (let i = 0; i < frames.length; ++i) {\n let palette = frames[i].getPalette();\n if (palette.usesTransparency) {\n usesTransparency = true;\n }\n if (palette.indexCount > 256) {\n throw new GifError(`Frame ${i} uses more than 256 color indexes`);\n }\n palettes.push(palette);\n }\n if (maxGlobalIndex === 0) {\n return { usesTransparency, palettes };\n }\n\n const globalColorSet = new Set();\n palettes.forEach(palette => {\n\n palette.colors.forEach(color => {\n\n globalColorSet.add(color);\n });\n });\n let indexCount = globalColorSet.size;\n if (usesTransparency) {\n // odd that GIF requires a color table entry at transparent index\n ++indexCount;\n }\n if (maxGlobalIndex && indexCount > maxGlobalIndex) {\n return { usesTransparency, palettes };\n }\n \n const colors = new Array(globalColorSet.size);\n const iter = globalColorSet.values();\n for (let i = 0; i < colors.length; ++i) {\n colors[i] = iter.next().value;\n }\n colors.sort((a, b) => (a - b));\n return { colors, indexCount, usesTransparency, palettes };\n};\n\n/**\n * copyAsJimp() returns a Jimp that contains a copy of the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the Jimp does not affect the provided bitmap image. This method serves as a macro for simplifying working with Jimp.\n *\n * @function copyAsJimp\n * @memberof GifUtil\n * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp.\n * @param {bitmapImageToCopy} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp.\n * @return {object} An new instance of Jimp containing a copy of the image in bitmapImageToCopy.\n */\n \nexports.copyAsJimp = function (jimp, bitmapImageToCopy) {\n return exports.shareAsJimp(jimp, new BitmapImage(bitmapImageToCopy));\n};\n\n/**\n * getMaxDimensions() returns the pixel width and height required to accommodate all of the provided frames, according to the offsets and dimensions of each frame.\n * \n * @function getMaxDimensions\n * @memberof GifUtil\n * @param {GifFrame[]} frames Frames to measure for their aggregate maximum dimensions.\n * @return {object} An object of the form {maxWidth, maxHeight} indicating the maximum width and height required to accommodate all frames.\n */\n\nexports.getMaxDimensions = function (frames) {\n let maxWidth = 0, maxHeight = 0;\n frames.forEach(frame => {\n const width = frame.xOffset + frame.bitmap.width;\n if (width > maxWidth) {\n maxWidth = width;\n }\n const height = frame.yOffset + frame.bitmap.height;\n if (height > maxHeight) {\n maxHeight = height;\n }\n });\n return { maxWidth, maxHeight };\n};\n\n/**\n * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Anthony Dekker.\n * \n * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.\n * \n * The method may increase the number of colors if there are fewer than the provided maximum.\n * \n * @function quantizeDekker\n * @memberof GifUtil\n * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.\n * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.\n * @param {object} dither (optional) An object configuring the dithering to apply. The properties are as followings, imported from the [`image-q` package](https://github.com/ibezkrovnyi/image-quantization) without explanation: { `ditherAlgorithm`: One of 'FloydSteinberg', 'FalseFloydSteinberg', 'Stucki', 'Atkinson', 'Jarvis', 'Burkes', 'Sierra', 'TwoSierra', 'SierraLite'; `minimumColorDistanceToDither`: (optional) A number defaulting to 0; `serpentine`: (optional) A boolean defaulting to true; `calculateErrorLikeGIMP`: (optional) A boolean defaulting to false. }\n */\n\nexports.quantizeDekker = function (imageOrImages, maxColorIndexes, dither) {\n maxColorIndexes = maxColorIndexes || 256;\n _quantize(imageOrImages, 'NeuQuantFloat', maxColorIndexes, 0, dither);\n}\n\n/**\n * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Leon Sorokin. This quantization method differs from the other two by likely never increasing the number of colors, should there be fewer than the provided maximum.\n * \n * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.\n * \n * @function quantizeSorokin\n * @memberof GifUtil\n * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.\n * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.\n * @param {string} histogram (optional) Histogram method: 'top-pop' for global top-population, 'min-pop' for minimum-population threshhold within subregions. Defaults to 'min-pop'.\n * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`.\n */\n\nexports.quantizeSorokin = function (imageOrImages, maxColorIndexes, histogram, dither) {\n maxColorIndexes = maxColorIndexes || 256;\n histogram = histogram || 'min-pop';\n let histogramID;\n switch (histogram) {\n case 'min-pop':\n histogramID = 2;\n break;\n\n case 'top-pop':\n histogramID = 1;\n break\n\n default:\n throw new Error(`Invalid quantizeSorokin histogram '${histogram}'`);\n }\n _quantize(imageOrImages, 'RGBQuant', maxColorIndexes, histogramID, dither);\n}\n\n/**\n * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Xiaolin Wu.\n * \n * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.\n * \n * The method may increase the number of colors if there are fewer than the provided maximum.\n * \n * @function quantizeWu\n * @memberof GifUtil\n * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.\n * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.\n * @param {number} significantBits (optional) This is the number of significant high bits in each RGB color channel. Takes integer values from 1 through 8. Higher values correspond to higher quality. Defaults to 5.\n * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`.\n */\n\nexports.quantizeWu = function (imageOrImages, maxColorIndexes, significantBits, dither) {\n maxColorIndexes = maxColorIndexes || 256;\n significantBits = significantBits || 5;\n if (significantBits < 1 || significantBits > 8) {\n throw new Error(\"Invalid quantization quality\");\n }\n _quantize(imageOrImages, 'WuQuant', maxColorIndexes, significantBits, dither);\n}\n\n/**\n * read() decodes an encoded GIF, whether provided as a filename or as a byte buffer.\n * \n * @function read\n * @memberof GifUtil\n * @param {string|Buffer} source Source to decode. When a string, it's the GIF filename to load and parse. When a Buffer, it's an encoded GIF to parse.\n * @param {object} decoder An optional GIF decoder object implementing the `decode` method of class GifCodec. When provided, the method decodes the GIF using this decoder. When not provided, the method uses GifCodec.\n * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the decoded GIF.\n */\n\nexports.read = function (source, decoder) {\n decoder = decoder || defaultCodec;\n if (Buffer.isBuffer(source)) {\n return decoder.decodeGif(source);\n }\n return _readBinary(source)\n .then(buffer => {\n\n return decoder.decodeGif(buffer);\n });\n};\n\n/**\n * shareAsJimp() returns a Jimp that shares a bitmap with the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the image in either the Jimp or the BitmapImage affects the other objects. This method serves as a macro for simplifying working with Jimp.\n *\n * @function shareAsJimp\n * @memberof GifUtil\n * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp.\n * @param {bitmapImageToShare} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp.\n * @return {object} An new instance of Jimp that shares the image in bitmapImageToShare.\n */\n \nexports.shareAsJimp = function (jimp, bitmapImageToShare) {\n const jimpImage = new jimp(bitmapImageToShare.bitmap.width,\n bitmapImageToShare.bitmap.height, 0);\n jimpImage.bitmap.data = bitmapImageToShare.bitmap.data;\n return jimpImage;\n};\n\n/**\n * write() encodes a GIF and saves it as a file.\n * \n * @function write\n * @memberof GifUtil\n * @param {string} path Filename to write GIF out as. Will overwrite an existing file.\n * @param {GifFrame[]} frames Array of frames to be written into GIF.\n * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred.\n * @param {object} encoder An optional GIF encoder object implementing the `encode` method of class GifCodec. When provided, the method encodes the GIF using this encoder. When not provided, the method uses GifCodec.\n * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.\n */\n\nexports.write = function (path, frames, spec, encoder) {\n encoder = encoder || defaultCodec;\n const matches = path.match(/\\.[a-zA-Z]+$/); // prevent accidents\n if (matches !== null &&\n INVALID_SUFFIXES.includes(matches[0].toLowerCase()))\n {\n throw new Error(`GIF '${path}' has an unexpected suffix`);\n }\n\n return encoder.encodeGif(frames, spec)\n .then(gif => {\n\n return _writeBinary(path, gif.buffer)\n .then(() => {\n\n return gif;\n });\n });\n};\n\nfunction _quantize(imageOrImages, method, maxColorIndexes, modifier, dither) {\n const images = Array.isArray(imageOrImages) ? imageOrImages : [imageOrImages];\n const ditherAlgs = [\n 'FloydSteinberg',\n 'FalseFloydSteinberg',\n 'Stucki',\n 'Atkinson',\n 'Jarvis',\n 'Burkes',\n 'Sierra',\n 'TwoSierra',\n 'SierraLite'\n ];\n\n if (dither) {\n if (ditherAlgs.indexOf(dither.ditherAlgorithm) < 0) {\n throw new Error(`Invalid ditherAlgorithm '${dither.ditherAlgorithm}'`);\n }\n if (dither.serpentine === undefined) {\n dither.serpentine = true;\n }\n if (dither.minimumColorDistanceToDither === undefined) {\n dither.minimumColorDistanceToDither = 0;\n }\n if (dither.calculateErrorLikeGIMP === undefined) {\n dither.calculateErrorLikeGIMP = false;\n }\n }\n\n const distCalculator = new ImageQ.distance.Euclidean();\n const quantizer = new ImageQ.palette[method](distCalculator, maxColorIndexes, modifier);\n let imageMaker;\n if (dither) {\n imageMaker = new ImageQ.image.ErrorDiffusionArray(\n distCalculator,\n ImageQ.image.ErrorDiffusionArrayKernel[dither.ditherAlgorithm],\n dither.serpentine,\n dither.minimumColorDistanceToDither,\n dither.calculateErrorLikeGIMP\n );\n }\n else {\n imageMaker = new ImageQ.image.NearestColor(distCalculator);\n }\n\n const inputContainers = [];\n images.forEach(image => {\n\n const imageBuf = image.bitmap.data;\n const inputBuf = new ArrayBuffer(imageBuf.length);\n const inputArray = new Uint32Array(inputBuf);\n for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) {\n inputArray[ai] = imageBuf.readUInt32LE(bi, true);\n }\n const inputContainer = ImageQ.utils.PointContainer.fromUint32Array(\n inputArray, image.bitmap.width, image.bitmap.height);\n quantizer.sample(inputContainer);\n inputContainers.push(inputContainer);\n });\n \n const limitedPalette = quantizer.quantizeSync();\n\n for (let i = 0; i < images.length; ++i) {\n const imageBuf = images[i].bitmap.data;\n const outputContainer = imageMaker.quantizeSync(inputContainers[i], limitedPalette);\n const outputArray = outputContainer.toUint32Array();\n for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) {\n imageBuf.writeUInt32LE(outputArray[ai], bi);\n }\n }\n}\n\nfunction _readBinary(path) {\n // TBD: add support for URLs\n return new Promise((resolve, reject) => {\n\n fs.readFile(path, (err, buffer) => {\n\n if (err) {\n return reject(err);\n }\n return resolve(buffer);\n });\n });\n}\n\nfunction _writeBinary(path, buffer) {\n // TBD: add support for URLs\n return new Promise((resolve, reject) => {\n\n fs.writeFile(path, buffer, err => {\n \n if (err) {\n return reject(err);\n }\n return resolve();\n });\n });\n}\n","'use strict';\n\nconst BitmapImage = require('./bitmapimage');\nconst { Gif, GifError } = require('./gif');\nconst { GifCodec } = require('./gifcodec');\nconst { GifFrame } = require('./gifframe');\nconst GifUtil = require('./gifutil');\n\nmodule.exports = {\n BitmapImage,\n Gif,\n GifCodec,\n GifFrame,\n GifUtil,\n GifError\n};\n","var win;\n\nif (typeof window !== \"undefined\") {\n win = window;\n} else if (typeof global !== \"undefined\") {\n win = global;\n} else if (typeof self !== \"undefined\"){\n win = self;\n} else {\n win = {};\n}\n\nmodule.exports = win;\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","'use strict';\n\nvar fnToStr = Function.prototype.toString;\n\nvar constructorRegex = /^\\s*class\\b/;\nvar isES6ClassFn = function isES6ClassFunction(value) {\n\ttry {\n\t\tvar fnStr = fnToStr.call(value);\n\t\treturn constructorRegex.test(fnStr);\n\t} catch (e) {\n\t\treturn false; // not a function\n\t}\n};\n\nvar tryFunctionObject = function tryFunctionToStr(value) {\n\ttry {\n\t\tif (isES6ClassFn(value)) { return false; }\n\t\tfnToStr.call(value);\n\t\treturn true;\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\nvar toStr = Object.prototype.toString;\nvar fnClass = '[object Function]';\nvar genClass = '[object GeneratorFunction]';\nvar hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';\n\nmodule.exports = function isCallable(value) {\n\tif (!value) { return false; }\n\tif (typeof value !== 'function' && typeof value !== 'object') { return false; }\n\tif (typeof value === 'function' && !value.prototype) { return true; }\n\tif (hasToStringTag) { return tryFunctionObject(value); }\n\tif (isES6ClassFn(value)) { return false; }\n\tvar strClass = toStr.call(value);\n\treturn strClass === fnClass || strClass === genClass;\n};\n","module.exports = isFunction\n\nvar toString = Object.prototype.toString\n\nfunction isFunction (fn) {\n var string = toString.call(fn)\n return string === '[object Function]' ||\n (typeof fn === 'function' && string !== '[object RegExp]') ||\n (typeof window !== 'undefined' &&\n // IE8 and below\n (fn === window.setTimeout ||\n fn === window.alert ||\n fn === window.confirm ||\n fn === window.prompt))\n};\n","// the whatwg-fetch polyfill installs the fetch() function\n// on the global object (window or self)\n//\n// Return that as the export for use in Webpack, Browserify etc.\nrequire('whatwg-fetch');\nmodule.exports = self.fetch.bind(self);\n","var encode = require('./lib/encoder'),\n decode = require('./lib/decoder');\n\nmodule.exports = {\n encode: encode,\n decode: decode\n};\n","/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /\n/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */\n/*\n Copyright 2011 notmasteryet\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// - The JPEG specification can be found in the ITU CCITT Recommendation T.81\n// (www.w3.org/Graphics/JPEG/itu-t81.pdf)\n// - The JFIF specification can be found in the JPEG File Interchange Format\n// (www.w3.org/Graphics/JPEG/jfif3.pdf)\n// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters\n// in PostScript Level 2, Technical Note #5116\n// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)\n\nvar JpegImage = (function jpegImage() {\n \"use strict\";\n var dctZigZag = new Int32Array([\n 0,\n 1, 8,\n 16, 9, 2,\n 3, 10, 17, 24,\n 32, 25, 18, 11, 4,\n 5, 12, 19, 26, 33, 40,\n 48, 41, 34, 27, 20, 13, 6,\n 7, 14, 21, 28, 35, 42, 49, 56,\n 57, 50, 43, 36, 29, 22, 15,\n 23, 30, 37, 44, 51, 58,\n 59, 52, 45, 38, 31,\n 39, 46, 53, 60,\n 61, 54, 47,\n 55, 62,\n 63\n ]);\n\n var dctCos1 = 4017 // cos(pi/16)\n var dctSin1 = 799 // sin(pi/16)\n var dctCos3 = 3406 // cos(3*pi/16)\n var dctSin3 = 2276 // sin(3*pi/16)\n var dctCos6 = 1567 // cos(6*pi/16)\n var dctSin6 = 3784 // sin(6*pi/16)\n var dctSqrt2 = 5793 // sqrt(2)\n var dctSqrt1d2 = 2896 // sqrt(2) / 2\n\n function constructor() {\n }\n\n function buildHuffmanTable(codeLengths, values) {\n var k = 0, code = [], i, j, length = 16;\n while (length > 0 && !codeLengths[length - 1])\n length--;\n code.push({children: [], index: 0});\n var p = code[0], q;\n for (i = 0; i < length; i++) {\n for (j = 0; j < codeLengths[i]; j++) {\n p = code.pop();\n p.children[p.index] = values[k];\n while (p.index > 0) {\n if (code.length === 0)\n throw new Error('Could not recreate Huffman Table');\n p = code.pop();\n }\n p.index++;\n code.push(p);\n while (code.length <= i) {\n code.push(q = {children: [], index: 0});\n p.children[p.index] = q.children;\n p = q;\n }\n k++;\n }\n if (i + 1 < length) {\n // p here points to last code\n code.push(q = {children: [], index: 0});\n p.children[p.index] = q.children;\n p = q;\n }\n }\n return code[0].children;\n }\n\n function decodeScan(data, offset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successivePrev, successive, opts) {\n var precision = frame.precision;\n var samplesPerLine = frame.samplesPerLine;\n var scanLines = frame.scanLines;\n var mcusPerLine = frame.mcusPerLine;\n var progressive = frame.progressive;\n var maxH = frame.maxH, maxV = frame.maxV;\n\n var startOffset = offset, bitsData = 0, bitsCount = 0;\n function readBit() {\n if (bitsCount > 0) {\n bitsCount--;\n return (bitsData >> bitsCount) & 1;\n }\n bitsData = data[offset++];\n if (bitsData == 0xFF) {\n var nextByte = data[offset++];\n if (nextByte) {\n throw new Error(\"unexpected marker: \" + ((bitsData << 8) | nextByte).toString(16));\n }\n // unstuff 0\n }\n bitsCount = 7;\n return bitsData >>> 7;\n }\n function decodeHuffman(tree) {\n var node = tree, bit;\n while ((bit = readBit()) !== null) {\n node = node[bit];\n if (typeof node === 'number')\n return node;\n if (typeof node !== 'object')\n throw new Error(\"invalid huffman sequence\");\n }\n return null;\n }\n function receive(length) {\n var n = 0;\n while (length > 0) {\n var bit = readBit();\n if (bit === null) return;\n n = (n << 1) | bit;\n length--;\n }\n return n;\n }\n function receiveAndExtend(length) {\n var n = receive(length);\n if (n >= 1 << (length - 1))\n return n;\n return n + (-1 << length) + 1;\n }\n function decodeBaseline(component, zz) {\n var t = decodeHuffman(component.huffmanTableDC);\n var diff = t === 0 ? 0 : receiveAndExtend(t);\n zz[0]= (component.pred += diff);\n var k = 1;\n while (k < 64) {\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15)\n break;\n k += 16;\n continue;\n }\n k += r;\n var z = dctZigZag[k];\n zz[z] = receiveAndExtend(s);\n k++;\n }\n }\n function decodeDCFirst(component, zz) {\n var t = decodeHuffman(component.huffmanTableDC);\n var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);\n zz[0] = (component.pred += diff);\n }\n function decodeDCSuccessive(component, zz) {\n zz[0] |= readBit() << successive;\n }\n var eobrun = 0;\n function decodeACFirst(component, zz) {\n if (eobrun > 0) {\n eobrun--;\n return;\n }\n var k = spectralStart, e = spectralEnd;\n while (k <= e) {\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r) - 1;\n break;\n }\n k += 16;\n continue;\n }\n k += r;\n var z = dctZigZag[k];\n zz[z] = receiveAndExtend(s) * (1 << successive);\n k++;\n }\n }\n var successiveACState = 0, successiveACNextValue;\n function decodeACSuccessive(component, zz) {\n var k = spectralStart, e = spectralEnd, r = 0;\n while (k <= e) {\n var z = dctZigZag[k];\n var direction = zz[z] < 0 ? -1 : 1;\n switch (successiveACState) {\n case 0: // initial state\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r);\n successiveACState = 4;\n } else {\n r = 16;\n successiveACState = 1;\n }\n } else {\n if (s !== 1)\n throw new Error(\"invalid ACn encoding\");\n successiveACNextValue = receiveAndExtend(s);\n successiveACState = r ? 2 : 3;\n }\n continue;\n case 1: // skipping r zero items\n case 2:\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n else {\n r--;\n if (r === 0)\n successiveACState = successiveACState == 2 ? 3 : 0;\n }\n break;\n case 3: // set value for a zero item\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n else {\n zz[z] = successiveACNextValue << successive;\n successiveACState = 0;\n }\n break;\n case 4: // eob\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n break;\n }\n k++;\n }\n if (successiveACState === 4) {\n eobrun--;\n if (eobrun === 0)\n successiveACState = 0;\n }\n }\n function decodeMcu(component, decode, mcu, row, col) {\n var mcuRow = (mcu / mcusPerLine) | 0;\n var mcuCol = mcu % mcusPerLine;\n var blockRow = mcuRow * component.v + row;\n var blockCol = mcuCol * component.h + col;\n // If the block is missing and we're in tolerant mode, just skip it.\n if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)\n return;\n decode(component, component.blocks[blockRow][blockCol]);\n }\n function decodeBlock(component, decode, mcu) {\n var blockRow = (mcu / component.blocksPerLine) | 0;\n var blockCol = mcu % component.blocksPerLine;\n // If the block is missing and we're in tolerant mode, just skip it.\n if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)\n return;\n decode(component, component.blocks[blockRow][blockCol]);\n }\n\n var componentsLength = components.length;\n var component, i, j, k, n;\n var decodeFn;\n if (progressive) {\n if (spectralStart === 0)\n decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;\n else\n decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;\n } else {\n decodeFn = decodeBaseline;\n }\n\n var mcu = 0, marker;\n var mcuExpected;\n if (componentsLength == 1) {\n mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;\n } else {\n mcuExpected = mcusPerLine * frame.mcusPerColumn;\n }\n if (!resetInterval) resetInterval = mcuExpected;\n\n var h, v;\n while (mcu < mcuExpected) {\n // reset interval stuff\n for (i = 0; i < componentsLength; i++)\n components[i].pred = 0;\n eobrun = 0;\n\n if (componentsLength == 1) {\n component = components[0];\n for (n = 0; n < resetInterval; n++) {\n decodeBlock(component, decodeFn, mcu);\n mcu++;\n }\n } else {\n for (n = 0; n < resetInterval; n++) {\n for (i = 0; i < componentsLength; i++) {\n component = components[i];\n h = component.h;\n v = component.v;\n for (j = 0; j < v; j++) {\n for (k = 0; k < h; k++) {\n decodeMcu(component, decodeFn, mcu, j, k);\n }\n }\n }\n mcu++;\n\n // If we've reached our expected MCU's, stop decoding\n if (mcu === mcuExpected) break;\n }\n }\n\n if (mcu === mcuExpected) {\n // Skip trailing bytes at the end of the scan - until we reach the next marker\n do {\n if (data[offset] === 0xFF) {\n if (data[offset + 1] !== 0x00) {\n break;\n }\n }\n offset += 1;\n } while (offset < data.length - 2);\n }\n\n // find marker\n bitsCount = 0;\n marker = (data[offset] << 8) | data[offset + 1];\n if (marker < 0xFF00) {\n throw new Error(\"marker was not found\");\n }\n\n if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx\n offset += 2;\n }\n else\n break;\n }\n\n return offset - startOffset;\n }\n\n function buildComponentData(frame, component) {\n var lines = [];\n var blocksPerLine = component.blocksPerLine;\n var blocksPerColumn = component.blocksPerColumn;\n var samplesPerLine = blocksPerLine << 3;\n // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.\n var R = new Int32Array(64), r = new Uint8Array(64);\n\n // A port of poppler's IDCT method which in turn is taken from:\n // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,\n // \"Practical Fast 1-D DCT Algorithms with 11 Multiplications\",\n // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,\n // 988-991.\n function quantizeAndInverse(zz, dataOut, dataIn) {\n var qt = component.quantizationTable;\n var v0, v1, v2, v3, v4, v5, v6, v7, t;\n var p = dataIn;\n var i;\n\n // dequant\n for (i = 0; i < 64; i++)\n p[i] = zz[i] * qt[i];\n\n // inverse DCT on rows\n for (i = 0; i < 8; ++i) {\n var row = 8 * i;\n\n // check for all-zero AC coefficients\n if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&\n p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&\n p[7 + row] == 0) {\n t = (dctSqrt2 * p[0 + row] + 512) >> 10;\n p[0 + row] = t;\n p[1 + row] = t;\n p[2 + row] = t;\n p[3 + row] = t;\n p[4 + row] = t;\n p[5 + row] = t;\n p[6 + row] = t;\n p[7 + row] = t;\n continue;\n }\n\n // stage 4\n v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;\n v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;\n v2 = p[2 + row];\n v3 = p[6 + row];\n v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;\n v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;\n v5 = p[3 + row] << 4;\n v6 = p[5 + row] << 4;\n\n // stage 3\n t = (v0 - v1+ 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;\n v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;\n v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;\n v7 = t;\n t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;\n v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0 + row] = v0 + v7;\n p[7 + row] = v0 - v7;\n p[1 + row] = v1 + v6;\n p[6 + row] = v1 - v6;\n p[2 + row] = v2 + v5;\n p[5 + row] = v2 - v5;\n p[3 + row] = v3 + v4;\n p[4 + row] = v3 - v4;\n }\n\n // inverse DCT on columns\n for (i = 0; i < 8; ++i) {\n var col = i;\n\n // check for all-zero AC coefficients\n if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&\n p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&\n p[7*8 + col] == 0) {\n t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;\n p[0*8 + col] = t;\n p[1*8 + col] = t;\n p[2*8 + col] = t;\n p[3*8 + col] = t;\n p[4*8 + col] = t;\n p[5*8 + col] = t;\n p[6*8 + col] = t;\n p[7*8 + col] = t;\n continue;\n }\n\n // stage 4\n v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;\n v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;\n v2 = p[2*8 + col];\n v3 = p[6*8 + col];\n v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;\n v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;\n v5 = p[3*8 + col];\n v6 = p[5*8 + col];\n\n // stage 3\n t = (v0 - v1 + 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;\n v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;\n v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;\n v7 = t;\n t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;\n v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0*8 + col] = v0 + v7;\n p[7*8 + col] = v0 - v7;\n p[1*8 + col] = v1 + v6;\n p[6*8 + col] = v1 - v6;\n p[2*8 + col] = v2 + v5;\n p[5*8 + col] = v2 - v5;\n p[3*8 + col] = v3 + v4;\n p[4*8 + col] = v3 - v4;\n }\n\n // convert to 8-bit integers\n for (i = 0; i < 64; ++i) {\n var sample = 128 + ((p[i] + 8) >> 4);\n dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;\n }\n }\n\n requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);\n\n var i, j;\n for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {\n var scanLine = blockRow << 3;\n for (i = 0; i < 8; i++)\n lines.push(new Uint8Array(samplesPerLine));\n for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {\n quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);\n\n var offset = 0, sample = blockCol << 3;\n for (j = 0; j < 8; j++) {\n var line = lines[scanLine + j];\n for (i = 0; i < 8; i++)\n line[sample + i] = r[offset++];\n }\n }\n }\n return lines;\n }\n\n function clampTo8bit(a) {\n return a < 0 ? 0 : a > 255 ? 255 : a;\n }\n\n constructor.prototype = {\n load: function load(path) {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", path, true);\n xhr.responseType = \"arraybuffer\";\n xhr.onload = (function() {\n // TODO catch parse error\n var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);\n this.parse(data);\n if (this.onload)\n this.onload();\n }).bind(this);\n xhr.send(null);\n },\n parse: function parse(data) {\n var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;\n var offset = 0, length = data.length;\n function readUint16() {\n var value = (data[offset] << 8) | data[offset + 1];\n offset += 2;\n return value;\n }\n function readDataBlock() {\n var length = readUint16();\n var array = data.subarray(offset, offset + length - 2);\n offset += array.length;\n return array;\n }\n function prepareComponents(frame) {\n // According to the JPEG standard, the sampling factor must be between 1 and 4\n // See https://github.com/libjpeg-turbo/libjpeg-turbo/blob/9abeff46d87bd201a952e276f3e4339556a403a3/libjpeg.txt#L1138-L1146\n var maxH = 1, maxV = 1;\n var component, componentId;\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n if (maxH < component.h) maxH = component.h;\n if (maxV < component.v) maxV = component.v;\n }\n }\n var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);\n var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);\n var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);\n var blocksPerLineForMcu = mcusPerLine * component.h;\n var blocksPerColumnForMcu = mcusPerColumn * component.v;\n var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;\n var blocks = [];\n\n // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)\n requestMemoryAllocation(blocksToAllocate * 256);\n\n for (var i = 0; i < blocksPerColumnForMcu; i++) {\n var row = [];\n for (var j = 0; j < blocksPerLineForMcu; j++)\n row.push(new Int32Array(64));\n blocks.push(row);\n }\n component.blocksPerLine = blocksPerLine;\n component.blocksPerColumn = blocksPerColumn;\n component.blocks = blocks;\n }\n }\n frame.maxH = maxH;\n frame.maxV = maxV;\n frame.mcusPerLine = mcusPerLine;\n frame.mcusPerColumn = mcusPerColumn;\n }\n var jfif = null;\n var adobe = null;\n var pixels = null;\n var frame, resetInterval;\n var quantizationTables = [], frames = [];\n var huffmanTablesAC = [], huffmanTablesDC = [];\n var fileMarker = readUint16();\n var malformedDataOffset = -1;\n this.comments = [];\n if (fileMarker != 0xFFD8) { // SOI (Start of Image)\n throw new Error(\"SOI not found\");\n }\n\n fileMarker = readUint16();\n while (fileMarker != 0xFFD9) { // EOI (End of image)\n var i, j, l;\n switch(fileMarker) {\n case 0xFF00: break;\n case 0xFFE0: // APP0 (Application Specific)\n case 0xFFE1: // APP1\n case 0xFFE2: // APP2\n case 0xFFE3: // APP3\n case 0xFFE4: // APP4\n case 0xFFE5: // APP5\n case 0xFFE6: // APP6\n case 0xFFE7: // APP7\n case 0xFFE8: // APP8\n case 0xFFE9: // APP9\n case 0xFFEA: // APP10\n case 0xFFEB: // APP11\n case 0xFFEC: // APP12\n case 0xFFED: // APP13\n case 0xFFEE: // APP14\n case 0xFFEF: // APP15\n case 0xFFFE: // COM (Comment)\n var appData = readDataBlock();\n\n if (fileMarker === 0xFFFE) {\n var comment = String.fromCharCode.apply(null, appData);\n this.comments.push(comment);\n }\n\n if (fileMarker === 0xFFE0) {\n if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&\n appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\\x00'\n jfif = {\n version: { major: appData[5], minor: appData[6] },\n densityUnits: appData[7],\n xDensity: (appData[8] << 8) | appData[9],\n yDensity: (appData[10] << 8) | appData[11],\n thumbWidth: appData[12],\n thumbHeight: appData[13],\n thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])\n };\n }\n }\n // TODO APP1 - Exif\n if (fileMarker === 0xFFE1) {\n if (appData[0] === 0x45 &&\n appData[1] === 0x78 &&\n appData[2] === 0x69 &&\n appData[3] === 0x66 &&\n appData[4] === 0) { // 'EXIF\\x00'\n this.exifBuffer = appData.subarray(5, appData.length);\n }\n }\n\n if (fileMarker === 0xFFEE) {\n if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&\n appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\\x00'\n adobe = {\n version: appData[6],\n flags0: (appData[7] << 8) | appData[8],\n flags1: (appData[9] << 8) | appData[10],\n transformCode: appData[11]\n };\n }\n }\n break;\n\n case 0xFFDB: // DQT (Define Quantization Tables)\n var quantizationTablesLength = readUint16();\n var quantizationTablesEnd = quantizationTablesLength + offset - 2;\n while (offset < quantizationTablesEnd) {\n var quantizationTableSpec = data[offset++];\n requestMemoryAllocation(64 * 4);\n var tableData = new Int32Array(64);\n if ((quantizationTableSpec >> 4) === 0) { // 8 bit values\n for (j = 0; j < 64; j++) {\n var z = dctZigZag[j];\n tableData[z] = data[offset++];\n }\n } else if ((quantizationTableSpec >> 4) === 1) { //16 bit\n for (j = 0; j < 64; j++) {\n var z = dctZigZag[j];\n tableData[z] = readUint16();\n }\n } else\n throw new Error(\"DQT: invalid table spec\");\n quantizationTables[quantizationTableSpec & 15] = tableData;\n }\n break;\n\n case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)\n case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)\n case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)\n readUint16(); // skip data length\n frame = {};\n frame.extended = (fileMarker === 0xFFC1);\n frame.progressive = (fileMarker === 0xFFC2);\n frame.precision = data[offset++];\n frame.scanLines = readUint16();\n frame.samplesPerLine = readUint16();\n frame.components = {};\n frame.componentsOrder = [];\n\n var pixelsInFrame = frame.scanLines * frame.samplesPerLine;\n if (pixelsInFrame > maxResolutionInPixels) {\n var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);\n throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);\n }\n\n var componentsCount = data[offset++], componentId;\n var maxH = 0, maxV = 0;\n for (i = 0; i < componentsCount; i++) {\n componentId = data[offset];\n var h = data[offset + 1] >> 4;\n var v = data[offset + 1] & 15;\n var qId = data[offset + 2];\n\n if ( h <= 0 || v <= 0 ) {\n throw new Error('Invalid sampling factor, expected values above 0');\n }\n\n frame.componentsOrder.push(componentId);\n frame.components[componentId] = {\n h: h,\n v: v,\n quantizationIdx: qId\n };\n offset += 3;\n }\n prepareComponents(frame);\n frames.push(frame);\n break;\n\n case 0xFFC4: // DHT (Define Huffman Tables)\n var huffmanLength = readUint16();\n for (i = 2; i < huffmanLength;) {\n var huffmanTableSpec = data[offset++];\n var codeLengths = new Uint8Array(16);\n var codeLengthSum = 0;\n for (j = 0; j < 16; j++, offset++) {\n codeLengthSum += (codeLengths[j] = data[offset]);\n }\n requestMemoryAllocation(16 + codeLengthSum);\n var huffmanValues = new Uint8Array(codeLengthSum);\n for (j = 0; j < codeLengthSum; j++, offset++)\n huffmanValues[j] = data[offset];\n i += 17 + codeLengthSum;\n\n ((huffmanTableSpec >> 4) === 0 ?\n huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =\n buildHuffmanTable(codeLengths, huffmanValues);\n }\n break;\n\n case 0xFFDD: // DRI (Define Restart Interval)\n readUint16(); // skip data length\n resetInterval = readUint16();\n break;\n\n case 0xFFDC: // Number of Lines marker\n readUint16() // skip data length\n readUint16() // Ignore this data since it represents the image height\n break;\n \n case 0xFFDA: // SOS (Start of Scan)\n var scanLength = readUint16();\n var selectorsCount = data[offset++];\n var components = [], component;\n for (i = 0; i < selectorsCount; i++) {\n component = frame.components[data[offset++]];\n var tableSpec = data[offset++];\n component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];\n component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];\n components.push(component);\n }\n var spectralStart = data[offset++];\n var spectralEnd = data[offset++];\n var successiveApproximation = data[offset++];\n var processed = decodeScan(data, offset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successiveApproximation >> 4, successiveApproximation & 15, this.opts);\n offset += processed;\n break;\n\n case 0xFFFF: // Fill bytes\n if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.\n offset--;\n }\n break;\n default:\n if (data[offset - 3] == 0xFF &&\n data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {\n // could be incorrect encoding -- last 0xFF byte of the previous\n // block was eaten by the encoder\n offset -= 3;\n break;\n }\n else if (fileMarker === 0xE0 || fileMarker == 0xE1) {\n // Recover from malformed APP1 markers popular in some phone models.\n // See https://github.com/eugeneware/jpeg-js/issues/82\n if (malformedDataOffset !== -1) {\n throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);\n }\n malformedDataOffset = offset - 1;\n const nextOffset = readUint16();\n if (data[offset + nextOffset - 2] === 0xFF) {\n offset += nextOffset - 2;\n break;\n }\n }\n throw new Error(\"unknown JPEG marker \" + fileMarker.toString(16));\n }\n fileMarker = readUint16();\n }\n if (frames.length != 1)\n throw new Error(\"only single frame JPEGs supported\");\n\n // set each frame's components quantization table\n for (var i = 0; i < frames.length; i++) {\n var cp = frames[i].components;\n for (var j in cp) {\n cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];\n delete cp[j].quantizationIdx;\n }\n }\n\n this.width = frame.samplesPerLine;\n this.height = frame.scanLines;\n this.jfif = jfif;\n this.adobe = adobe;\n this.components = [];\n for (var i = 0; i < frame.componentsOrder.length; i++) {\n var component = frame.components[frame.componentsOrder[i]];\n this.components.push({\n lines: buildComponentData(frame, component),\n scaleX: component.h / frame.maxH,\n scaleY: component.v / frame.maxV\n });\n }\n },\n getData: function getData(width, height) {\n var scaleX = this.width / width, scaleY = this.height / height;\n\n var component1, component2, component3, component4;\n var component1Line, component2Line, component3Line, component4Line;\n var x, y;\n var offset = 0;\n var Y, Cb, Cr, K, C, M, Ye, R, G, B;\n var colorTransform;\n var dataLength = width * height * this.components.length;\n requestMemoryAllocation(dataLength);\n var data = new Uint8Array(dataLength);\n switch (this.components.length) {\n case 1:\n component1 = this.components[0];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n\n data[offset++] = Y;\n }\n }\n break;\n case 2:\n // PDF might compress two component data in custom colorspace\n component1 = this.components[0];\n component2 = this.components[1];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n data[offset++] = Y;\n Y = component2Line[0 | (x * component2.scaleX * scaleX)];\n data[offset++] = Y;\n }\n }\n break;\n case 3:\n // The default transform for three components is true\n colorTransform = true;\n // The adobe transform marker overrides any previous setting\n if (this.adobe && this.adobe.transformCode)\n colorTransform = true;\n else if (typeof this.opts.colorTransform !== 'undefined')\n colorTransform = !!this.opts.colorTransform;\n\n component1 = this.components[0];\n component2 = this.components[1];\n component3 = this.components[2];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n if (!colorTransform) {\n R = component1Line[0 | (x * component1.scaleX * scaleX)];\n G = component2Line[0 | (x * component2.scaleX * scaleX)];\n B = component3Line[0 | (x * component3.scaleX * scaleX)];\n } else {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n Cb = component2Line[0 | (x * component2.scaleX * scaleX)];\n Cr = component3Line[0 | (x * component3.scaleX * scaleX)];\n\n R = clampTo8bit(Y + 1.402 * (Cr - 128));\n G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));\n B = clampTo8bit(Y + 1.772 * (Cb - 128));\n }\n\n data[offset++] = R;\n data[offset++] = G;\n data[offset++] = B;\n }\n }\n break;\n case 4:\n if (!this.adobe)\n throw new Error('Unsupported color mode (4 components)');\n // The default transform for four components is false\n colorTransform = false;\n // The adobe transform marker overrides any previous setting\n if (this.adobe && this.adobe.transformCode)\n colorTransform = true;\n else if (typeof this.opts.colorTransform !== 'undefined')\n colorTransform = !!this.opts.colorTransform;\n\n component1 = this.components[0];\n component2 = this.components[1];\n component3 = this.components[2];\n component4 = this.components[3];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];\n component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n if (!colorTransform) {\n C = component1Line[0 | (x * component1.scaleX * scaleX)];\n M = component2Line[0 | (x * component2.scaleX * scaleX)];\n Ye = component3Line[0 | (x * component3.scaleX * scaleX)];\n K = component4Line[0 | (x * component4.scaleX * scaleX)];\n } else {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n Cb = component2Line[0 | (x * component2.scaleX * scaleX)];\n Cr = component3Line[0 | (x * component3.scaleX * scaleX)];\n K = component4Line[0 | (x * component4.scaleX * scaleX)];\n\n C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));\n M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));\n Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));\n }\n data[offset++] = 255-C;\n data[offset++] = 255-M;\n data[offset++] = 255-Ye;\n data[offset++] = 255-K;\n }\n }\n break;\n default:\n throw new Error('Unsupported color mode');\n }\n return data;\n },\n copyToImageData: function copyToImageData(imageData, formatAsRGBA) {\n var width = imageData.width, height = imageData.height;\n var imageDataArray = imageData.data;\n var data = this.getData(width, height);\n var i = 0, j = 0, x, y;\n var Y, K, C, M, R, G, B;\n switch (this.components.length) {\n case 1:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n Y = data[i++];\n\n imageDataArray[j++] = Y;\n imageDataArray[j++] = Y;\n imageDataArray[j++] = Y;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n case 3:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n R = data[i++];\n G = data[i++];\n B = data[i++];\n\n imageDataArray[j++] = R;\n imageDataArray[j++] = G;\n imageDataArray[j++] = B;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n case 4:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n C = data[i++];\n M = data[i++];\n Y = data[i++];\n K = data[i++];\n\n R = 255 - clampTo8bit(C * (1 - K / 255) + K);\n G = 255 - clampTo8bit(M * (1 - K / 255) + K);\n B = 255 - clampTo8bit(Y * (1 - K / 255) + K);\n\n imageDataArray[j++] = R;\n imageDataArray[j++] = G;\n imageDataArray[j++] = B;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n default:\n throw new Error('Unsupported color mode');\n }\n }\n };\n\n\n // We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content.\n var totalBytesAllocated = 0;\n var maxMemoryUsageBytes = 0;\n function requestMemoryAllocation(increaseAmount = 0) {\n var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;\n if (totalMemoryImpactBytes > maxMemoryUsageBytes) {\n var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);\n throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);\n }\n\n totalBytesAllocated = totalMemoryImpactBytes;\n }\n\n constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) {\n totalBytesAllocated = 0;\n maxMemoryUsageBytes = maxMemoryUsageBytes_;\n };\n\n constructor.getBytesAllocated = function () {\n return totalBytesAllocated;\n };\n\n constructor.requestMemoryAllocation = requestMemoryAllocation;\n\n return constructor;\n})();\n\nif (typeof module !== 'undefined') {\n\tmodule.exports = decode;\n} else if (typeof window !== 'undefined') {\n\twindow['jpeg-js'] = window['jpeg-js'] || {};\n\twindow['jpeg-js'].decode = decode;\n}\n\nfunction decode(jpegData, userOpts = {}) {\n var defaultOpts = {\n // \"undefined\" means \"Choose whether to transform colors based on the image’s color model.\"\n colorTransform: undefined,\n useTArray: false,\n formatAsRGBA: true,\n tolerantDecoding: true,\n maxResolutionInMP: 100, // Don't decode more than 100 megapixels\n maxMemoryUsageInMB: 512, // Don't decode if memory footprint is more than 512MB\n };\n\n var opts = {...defaultOpts, ...userOpts};\n var arr = new Uint8Array(jpegData);\n var decoder = new JpegImage();\n decoder.opts = opts;\n // If this constructor ever supports async decoding this will need to be done differently.\n // Until then, treating as singleton limit is fine.\n JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);\n decoder.parse(arr);\n\n var channels = (opts.formatAsRGBA) ? 4 : 3;\n var bytesNeeded = decoder.width * decoder.height * channels;\n try {\n JpegImage.requestMemoryAllocation(bytesNeeded);\n var image = {\n width: decoder.width,\n height: decoder.height,\n exifBuffer: decoder.exifBuffer,\n data: opts.useTArray ?\n new Uint8Array(bytesNeeded) :\n Buffer.alloc(bytesNeeded)\n };\n if(decoder.comments.length > 0) {\n image[\"comments\"] = decoder.comments;\n }\n } catch (err) {\n if (err instanceof RangeError) {\n throw new Error(\"Could not allocate enough memory for the image. \" +\n \"Required: \" + bytesNeeded);\n } \n \n if (err instanceof ReferenceError) {\n if (err.message === \"Buffer is not defined\") {\n throw new Error(\"Buffer is not globally defined in this environment. \" +\n \"Consider setting useTArray to true\");\n }\n }\n throw err;\n }\n\n decoder.copyToImageData(image, opts.formatAsRGBA);\n\n return image;\n}\n","/*\n Copyright (c) 2008, Adobe Systems Incorporated\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without \n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright notice, \n this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the \n documentation and/or other materials provided with the distribution.\n \n * Neither the name of Adobe Systems Incorporated nor the names of its \n contributors may be used to endorse or promote products derived from \n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR \n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*\nJPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009\n\nBasic GUI blocking jpeg encoder\n*/\n\nvar btoa = btoa || function(buf) {\n return Buffer.from(buf).toString('base64');\n};\n\nfunction JPEGEncoder(quality) {\n var self = this;\n\tvar fround = Math.round;\n\tvar ffloor = Math.floor;\n\tvar YTable = new Array(64);\n\tvar UVTable = new Array(64);\n\tvar fdtbl_Y = new Array(64);\n\tvar fdtbl_UV = new Array(64);\n\tvar YDC_HT;\n\tvar UVDC_HT;\n\tvar YAC_HT;\n\tvar UVAC_HT;\n\t\n\tvar bitcode = new Array(65535);\n\tvar category = new Array(65535);\n\tvar outputfDCTQuant = new Array(64);\n\tvar DU = new Array(64);\n\tvar byteout = [];\n\tvar bytenew = 0;\n\tvar bytepos = 7;\n\t\n\tvar YDU = new Array(64);\n\tvar UDU = new Array(64);\n\tvar VDU = new Array(64);\n\tvar clt = new Array(256);\n\tvar RGB_YUV_TABLE = new Array(2048);\n\tvar currentQuality;\n\t\n\tvar ZigZag = [\n\t\t\t 0, 1, 5, 6,14,15,27,28,\n\t\t\t 2, 4, 7,13,16,26,29,42,\n\t\t\t 3, 8,12,17,25,30,41,43,\n\t\t\t 9,11,18,24,31,40,44,53,\n\t\t\t10,19,23,32,39,45,52,54,\n\t\t\t20,22,33,38,46,51,55,60,\n\t\t\t21,34,37,47,50,56,59,61,\n\t\t\t35,36,48,49,57,58,62,63\n\t\t];\n\t\n\tvar std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];\n\tvar std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];\n\tvar std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];\n\tvar std_ac_luminance_values = [\n\t\t\t0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,\n\t\t\t0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,\n\t\t\t0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,\n\t\t\t0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,\n\t\t\t0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,\n\t\t\t0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,\n\t\t\t0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,\n\t\t\t0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,\n\t\t\t0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,\n\t\t\t0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,\n\t\t\t0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,\n\t\t\t0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,\n\t\t\t0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,\n\t\t\t0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,\n\t\t\t0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,\n\t\t\t0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,\n\t\t\t0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,\n\t\t\t0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,\n\t\t\t0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,\n\t\t\t0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,\n\t\t\t0xf9,0xfa\n\t\t];\n\t\n\tvar std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];\n\tvar std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];\n\tvar std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];\n\tvar std_ac_chrominance_values = [\n\t\t\t0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,\n\t\t\t0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,\n\t\t\t0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,\n\t\t\t0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,\n\t\t\t0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,\n\t\t\t0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,\n\t\t\t0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,\n\t\t\t0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,\n\t\t\t0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,\n\t\t\t0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,\n\t\t\t0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,\n\t\t\t0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,\n\t\t\t0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,\n\t\t\t0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,\n\t\t\t0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,\n\t\t\t0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,\n\t\t\t0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,\n\t\t\t0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,\n\t\t\t0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,\n\t\t\t0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,\n\t\t\t0xf9,0xfa\n\t\t];\n\t\n\tfunction initQuantTables(sf){\n\t\t\tvar YQT = [\n\t\t\t\t16, 11, 10, 16, 24, 40, 51, 61,\n\t\t\t\t12, 12, 14, 19, 26, 58, 60, 55,\n\t\t\t\t14, 13, 16, 24, 40, 57, 69, 56,\n\t\t\t\t14, 17, 22, 29, 51, 87, 80, 62,\n\t\t\t\t18, 22, 37, 56, 68,109,103, 77,\n\t\t\t\t24, 35, 55, 64, 81,104,113, 92,\n\t\t\t\t49, 64, 78, 87,103,121,120,101,\n\t\t\t\t72, 92, 95, 98,112,100,103, 99\n\t\t\t];\n\t\t\t\n\t\t\tfor (var i = 0; i < 64; i++) {\n\t\t\t\tvar t = ffloor((YQT[i]*sf+50)/100);\n\t\t\t\tif (t < 1) {\n\t\t\t\t\tt = 1;\n\t\t\t\t} else if (t > 255) {\n\t\t\t\t\tt = 255;\n\t\t\t\t}\n\t\t\t\tYTable[ZigZag[i]] = t;\n\t\t\t}\n\t\t\tvar UVQT = [\n\t\t\t\t17, 18, 24, 47, 99, 99, 99, 99,\n\t\t\t\t18, 21, 26, 66, 99, 99, 99, 99,\n\t\t\t\t24, 26, 56, 99, 99, 99, 99, 99,\n\t\t\t\t47, 66, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99\n\t\t\t];\n\t\t\tfor (var j = 0; j < 64; j++) {\n\t\t\t\tvar u = ffloor((UVQT[j]*sf+50)/100);\n\t\t\t\tif (u < 1) {\n\t\t\t\t\tu = 1;\n\t\t\t\t} else if (u > 255) {\n\t\t\t\t\tu = 255;\n\t\t\t\t}\n\t\t\t\tUVTable[ZigZag[j]] = u;\n\t\t\t}\n\t\t\tvar aasf = [\n\t\t\t\t1.0, 1.387039845, 1.306562965, 1.175875602,\n\t\t\t\t1.0, 0.785694958, 0.541196100, 0.275899379\n\t\t\t];\n\t\t\tvar k = 0;\n\t\t\tfor (var row = 0; row < 8; row++)\n\t\t\t{\n\t\t\t\tfor (var col = 0; col < 8; col++)\n\t\t\t\t{\n\t\t\t\t\tfdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));\n\t\t\t\t\tfdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction computeHuffmanTbl(nrcodes, std_table){\n\t\t\tvar codevalue = 0;\n\t\t\tvar pos_in_table = 0;\n\t\t\tvar HT = new Array();\n\t\t\tfor (var k = 1; k <= 16; k++) {\n\t\t\t\tfor (var j = 1; j <= nrcodes[k]; j++) {\n\t\t\t\t\tHT[std_table[pos_in_table]] = [];\n\t\t\t\t\tHT[std_table[pos_in_table]][0] = codevalue;\n\t\t\t\t\tHT[std_table[pos_in_table]][1] = k;\n\t\t\t\t\tpos_in_table++;\n\t\t\t\t\tcodevalue++;\n\t\t\t\t}\n\t\t\t\tcodevalue*=2;\n\t\t\t}\n\t\t\treturn HT;\n\t\t}\n\t\t\n\t\tfunction initHuffmanTbl()\n\t\t{\n\t\t\tYDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);\n\t\t\tUVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);\n\t\t\tYAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);\n\t\t\tUVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);\n\t\t}\n\t\n\t\tfunction initCategoryNumber()\n\t\t{\n\t\t\tvar nrlower = 1;\n\t\t\tvar nrupper = 2;\n\t\t\tfor (var cat = 1; cat <= 15; cat++) {\n\t\t\t\t//Positive numbers\n\t\t\t\tfor (var nr = nrlower; nr>0] \t= 38470 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+ 512)>>0] \t= 7471 * i + 0x8000;\n\t\t\t\tRGB_YUV_TABLE[(i+ 768)>>0] \t= -11059 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1024)>>0] \t= -21709 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1280)>>0] \t= 32768 * i + 0x807FFF;\n\t\t\t\tRGB_YUV_TABLE[(i+1536)>>0] \t= -27439 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1792)>>0] \t= - 5329 * i;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// IO functions\n\t\tfunction writeBits(bs)\n\t\t{\n\t\t\tvar value = bs[0];\n\t\t\tvar posval = bs[1]-1;\n\t\t\twhile ( posval >= 0 ) {\n\t\t\t\tif (value & (1 << posval) ) {\n\t\t\t\t\tbytenew |= (1 << bytepos);\n\t\t\t\t}\n\t\t\t\tposval--;\n\t\t\t\tbytepos--;\n\t\t\t\tif (bytepos < 0) {\n\t\t\t\t\tif (bytenew == 0xFF) {\n\t\t\t\t\t\twriteByte(0xFF);\n\t\t\t\t\t\twriteByte(0);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\twriteByte(bytenew);\n\t\t\t\t\t}\n\t\t\t\t\tbytepos=7;\n\t\t\t\t\tbytenew=0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeByte(value)\n\t\t{\n\t\t\t//byteout.push(clt[value]); // write char directly instead of converting later\n byteout.push(value);\n\t\t}\n\t\n\t\tfunction writeWord(value)\n\t\t{\n\t\t\twriteByte((value>>8)&0xFF);\n\t\t\twriteByte((value )&0xFF);\n\t\t}\n\t\t\n\t\t// DCT & quantization core\n\t\tfunction fDCTQuant(data, fdtbl)\n\t\t{\n\t\t\tvar d0, d1, d2, d3, d4, d5, d6, d7;\n\t\t\t/* Pass 1: process rows. */\n\t\t\tvar dataOff=0;\n\t\t\tvar i;\n\t\t\tvar I8 = 8;\n\t\t\tvar I64 = 64;\n\t\t\tfor (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);\n\t\t\t\t//outputfDCTQuant[i] = fround(fDCTQuant);\n\n\t\t\t}\n\t\t\treturn outputfDCTQuant;\n\t\t}\n\t\t\n\t\tfunction writeAPP0()\n\t\t{\n\t\t\twriteWord(0xFFE0); // marker\n\t\t\twriteWord(16); // length\n\t\t\twriteByte(0x4A); // J\n\t\t\twriteByte(0x46); // F\n\t\t\twriteByte(0x49); // I\n\t\t\twriteByte(0x46); // F\n\t\t\twriteByte(0); // = \"JFIF\",'\\0'\n\t\t\twriteByte(1); // versionhi\n\t\t\twriteByte(1); // versionlo\n\t\t\twriteByte(0); // xyunits\n\t\t\twriteWord(1); // xdensity\n\t\t\twriteWord(1); // ydensity\n\t\t\twriteByte(0); // thumbnwidth\n\t\t\twriteByte(0); // thumbnheight\n\t\t}\n\n\t\tfunction writeAPP1(exifBuffer) {\n\t\t\tif (!exifBuffer) return;\n\n\t\t\twriteWord(0xFFE1); // APP1 marker\n\n\t\t\tif (exifBuffer[0] === 0x45 &&\n\t\t\t\t\texifBuffer[1] === 0x78 &&\n\t\t\t\t\texifBuffer[2] === 0x69 &&\n\t\t\t\t\texifBuffer[3] === 0x66) {\n\t\t\t\t// Buffer already starts with EXIF, just use it directly\n\t\t\t\twriteWord(exifBuffer.length + 2); // length is buffer + length itself!\n\t\t\t} else {\n\t\t\t\t// Buffer doesn't start with EXIF, write it for them\n\t\t\t\twriteWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\\0 + length itself!\n\t\t\t\twriteByte(0x45); // E\n\t\t\t\twriteByte(0x78); // X\n\t\t\t\twriteByte(0x69); // I\n\t\t\t\twriteByte(0x66); // F\n\t\t\t\twriteByte(0); // = \"EXIF\",'\\0'\n\t\t\t}\n\n\t\t\tfor (var i = 0; i < exifBuffer.length; i++) {\n\t\t\t\twriteByte(exifBuffer[i]);\n\t\t\t}\n\t\t}\n\n\t\tfunction writeSOF0(width, height)\n\t\t{\n\t\t\twriteWord(0xFFC0); // marker\n\t\t\twriteWord(17); // length, truecolor YUV JPG\n\t\t\twriteByte(8); // precision\n\t\t\twriteWord(height);\n\t\t\twriteWord(width);\n\t\t\twriteByte(3); // nrofcomponents\n\t\t\twriteByte(1); // IdY\n\t\t\twriteByte(0x11); // HVY\n\t\t\twriteByte(0); // QTY\n\t\t\twriteByte(2); // IdU\n\t\t\twriteByte(0x11); // HVU\n\t\t\twriteByte(1); // QTU\n\t\t\twriteByte(3); // IdV\n\t\t\twriteByte(0x11); // HVV\n\t\t\twriteByte(1); // QTV\n\t\t}\n\t\n\t\tfunction writeDQT()\n\t\t{\n\t\t\twriteWord(0xFFDB); // marker\n\t\t\twriteWord(132);\t // length\n\t\t\twriteByte(0);\n\t\t\tfor (var i=0; i<64; i++) {\n\t\t\t\twriteByte(YTable[i]);\n\t\t\t}\n\t\t\twriteByte(1);\n\t\t\tfor (var j=0; j<64; j++) {\n\t\t\t\twriteByte(UVTable[j]);\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeDHT()\n\t\t{\n\t\t\twriteWord(0xFFC4); // marker\n\t\t\twriteWord(0x01A2); // length\n\t\n\t\t\twriteByte(0); // HTYDCinfo\n\t\t\tfor (var i=0; i<16; i++) {\n\t\t\t\twriteByte(std_dc_luminance_nrcodes[i+1]);\n\t\t\t}\n\t\t\tfor (var j=0; j<=11; j++) {\n\t\t\t\twriteByte(std_dc_luminance_values[j]);\n\t\t\t}\n\t\n\t\t\twriteByte(0x10); // HTYACinfo\n\t\t\tfor (var k=0; k<16; k++) {\n\t\t\t\twriteByte(std_ac_luminance_nrcodes[k+1]);\n\t\t\t}\n\t\t\tfor (var l=0; l<=161; l++) {\n\t\t\t\twriteByte(std_ac_luminance_values[l]);\n\t\t\t}\n\t\n\t\t\twriteByte(1); // HTUDCinfo\n\t\t\tfor (var m=0; m<16; m++) {\n\t\t\t\twriteByte(std_dc_chrominance_nrcodes[m+1]);\n\t\t\t}\n\t\t\tfor (var n=0; n<=11; n++) {\n\t\t\t\twriteByte(std_dc_chrominance_values[n]);\n\t\t\t}\n\t\n\t\t\twriteByte(0x11); // HTUACinfo\n\t\t\tfor (var o=0; o<16; o++) {\n\t\t\t\twriteByte(std_ac_chrominance_nrcodes[o+1]);\n\t\t\t}\n\t\t\tfor (var p=0; p<=161; p++) {\n\t\t\t\twriteByte(std_ac_chrominance_values[p]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction writeCOM(comments)\n\t\t{\n\t\t\tif (typeof comments === \"undefined\" || comments.constructor !== Array) return;\n\t\t\tcomments.forEach(e => {\n\t\t\t\tif (typeof e !== \"string\") return;\n\t\t\t\twriteWord(0xFFFE); // marker\n\t\t\t\tvar l = e.length;\n\t\t\t\twriteWord(l + 2); // length itself as well\n\t\t\t\tvar i;\n\t\t\t\tfor (i = 0; i < l; i++)\n\t\t\t\t\twriteByte(e.charCodeAt(i));\n\t\t\t});\n\t\t}\n\t\n\t\tfunction writeSOS()\n\t\t{\n\t\t\twriteWord(0xFFDA); // marker\n\t\t\twriteWord(12); // length\n\t\t\twriteByte(3); // nrofcomponents\n\t\t\twriteByte(1); // IdY\n\t\t\twriteByte(0); // HTY\n\t\t\twriteByte(2); // IdU\n\t\t\twriteByte(0x11); // HTU\n\t\t\twriteByte(3); // IdV\n\t\t\twriteByte(0x11); // HTV\n\t\t\twriteByte(0); // Ss\n\t\t\twriteByte(0x3f); // Se\n\t\t\twriteByte(0); // Bf\n\t\t}\n\t\t\n\t\tfunction processDU(CDU, fdtbl, DC, HTDC, HTAC){\n\t\t\tvar EOB = HTAC[0x00];\n\t\t\tvar M16zeroes = HTAC[0xF0];\n\t\t\tvar pos;\n\t\t\tvar I16 = 16;\n\t\t\tvar I63 = 63;\n\t\t\tvar I64 = 64;\n\t\t\tvar DU_DCT = fDCTQuant(CDU, fdtbl);\n\t\t\t//ZigZag reorder\n\t\t\tfor (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};\n\t\t\t//end0pos = first element in reverse order !=0\n\t\t\tif ( end0pos == 0) {\n\t\t\t\twriteBits(EOB);\n\t\t\t\treturn DC;\n\t\t\t}\n\t\t\tvar i = 1;\n\t\t\tvar lng;\n\t\t\twhile ( i <= end0pos ) {\n\t\t\t\tvar startpos = i;\n\t\t\t\tfor (; (DU[i]==0) && (i<=end0pos); ++i) {}\n\t\t\t\tvar nrzeroes = i-startpos;\n\t\t\t\tif ( nrzeroes >= I16 ) {\n\t\t\t\t\tlng = nrzeroes>>4;\n\t\t\t\t\tfor (var nrmarker=1; nrmarker <= lng; ++nrmarker)\n\t\t\t\t\t\twriteBits(M16zeroes);\n\t\t\t\t\tnrzeroes = nrzeroes&0xF;\n\t\t\t\t}\n\t\t\t\tpos = 32767+DU[i];\n\t\t\t\twriteBits(HTAC[(nrzeroes<<4)+category[pos]]);\n\t\t\t\twriteBits(bitcode[pos]);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif ( end0pos != I63 ) {\n\t\t\t\twriteBits(EOB);\n\t\t\t}\n\t\t\treturn DC;\n\t\t}\n\n\t\tfunction initCharLookupTable(){\n\t\t\tvar sfcc = String.fromCharCode;\n\t\t\tfor(var i=0; i < 256; i++){ ///// ACHTUNG // 255\n\t\t\t\tclt[i] = sfcc(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis.encode = function(image,quality) // image data object\n\t\t{\n\t\t\tvar time_start = new Date().getTime();\n\t\t\t\n\t\t\tif(quality) setQuality(quality);\n\t\t\t\n\t\t\t// Initialize bit writer\n\t\t\tbyteout = new Array();\n\t\t\tbytenew=0;\n\t\t\tbytepos=7;\n\t\n\t\t\t// Add JPEG headers\n\t\t\twriteWord(0xFFD8); // SOI\n\t\t\twriteAPP0();\n\t\t\twriteCOM(image.comments);\n\t\t\twriteAPP1(image.exifBuffer);\n\t\t\twriteDQT();\n\t\t\twriteSOF0(image.width,image.height);\n\t\t\twriteDHT();\n\t\t\twriteSOS();\n\n\t\n\t\t\t// Encode 8x8 macroblocks\n\t\t\tvar DCY=0;\n\t\t\tvar DCU=0;\n\t\t\tvar DCV=0;\n\t\t\t\n\t\t\tbytenew=0;\n\t\t\tbytepos=7;\n\t\t\t\n\t\t\t\n\t\t\tthis.encode.displayName = \"_encode_\";\n\n\t\t\tvar imageData = image.data;\n\t\t\tvar width = image.width;\n\t\t\tvar height = image.height;\n\n\t\t\tvar quadWidth = width*4;\n\t\t\tvar tripleWidth = width*3;\n\t\t\t\n\t\t\tvar x, y = 0;\n\t\t\tvar r, g, b;\n\t\t\tvar start,p, col,row,pos;\n\t\t\twhile(y < height){\n\t\t\t\tx = 0;\n\t\t\t\twhile(x < quadWidth){\n\t\t\t\tstart = quadWidth * y + x;\n\t\t\t\tp = start;\n\t\t\t\tcol = -1;\n\t\t\t\trow = 0;\n\t\t\t\t\n\t\t\t\tfor(pos=0; pos < 64; pos++){\n\t\t\t\t\trow = pos >> 3;// /8\n\t\t\t\t\tcol = ( pos & 7 ) * 4; // %8\n\t\t\t\t\tp = start + ( row * quadWidth ) + col;\t\t\n\t\t\t\t\t\n\t\t\t\t\tif(y+row >= height){ // padding bottom\n\t\t\t\t\t\tp-= (quadWidth*(y+1+row-height));\n\t\t\t\t\t}\n\n\t\t\t\t\tif(x+col >= quadWidth){ // padding right\t\n\t\t\t\t\t\tp-= ((x+col) - quadWidth +4)\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tr = imageData[ p++ ];\n\t\t\t\t\tg = imageData[ p++ ];\n\t\t\t\t\tb = imageData[ p++ ];\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t/* // calculate YUV values dynamically\n\t\t\t\t\tYDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80\n\t\t\t\t\tUDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));\n\t\t\t\t\tVDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));\n\t\t\t\t\t*/\n\t\t\t\t\t\n\t\t\t\t\t// use lookup table (slightly faster)\n\t\t\t\t\tYDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;\n\t\t\t\t\tUDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;\n\t\t\t\t\tVDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tDCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);\n\t\t\t\tDCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);\n\t\t\t\tDCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);\n\t\t\t\tx+=32;\n\t\t\t\t}\n\t\t\t\ty+=8;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t////////////////////////////////////////////////////////////////\n\t\n\t\t\t// Do the bit alignment of the EOI marker\n\t\t\tif ( bytepos >= 0 ) {\n\t\t\t\tvar fillbits = [];\n\t\t\t\tfillbits[1] = bytepos+1;\n\t\t\t\tfillbits[0] = (1<<(bytepos+1))-1;\n\t\t\t\twriteBits(fillbits);\n\t\t\t}\n\t\n\t\t\twriteWord(0xFFD9); //EOI\n\n\t\t\tif (typeof module === 'undefined') return new Uint8Array(byteout);\n return Buffer.from(byteout);\n\n\t\t\tvar jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));\n\t\t\t\n\t\t\tbyteout = [];\n\t\t\t\n\t\t\t// benchmarking\n\t\t\tvar duration = new Date().getTime() - time_start;\n \t\t//console.log('Encoding time: '+ duration + 'ms');\n \t\t//\n\t\t\t\n\t\t\treturn jpegDataUri\t\t\t\n\t}\n\t\n\tfunction setQuality(quality){\n\t\tif (quality <= 0) {\n\t\t\tquality = 1;\n\t\t}\n\t\tif (quality > 100) {\n\t\t\tquality = 100;\n\t\t}\n\t\t\n\t\tif(currentQuality == quality) return // don't recalc if unchanged\n\t\t\n\t\tvar sf = 0;\n\t\tif (quality < 50) {\n\t\t\tsf = Math.floor(5000 / quality);\n\t\t} else {\n\t\t\tsf = Math.floor(200 - quality*2);\n\t\t}\n\t\t\n\t\tinitQuantTables(sf);\n\t\tcurrentQuality = quality;\n\t\t//console.log('Quality set to: '+quality +'%');\n\t}\n\t\n\tfunction init(){\n\t\tvar time_start = new Date().getTime();\n\t\tif(!quality) quality = 50;\n\t\t// Create tables\n\t\tinitCharLookupTable()\n\t\tinitHuffmanTbl();\n\t\tinitCategoryNumber();\n\t\tinitRGBYUVTable();\n\t\t\n\t\tsetQuality(quality);\n\t\tvar duration = new Date().getTime() - time_start;\n \t//console.log('Initialization '+ duration + 'ms');\n\t}\n\t\n\tinit();\n\t\n};\n\nif (typeof module !== 'undefined') {\n\tmodule.exports = encode;\n} else if (typeof window !== 'undefined') {\n\twindow['jpeg-js'] = window['jpeg-js'] || {};\n\twindow['jpeg-js'].encode = encode;\n}\n\nfunction encode(imgData, qu) {\n if (typeof qu === 'undefined') qu = 50;\n var encoder = new JPEGEncoder(qu);\n\tvar data = encoder.encode(imgData, qu);\n return {\n data: data,\n width: imgData.width,\n height: imgData.height,\n };\n}\n\n// helper function to get the imageData of an existing image on the current page.\nfunction getImageDataFromImage(idOrElement){\n\tvar theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement;\n\tvar cvs = document.createElement('canvas');\n\tcvs.width = theImg.width;\n\tcvs.height = theImg.height;\n\tvar ctx = cvs.getContext(\"2d\");\n\tctx.drawImage(theImg,0,0);\n\t\n\treturn (ctx.getImageData(0, 0, cvs.width, cvs.height));\n}\n","var xhr = require('xhr')\nvar noop = function(){}\nvar parseASCII = require('parse-bmfont-ascii')\nvar parseXML = require('parse-bmfont-xml')\nvar readBinary = require('parse-bmfont-binary')\nvar isBinaryFormat = require('./lib/is-binary')\nvar xtend = require('xtend')\n\nvar xml2 = (function hasXML2() {\n return self.XMLHttpRequest && \"withCredentials\" in new XMLHttpRequest\n})()\n\nmodule.exports = function(opt, cb) {\n cb = typeof cb === 'function' ? cb : noop\n\n if (typeof opt === 'string')\n opt = { uri: opt }\n else if (!opt)\n opt = {}\n\n var expectBinary = opt.binary\n if (expectBinary)\n opt = getBinaryOpts(opt)\n\n xhr(opt, function(err, res, body) {\n if (err)\n return cb(err)\n if (!/^2/.test(res.statusCode))\n return cb(new Error('http status code: '+res.statusCode))\n if (!body)\n return cb(new Error('no body result'))\n\n var binary = false \n\n //if the response type is an array buffer,\n //we need to convert it into a regular Buffer object\n if (isArrayBuffer(body)) {\n var array = new Uint8Array(body)\n body = Buffer.from(array, 'binary')\n }\n\n //now check the string/Buffer response\n //and see if it has a binary BMF header\n if (isBinaryFormat(body)) {\n binary = true\n //if we have a string, turn it into a Buffer\n if (typeof body === 'string') \n body = Buffer.from(body, 'binary')\n } \n\n //we are not parsing a binary format, just ASCII/XML/etc\n if (!binary) {\n //might still be a buffer if responseType is 'arraybuffer'\n if (Buffer.isBuffer(body))\n body = body.toString(opt.encoding)\n body = body.trim()\n }\n\n var result\n try {\n var type = res.headers['content-type']\n if (binary)\n result = readBinary(body)\n else if (/json/.test(type) || body.charAt(0) === '{')\n result = JSON.parse(body)\n else if (/xml/.test(type) || body.charAt(0) === '<')\n result = parseXML(body)\n else\n result = parseASCII(body)\n } catch (e) {\n cb(new Error('error parsing font '+e.message))\n cb = noop\n }\n cb(null, result)\n })\n}\n\nfunction isArrayBuffer(arr) {\n var str = Object.prototype.toString\n return str.call(arr) === '[object ArrayBuffer]'\n}\n\nfunction getBinaryOpts(opt) {\n //IE10+ and other modern browsers support array buffers\n if (xml2)\n return xtend(opt, { responseType: 'arraybuffer' })\n \n if (typeof self.XMLHttpRequest === 'undefined')\n throw new Error('your browser does not support XHR loading')\n\n //IE9 and XML1 browsers could still use an override\n var req = new self.XMLHttpRequest()\n req.overrideMimeType('text/plain; charset=x-user-defined')\n return xtend({\n xhr: req\n }, opt)\n}\n","var equal = require('buffer-equal')\nvar HEADER = Buffer.from([66, 77, 70, 3])\n\nmodule.exports = function(buf) {\n if (typeof buf === 'string')\n return buf.substring(0, 3) === 'BMF'\n return buf.length > 4 && equal(buf.slice(0, 4), HEADER)\n}","// (c) Dean McNamee , 2013.\n//\n// https://github.com/deanm/omggif\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n//\n// omggif is a JavaScript implementation of a GIF 89a encoder and decoder,\n// including animation and compression. It does not rely on any specific\n// underlying system, so should run in the browser, Node, or Plask.\n\n\"use strict\";\n\nfunction GifWriter(buf, width, height, gopts) {\n var p = 0;\n\n var gopts = gopts === undefined ? { } : gopts;\n var loop_count = gopts.loop === undefined ? null : gopts.loop;\n var global_palette = gopts.palette === undefined ? null : gopts.palette;\n\n if (width <= 0 || height <= 0 || width > 65535 || height > 65535)\n throw new Error(\"Width/Height invalid.\");\n\n function check_palette_and_num_colors(palette) {\n var num_colors = palette.length;\n if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) {\n throw new Error(\n \"Invalid code/color length, must be power of 2 and 2 .. 256.\");\n }\n return num_colors;\n }\n\n // - Header.\n buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF\n buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a\n\n // Handling of Global Color Table (palette) and background index.\n var gp_num_colors_pow2 = 0;\n var background = 0;\n if (global_palette !== null) {\n var gp_num_colors = check_palette_and_num_colors(global_palette);\n while (gp_num_colors >>= 1) ++gp_num_colors_pow2;\n gp_num_colors = 1 << gp_num_colors_pow2;\n --gp_num_colors_pow2;\n if (gopts.background !== undefined) {\n background = gopts.background;\n if (background >= gp_num_colors)\n throw new Error(\"Background index out of range.\");\n // The GIF spec states that a background index of 0 should be ignored, so\n // this is probably a mistake and you really want to set it to another\n // slot in the palette. But actually in the end most browsers, etc end\n // up ignoring this almost completely (including for dispose background).\n if (background === 0)\n throw new Error(\"Background index explicitly passed as 0.\");\n }\n }\n\n // - Logical Screen Descriptor.\n // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.\n buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff;\n buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff;\n // NOTE: Indicates 0-bpp original color resolution (unused?).\n buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.\n gp_num_colors_pow2; // NOTE: No sort flag (unused?).\n buf[p++] = background; // Background Color Index.\n buf[p++] = 0; // Pixel aspect ratio (unused?).\n\n // - Global Color Table\n if (global_palette !== null) {\n for (var i = 0, il = global_palette.length; i < il; ++i) {\n var rgb = global_palette[i];\n buf[p++] = rgb >> 16 & 0xff;\n buf[p++] = rgb >> 8 & 0xff;\n buf[p++] = rgb & 0xff;\n }\n }\n\n if (loop_count !== null) { // Netscape block for looping.\n if (loop_count < 0 || loop_count > 65535)\n throw new Error(\"Loop count invalid.\")\n // Extension code, label, and length.\n buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b;\n // NETSCAPE2.0\n buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53;\n buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45;\n buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30;\n // Sub-block\n buf[p++] = 0x03; buf[p++] = 0x01;\n buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff;\n buf[p++] = 0x00; // Terminator.\n }\n\n\n var ended = false;\n\n this.addFrame = function(x, y, w, h, indexed_pixels, opts) {\n if (ended === true) { --p; ended = false; } // Un-end.\n\n opts = opts === undefined ? { } : opts;\n\n // TODO(deanm): Bounds check x, y. Do they need to be within the virtual\n // canvas width/height, I imagine?\n if (x < 0 || y < 0 || x > 65535 || y > 65535)\n throw new Error(\"x/y invalid.\")\n\n if (w <= 0 || h <= 0 || w > 65535 || h > 65535)\n throw new Error(\"Width/Height invalid.\")\n\n if (indexed_pixels.length < w * h)\n throw new Error(\"Not enough pixels for the frame size.\");\n\n var using_local_palette = true;\n var palette = opts.palette;\n if (palette === undefined || palette === null) {\n using_local_palette = false;\n palette = global_palette;\n }\n\n if (palette === undefined || palette === null)\n throw new Error(\"Must supply either a local or global palette.\");\n\n var num_colors = check_palette_and_num_colors(palette);\n\n // Compute the min_code_size (power of 2), destroying num_colors.\n var min_code_size = 0;\n while (num_colors >>= 1) ++min_code_size;\n num_colors = 1 << min_code_size; // Now we can easily get it back.\n\n var delay = opts.delay === undefined ? 0 : opts.delay;\n\n // From the spec:\n // 0 - No disposal specified. The decoder is\n // not required to take any action.\n // 1 - Do not dispose. The graphic is to be left\n // in place.\n // 2 - Restore to background color. The area used by the\n // graphic must be restored to the background color.\n // 3 - Restore to previous. The decoder is required to\n // restore the area overwritten by the graphic with\n // what was there prior to rendering the graphic.\n // 4-7 - To be defined.\n // NOTE(deanm): Dispose background doesn't really work, apparently most\n // browsers ignore the background palette index and clear to transparency.\n var disposal = opts.disposal === undefined ? 0 : opts.disposal;\n if (disposal < 0 || disposal > 3) // 4-7 is reserved.\n throw new Error(\"Disposal out of range.\");\n\n var use_transparency = false;\n var transparent_index = 0;\n if (opts.transparent !== undefined && opts.transparent !== null) {\n use_transparency = true;\n transparent_index = opts.transparent;\n if (transparent_index < 0 || transparent_index >= num_colors)\n throw new Error(\"Transparent color index.\");\n }\n\n if (disposal !== 0 || use_transparency || delay !== 0) {\n // - Graphics Control Extension\n buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label.\n buf[p++] = 4; // Byte size.\n\n buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);\n buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff;\n buf[p++] = transparent_index; // Transparent color index.\n buf[p++] = 0; // Block Terminator.\n }\n\n // - Image Descriptor\n buf[p++] = 0x2c; // Image Seperator.\n buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left.\n buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top.\n buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff;\n buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff;\n // NOTE: No sort flag (unused?).\n // TODO(deanm): Support interlace.\n buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0;\n\n // - Local Color Table\n if (using_local_palette === true) {\n for (var i = 0, il = palette.length; i < il; ++i) {\n var rgb = palette[i];\n buf[p++] = rgb >> 16 & 0xff;\n buf[p++] = rgb >> 8 & 0xff;\n buf[p++] = rgb & 0xff;\n }\n }\n\n p = GifWriterOutputLZWCodeStream(\n buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);\n\n return p;\n };\n\n this.end = function() {\n if (ended === false) {\n buf[p++] = 0x3b; // Trailer.\n ended = true;\n }\n return p;\n };\n\n this.getOutputBuffer = function() { return buf; };\n this.setOutputBuffer = function(v) { buf = v; };\n this.getOutputBufferPosition = function() { return p; };\n this.setOutputBufferPosition = function(v) { p = v; };\n}\n\n// Main compression routine, palette indexes -> LZW code stream.\n// |index_stream| must have at least one entry.\nfunction GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {\n buf[p++] = min_code_size;\n var cur_subblock = p++; // Pointing at the length field.\n\n var clear_code = 1 << min_code_size;\n var code_mask = clear_code - 1;\n var eoi_code = clear_code + 1;\n var next_code = eoi_code + 1;\n\n var cur_code_size = min_code_size + 1; // Number of bits per code.\n var cur_shift = 0;\n // We have at most 12-bit codes, so we should have to hold a max of 19\n // bits here (and then we would write out).\n var cur = 0;\n\n function emit_bytes_to_buffer(bit_block_size) {\n while (cur_shift >= bit_block_size) {\n buf[p++] = cur & 0xff;\n cur >>= 8; cur_shift -= 8;\n if (p === cur_subblock + 256) { // Finished a subblock.\n buf[cur_subblock] = 255;\n cur_subblock = p++;\n }\n }\n }\n\n function emit_code(c) {\n cur |= c << cur_shift;\n cur_shift += cur_code_size;\n emit_bytes_to_buffer(8);\n }\n\n // I am not an expert on the topic, and I don't want to write a thesis.\n // However, it is good to outline here the basic algorithm and the few data\n // structures and optimizations here that make this implementation fast.\n // The basic idea behind LZW is to build a table of previously seen runs\n // addressed by a short id (herein called output code). All data is\n // referenced by a code, which represents one or more values from the\n // original input stream. All input bytes can be referenced as the same\n // value as an output code. So if you didn't want any compression, you\n // could more or less just output the original bytes as codes (there are\n // some details to this, but it is the idea). In order to achieve\n // compression, values greater then the input range (codes can be up to\n // 12-bit while input only 8-bit) represent a sequence of previously seen\n // inputs. The decompressor is able to build the same mapping while\n // decoding, so there is always a shared common knowledge between the\n // encoding and decoder, which is also important for \"timing\" aspects like\n // how to handle variable bit width code encoding.\n //\n // One obvious but very important consequence of the table system is there\n // is always a unique id (at most 12-bits) to map the runs. 'A' might be\n // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship\n // can be used for an effecient lookup strategy for the code mapping. We\n // need to know if a run has been seen before, and be able to map that run\n // to the output code. Since we start with known unique ids (input bytes),\n // and then from those build more unique ids (table entries), we can\n // continue this chain (almost like a linked list) to always have small\n // integer values that represent the current byte chains in the encoder.\n // This means instead of tracking the input bytes (AAAABCD) to know our\n // current state, we can track the table entry for AAAABC (it is guaranteed\n // to exist by the nature of the algorithm) and the next character D.\n // Therefor the tuple of (table_entry, byte) is guaranteed to also be\n // unique. This allows us to create a simple lookup key for mapping input\n // sequences to codes (table indices) without having to store or search\n // any of the code sequences. So if 'AAAA' has a table entry of 12, the\n // tuple of ('AAAA', K) for any input byte K will be unique, and can be our\n // key. This leads to a integer value at most 20-bits, which can always\n // fit in an SMI value and be used as a fast sparse array / object key.\n\n // Output code for the current contents of the index buffer.\n var ib_code = index_stream[0] & code_mask; // Load first input index.\n var code_table = { }; // Key'd on our 20-bit \"tuple\".\n\n emit_code(clear_code); // Spec says first code should be a clear code.\n\n // First index already loaded, process the rest of the stream.\n for (var i = 1, il = index_stream.length; i < il; ++i) {\n var k = index_stream[i] & code_mask;\n var cur_key = ib_code << 8 | k; // (prev, k) unique tuple.\n var cur_code = code_table[cur_key]; // buffer + k.\n\n // Check if we have to create a new code table entry.\n if (cur_code === undefined) { // We don't have buffer + k.\n // Emit index buffer (without k).\n // This is an inline version of emit_code, because this is the core\n // writing routine of the compressor (and V8 cannot inline emit_code\n // because it is a closure here in a different context). Additionally\n // we can call emit_byte_to_buffer less often, because we can have\n // 30-bits (from our 31-bit signed SMI), and we know our codes will only\n // be 12-bits, so can safely have 18-bits there without overflow.\n // emit_code(ib_code);\n cur |= ib_code << cur_shift;\n cur_shift += cur_code_size;\n while (cur_shift >= 8) {\n buf[p++] = cur & 0xff;\n cur >>= 8; cur_shift -= 8;\n if (p === cur_subblock + 256) { // Finished a subblock.\n buf[cur_subblock] = 255;\n cur_subblock = p++;\n }\n }\n\n if (next_code === 4096) { // Table full, need a clear.\n emit_code(clear_code);\n next_code = eoi_code + 1;\n cur_code_size = min_code_size + 1;\n code_table = { };\n } else { // Table not full, insert a new entry.\n // Increase our variable bit code sizes if necessary. This is a bit\n // tricky as it is based on \"timing\" between the encoding and\n // decoder. From the encoders perspective this should happen after\n // we've already emitted the index buffer and are about to create the\n // first table entry that would overflow our current code bit size.\n if (next_code >= (1 << cur_code_size)) ++cur_code_size;\n code_table[cur_key] = next_code++; // Insert into code table.\n }\n\n ib_code = k; // Index buffer to single input k.\n } else {\n ib_code = cur_code; // Index buffer to sequence in code table.\n }\n }\n\n emit_code(ib_code); // There will still be something in the index buffer.\n emit_code(eoi_code); // End Of Information.\n\n // Flush / finalize the sub-blocks stream to the buffer.\n emit_bytes_to_buffer(1);\n\n // Finish the sub-blocks, writing out any unfinished lengths and\n // terminating with a sub-block of length 0. If we have already started\n // but not yet used a sub-block it can just become the terminator.\n if (cur_subblock + 1 === p) { // Started but unused.\n buf[cur_subblock] = 0;\n } else { // Started and used, write length and additional terminator block.\n buf[cur_subblock] = p - cur_subblock - 1;\n buf[p++] = 0;\n }\n return p;\n}\n\nfunction GifReader(buf) {\n var p = 0;\n\n // - Header (GIF87a or GIF89a).\n if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 ||\n buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) {\n throw new Error(\"Invalid GIF 87a/89a header.\");\n }\n\n // - Logical Screen Descriptor.\n var width = buf[p++] | buf[p++] << 8;\n var height = buf[p++] | buf[p++] << 8;\n var pf0 = buf[p++]; // .\n var global_palette_flag = pf0 >> 7;\n var num_global_colors_pow2 = pf0 & 0x7;\n var num_global_colors = 1 << (num_global_colors_pow2 + 1);\n var background = buf[p++];\n buf[p++]; // Pixel aspect ratio (unused?).\n\n var global_palette_offset = null;\n var global_palette_size = null;\n\n if (global_palette_flag) {\n global_palette_offset = p;\n global_palette_size = num_global_colors;\n p += num_global_colors * 3; // Seek past palette.\n }\n\n var no_eof = true;\n\n var frames = [ ];\n\n var delay = 0;\n var transparent_index = null;\n var disposal = 0; // 0 - No disposal specified.\n var loop_count = null;\n\n this.width = width;\n this.height = height;\n\n while (no_eof && p < buf.length) {\n switch (buf[p++]) {\n case 0x21: // Graphics Control Extension Block\n switch (buf[p++]) {\n case 0xff: // Application specific block\n // Try if it's a Netscape block (with animation loop counter).\n if (buf[p ] !== 0x0b || // 21 FF already read, check block size.\n // NETSCAPE2.0\n buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 &&\n buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 &&\n buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 &&\n buf[p+10] == 0x2e && buf[p+11] == 0x30 &&\n // Sub-block\n buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) {\n p += 14;\n loop_count = buf[p++] | buf[p++] << 8;\n p++; // Skip terminator.\n } else { // We don't know what it is, just try to get past it.\n p += 12;\n while (true) { // Seek through subblocks.\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n p += block_size;\n }\n }\n break;\n\n case 0xf9: // Graphics Control Extension\n if (buf[p++] !== 0x4 || buf[p+4] !== 0)\n throw new Error(\"Invalid graphics extension block.\");\n var pf1 = buf[p++];\n delay = buf[p++] | buf[p++] << 8;\n transparent_index = buf[p++];\n if ((pf1 & 1) === 0) transparent_index = null;\n disposal = pf1 >> 2 & 0x7;\n p++; // Skip terminator.\n break;\n\n case 0xfe: // Comment Extension.\n while (true) { // Seek through subblocks.\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n // console.log(buf.slice(p, p+block_size).toString('ascii'));\n p += block_size;\n }\n break;\n\n default:\n throw new Error(\n \"Unknown graphic control label: 0x\" + buf[p-1].toString(16));\n }\n break;\n\n case 0x2c: // Image Descriptor.\n var x = buf[p++] | buf[p++] << 8;\n var y = buf[p++] | buf[p++] << 8;\n var w = buf[p++] | buf[p++] << 8;\n var h = buf[p++] | buf[p++] << 8;\n var pf2 = buf[p++];\n var local_palette_flag = pf2 >> 7;\n var interlace_flag = pf2 >> 6 & 1;\n var num_local_colors_pow2 = pf2 & 0x7;\n var num_local_colors = 1 << (num_local_colors_pow2 + 1);\n var palette_offset = global_palette_offset;\n var palette_size = global_palette_size;\n var has_local_palette = false;\n if (local_palette_flag) {\n var has_local_palette = true;\n palette_offset = p; // Override with local palette.\n palette_size = num_local_colors;\n p += num_local_colors * 3; // Seek past palette.\n }\n\n var data_offset = p;\n\n p++; // codesize\n while (true) {\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n p += block_size;\n }\n\n frames.push({x: x, y: y, width: w, height: h,\n has_local_palette: has_local_palette,\n palette_offset: palette_offset,\n palette_size: palette_size,\n data_offset: data_offset,\n data_length: p - data_offset,\n transparent_index: transparent_index,\n interlaced: !!interlace_flag,\n delay: delay,\n disposal: disposal});\n break;\n\n case 0x3b: // Trailer Marker (end of file).\n no_eof = false;\n break;\n\n default:\n throw new Error(\"Unknown gif block: 0x\" + buf[p-1].toString(16));\n break;\n }\n }\n\n this.numFrames = function() {\n return frames.length;\n };\n\n this.loopCount = function() {\n return loop_count;\n };\n\n this.frameInfo = function(frame_num) {\n if (frame_num < 0 || frame_num >= frames.length)\n throw new Error(\"Frame index out of range.\");\n return frames[frame_num];\n }\n\n this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {\n var frame = this.frameInfo(frame_num);\n var num_pixels = frame.width * frame.height;\n var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.\n GifReaderLZWOutputIndexStream(\n buf, frame.data_offset, index_stream, num_pixels);\n var palette_offset = frame.palette_offset;\n\n // NOTE(deanm): It seems to be much faster to compare index to 256 than\n // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in\n // the profile, not sure if it's related to using a Uint8Array.\n var trans = frame.transparent_index;\n if (trans === null) trans = 256;\n\n // We are possibly just blitting to a portion of the entire frame.\n // That is a subrect within the framerect, so the additional pixels\n // must be skipped over after we finished a scanline.\n var framewidth = frame.width;\n var framestride = width - framewidth;\n var xleft = framewidth; // Number of subrect pixels left in scanline.\n\n // Output indicies of the top left and bottom right corners of the subrect.\n var opbeg = ((frame.y * width) + frame.x) * 4;\n var opend = ((frame.y + frame.height) * width + frame.x) * 4;\n var op = opbeg;\n\n var scanstride = framestride * 4;\n\n // Use scanstride to skip past the rows when interlacing. This is skipping\n // 7 rows for the first two passes, then 3 then 1.\n if (frame.interlaced === true) {\n scanstride += width * 4 * 7; // Pass 1.\n }\n\n var interlaceskip = 8; // Tracking the row interval in the current pass.\n\n for (var i = 0, il = index_stream.length; i < il; ++i) {\n var index = index_stream[i];\n\n if (xleft === 0) { // Beginning of new scan line\n op += scanstride;\n xleft = framewidth;\n if (op >= opend) { // Catch the wrap to switch passes when interlacing.\n scanstride = framestride * 4 + width * 4 * (interlaceskip-1);\n // interlaceskip / 2 * 4 is interlaceskip << 1.\n op = opbeg + (framewidth + framestride) * (interlaceskip << 1);\n interlaceskip >>= 1;\n }\n }\n\n if (index === trans) {\n op += 4;\n } else {\n var r = buf[palette_offset + index * 3];\n var g = buf[palette_offset + index * 3 + 1];\n var b = buf[palette_offset + index * 3 + 2];\n pixels[op++] = b;\n pixels[op++] = g;\n pixels[op++] = r;\n pixels[op++] = 255;\n }\n --xleft;\n }\n };\n\n // I will go to copy and paste hell one day...\n this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {\n var frame = this.frameInfo(frame_num);\n var num_pixels = frame.width * frame.height;\n var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.\n GifReaderLZWOutputIndexStream(\n buf, frame.data_offset, index_stream, num_pixels);\n var palette_offset = frame.palette_offset;\n\n // NOTE(deanm): It seems to be much faster to compare index to 256 than\n // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in\n // the profile, not sure if it's related to using a Uint8Array.\n var trans = frame.transparent_index;\n if (trans === null) trans = 256;\n\n // We are possibly just blitting to a portion of the entire frame.\n // That is a subrect within the framerect, so the additional pixels\n // must be skipped over after we finished a scanline.\n var framewidth = frame.width;\n var framestride = width - framewidth;\n var xleft = framewidth; // Number of subrect pixels left in scanline.\n\n // Output indicies of the top left and bottom right corners of the subrect.\n var opbeg = ((frame.y * width) + frame.x) * 4;\n var opend = ((frame.y + frame.height) * width + frame.x) * 4;\n var op = opbeg;\n\n var scanstride = framestride * 4;\n\n // Use scanstride to skip past the rows when interlacing. This is skipping\n // 7 rows for the first two passes, then 3 then 1.\n if (frame.interlaced === true) {\n scanstride += width * 4 * 7; // Pass 1.\n }\n\n var interlaceskip = 8; // Tracking the row interval in the current pass.\n\n for (var i = 0, il = index_stream.length; i < il; ++i) {\n var index = index_stream[i];\n\n if (xleft === 0) { // Beginning of new scan line\n op += scanstride;\n xleft = framewidth;\n if (op >= opend) { // Catch the wrap to switch passes when interlacing.\n scanstride = framestride * 4 + width * 4 * (interlaceskip-1);\n // interlaceskip / 2 * 4 is interlaceskip << 1.\n op = opbeg + (framewidth + framestride) * (interlaceskip << 1);\n interlaceskip >>= 1;\n }\n }\n\n if (index === trans) {\n op += 4;\n } else {\n var r = buf[palette_offset + index * 3];\n var g = buf[palette_offset + index * 3 + 1];\n var b = buf[palette_offset + index * 3 + 2];\n pixels[op++] = r;\n pixels[op++] = g;\n pixels[op++] = b;\n pixels[op++] = 255;\n }\n --xleft;\n }\n };\n}\n\nfunction GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {\n var min_code_size = code_stream[p++];\n\n var clear_code = 1 << min_code_size;\n var eoi_code = clear_code + 1;\n var next_code = eoi_code + 1;\n\n var cur_code_size = min_code_size + 1; // Number of bits per code.\n // NOTE: This shares the same name as the encoder, but has a different\n // meaning here. Here this masks each code coming from the code stream.\n var code_mask = (1 << cur_code_size) - 1;\n var cur_shift = 0;\n var cur = 0;\n\n var op = 0; // Output pointer.\n\n var subblock_size = code_stream[p++];\n\n // TODO(deanm): Would using a TypedArray be any faster? At least it would\n // solve the fast mode / backing store uncertainty.\n // var code_table = Array(4096);\n var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.\n\n var prev_code = null; // Track code-1.\n\n while (true) {\n // Read up to two bytes, making sure we always 12-bits for max sized code.\n while (cur_shift < 16) {\n if (subblock_size === 0) break; // No more data to be read.\n\n cur |= code_stream[p++] << cur_shift;\n cur_shift += 8;\n\n if (subblock_size === 1) { // Never let it get to 0 to hold logic above.\n subblock_size = code_stream[p++]; // Next subblock.\n } else {\n --subblock_size;\n }\n }\n\n // TODO(deanm): We should never really get here, we should have received\n // and EOI.\n if (cur_shift < cur_code_size)\n break;\n\n var code = cur & code_mask;\n cur >>= cur_code_size;\n cur_shift -= cur_code_size;\n\n // TODO(deanm): Maybe should check that the first code was a clear code,\n // at least this is what you're supposed to do. But actually our encoder\n // now doesn't emit a clear code first anyway.\n if (code === clear_code) {\n // We don't actually have to clear the table. This could be a good idea\n // for greater error checking, but we don't really do any anyway. We\n // will just track it with next_code and overwrite old entries.\n\n next_code = eoi_code + 1;\n cur_code_size = min_code_size + 1;\n code_mask = (1 << cur_code_size) - 1;\n\n // Don't update prev_code ?\n prev_code = null;\n continue;\n } else if (code === eoi_code) {\n break;\n }\n\n // We have a similar situation as the decoder, where we want to store\n // variable length entries (code table entries), but we want to do in a\n // faster manner than an array of arrays. The code below stores sort of a\n // linked list within the code table, and then \"chases\" through it to\n // construct the dictionary entries. When a new entry is created, just the\n // last byte is stored, and the rest (prefix) of the entry is only\n // referenced by its table entry. Then the code chases through the\n // prefixes until it reaches a single byte code. We have to chase twice,\n // first to compute the length, and then to actually copy the data to the\n // output (backwards, since we know the length). The alternative would be\n // storing something in an intermediate stack, but that doesn't make any\n // more sense. I implemented an approach where it also stored the length\n // in the code table, although it's a bit tricky because you run out of\n // bits (12 + 12 + 8), but I didn't measure much improvements (the table\n // entries are generally not the long). Even when I created benchmarks for\n // very long table entries the complexity did not seem worth it.\n // The code table stores the prefix entry in 12 bits and then the suffix\n // byte in 8 bits, so each entry is 20 bits.\n\n var chase_code = code < next_code ? code : prev_code;\n\n // Chase what we will output, either {CODE} or {CODE-1}.\n var chase_length = 0;\n var chase = chase_code;\n while (chase > clear_code) {\n chase = code_table[chase] >> 8;\n ++chase_length;\n }\n\n var k = chase;\n\n var op_end = op + chase_length + (chase_code !== code ? 1 : 0);\n if (op_end > output_length) {\n console.log(\"Warning, gif stream longer than expected.\");\n return;\n }\n\n // Already have the first byte from the chase, might as well write it fast.\n output[op++] = k;\n\n op += chase_length;\n var b = op; // Track pointer, writing backwards.\n\n if (chase_code !== code) // The case of emitting {CODE-1} + k.\n output[op++] = k;\n\n chase = chase_code;\n while (chase_length--) {\n chase = code_table[chase];\n output[--b] = chase & 0xff; // Write backwards.\n chase >>= 8; // Pull down to the prefix code.\n }\n\n if (prev_code !== null && next_code < 4096) {\n code_table[next_code++] = prev_code << 8 | k;\n // TODO(deanm): Figure out this clearing vs code growth logic better. I\n // have an feeling that it should just happen somewhere else, for now it\n // is awkward between when we grow past the max and then hit a clear code.\n // For now just check if we hit the max 12-bits (then a clear code should\n // follow, also of course encoded in 12-bits).\n if (next_code >= code_mask+1 && cur_code_size < 12) {\n ++cur_code_size;\n code_mask = code_mask << 1 | 1;\n }\n }\n\n prev_code = code;\n }\n\n if (op !== output_length) {\n console.log(\"Warning, gif stream shorter than expected.\");\n }\n\n return output;\n}\n\n// CommonJS.\ntry { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) {}\n","// Top level file is just a mixin of submodules & constants\n'use strict';\n\nvar assign = require('./lib/utils/common').assign;\n\nvar deflate = require('./lib/deflate');\nvar inflate = require('./lib/inflate');\nvar constants = require('./lib/zlib/constants');\n\nvar pako = {};\n\nassign(pako, deflate, inflate, constants);\n\nmodule.exports = pako;\n","'use strict';\n\n\nvar zlib_deflate = require('./zlib/deflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\n\nvar toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nvar Z_NO_FLUSH = 0;\nvar Z_FINISH = 4;\n\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_SYNC_FLUSH = 2;\n\nvar Z_DEFAULT_COMPRESSION = -1;\n\nvar Z_DEFAULT_STRATEGY = 0;\n\nvar Z_DEFLATED = 8;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate(options) {\n if (!(this instanceof Deflate)) return new Deflate(options);\n\n this.options = utils.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n var dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = zlib_deflate.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = zlib_deflate.deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n if (this.options.to === 'string') {\n this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate(input, options) {\n var deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || msg[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate(input, options);\n}\n\n\nexports.Deflate = Deflate;\nexports.deflate = deflate;\nexports.deflateRaw = deflateRaw;\nexports.gzip = gzip;\n","'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n","'use strict';\n\n\nvar TYPED_OK = (typeof Uint8Array !== 'undefined') &&\n (typeof Uint16Array !== 'undefined') &&\n (typeof Int32Array !== 'undefined');\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexports.assign = function (obj /*from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// reduce buffer size, avoiding mem copy\nexports.shrinkBuf = function (buf, size) {\n if (buf.length === size) { return buf; }\n if (buf.subarray) { return buf.subarray(0, size); }\n buf.length = size;\n return buf;\n};\n\n\nvar fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n var i, l, len, pos, chunk, result;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nvar fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\nexports.setTyped = function (on) {\n if (on) {\n exports.Buf8 = Uint8Array;\n exports.Buf16 = Uint16Array;\n exports.Buf32 = Int32Array;\n exports.assign(exports, fnTyped);\n } else {\n exports.Buf8 = Array;\n exports.Buf16 = Array;\n exports.Buf32 = Array;\n exports.assign(exports, fnUntyped);\n }\n};\n\nexports.setTyped(TYPED_OK);\n","// String encode/decode helpers\n'use strict';\n\n\nvar utils = require('./common');\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nvar STR_APPLY_OK = true;\nvar STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nvar _utf8len = new utils.Buf8(256);\nfor (var q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n","'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n","'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar trees = require('./trees');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar msg = require('./messages');\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nvar Z_NO_FLUSH = 0;\nvar Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\nvar Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\n//var Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\n//var Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\n//var Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n\n/* compression levels */\n//var Z_NO_COMPRESSION = 0;\n//var Z_BEST_SPEED = 1;\n//var Z_BEST_COMPRESSION = 9;\nvar Z_DEFAULT_COMPRESSION = -1;\n\n\nvar Z_FILTERED = 1;\nvar Z_HUFFMAN_ONLY = 2;\nvar Z_RLE = 3;\nvar Z_FIXED = 4;\nvar Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\n//var Z_BINARY = 0;\n//var Z_TEXT = 1;\n//var Z_ASCII = 1; // = Z_TEXT\nvar Z_UNKNOWN = 2;\n\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n/*============================================================================*/\n\n\nvar MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_MEM_LEVEL = 8;\n\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nvar D_CODES = 30;\n/* number of distance codes */\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\nvar MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nvar PRESET_DICT = 0x20;\n\nvar INIT_STATE = 42;\nvar EXTRA_STATE = 69;\nvar NAME_STATE = 73;\nvar COMMENT_STATE = 91;\nvar HCRC_STATE = 103;\nvar BUSY_STATE = 113;\nvar FINISH_STATE = 666;\n\nvar BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nvar BS_BLOCK_DONE = 2; /* block flush performed */\nvar BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nvar BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nvar OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n var s = strm.state;\n\n //_tr_flush_bits(s);\n var len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n// put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n var len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n var _w_size = s.w_size;\n var p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// var curr = s.strstart + s.lookahead;\n// var init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n var max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n var max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n var hash_head; /* head of the hash chain */\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n var hash_head; /* head of hash chain */\n var bflush; /* set if current block must be flushed */\n\n var max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n var bflush; /* set if current block must be flushed */\n var prev; /* byte at distance one to match */\n var scan, strend; /* scan goes up to strend for length of run */\n\n var _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nvar configuration_table;\n\nconfiguration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nfunction deflateResetKeep(strm) {\n var s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n var ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n var wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n var s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n var old_flush, s;\n var beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n var level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n var status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var s;\n var str, n;\n var wrap;\n var avail;\n var next;\n var input;\n var tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\n\nexports.deflateInit = deflateInit;\nexports.deflateInit2 = deflateInit2;\nexports.deflateReset = deflateReset;\nexports.deflateResetKeep = deflateResetKeep;\nexports.deflateSetHeader = deflateSetHeader;\nexports.deflate = deflate;\nexports.deflateEnd = deflateEnd;\nexports.deflateSetDictionary = deflateSetDictionary;\nexports.deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\nvar utils = require('../utils/common');\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//var Z_FILTERED = 1;\n//var Z_HUFFMAN_ONLY = 2;\n//var Z_RLE = 3;\nvar Z_FIXED = 4;\n//var Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nvar Z_BINARY = 0;\nvar Z_TEXT = 1;\n//var Z_ASCII = 1; // = Z_TEXT\nvar Z_UNKNOWN = 2;\n\n/*============================================================================*/\n\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nvar STORED_BLOCK = 0;\nvar STATIC_TREES = 1;\nvar DYN_TREES = 2;\n/* The three kinds of block type */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nvar D_CODES = 30;\n/* number of distance codes */\n\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nvar MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nvar END_BLOCK = 256;\n/* end of block literal code */\n\nvar REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nvar REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nvar REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nvar extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nvar extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nvar extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nvar bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nvar DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nvar static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nvar static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nvar _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nvar _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nvar base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nvar base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nvar static_l_desc;\nvar static_d_desc;\nvar static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n var res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var max_code = desc.max_code;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var extra = desc.stat_desc.extra_bits;\n var base = desc.stat_desc.extra_base;\n var max_length = desc.stat_desc.max_length;\n var h; /* heap index */\n var n, m; /* iterate over the tree elements */\n var bits; /* bit length */\n var xbits; /* extra bits */\n var f; /* frequency */\n var overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n var code = 0; /* running code value */\n var bits; /* bit index */\n var n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n var n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s)\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n var _n2 = n * 2;\n var _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n var v = s.heap[k];\n var j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n var dist; /* distance of matched string */\n var lc; /* match length or unmatched char (if dist == 0) */\n var lx = 0; /* running index in l_buf */\n var code; /* the code to send */\n var extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var elems = desc.stat_desc.elems;\n var n, m; /* iterate over heap elements */\n var max_code = -1; /* largest code with non zero frequency */\n var node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n var max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n var rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n var black_mask = 0xf3ffc07f;\n var n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nvar static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s)\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n var opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n var max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexports._tr_init = _tr_init;\nexports._tr_stored_block = _tr_stored_block;\nexports._tr_flush_block = _tr_flush_block;\nexports._tr_tally = _tr_tally;\nexports._tr_align = _tr_align;\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n","module.exports = function parseBMFontAscii(data) {\n if (!data)\n throw new Error('no data provided')\n data = data.toString().trim()\n\n var output = {\n pages: [],\n chars: [],\n kernings: []\n }\n\n var lines = data.split(/\\r\\n?|\\n/g)\n\n if (lines.length === 0)\n throw new Error('no data in BMFont file')\n\n for (var i = 0; i < lines.length; i++) {\n var lineData = splitLine(lines[i], i)\n if (!lineData) //skip empty lines\n continue\n\n if (lineData.key === 'page') {\n if (typeof lineData.data.id !== 'number')\n throw new Error('malformed file at line ' + i + ' -- needs page id=N')\n if (typeof lineData.data.file !== 'string')\n throw new Error('malformed file at line ' + i + ' -- needs page file=\"path\"')\n output.pages[lineData.data.id] = lineData.data.file\n } else if (lineData.key === 'chars' || lineData.key === 'kernings') {\n //... do nothing for these two ...\n } else if (lineData.key === 'char') {\n output.chars.push(lineData.data)\n } else if (lineData.key === 'kerning') {\n output.kernings.push(lineData.data)\n } else {\n output[lineData.key] = lineData.data\n }\n }\n\n return output\n}\n\nfunction splitLine(line, idx) {\n line = line.replace(/\\t+/g, ' ').trim()\n if (!line)\n return null\n\n var space = line.indexOf(' ')\n if (space === -1) \n throw new Error(\"no named row at line \" + idx)\n\n var key = line.substring(0, space)\n\n line = line.substring(space + 1)\n //clear \"letter\" field as it is non-standard and\n //requires additional complexity to parse \" / = symbols\n line = line.replace(/letter=[\\'\\\"]\\S+[\\'\\\"]/gi, '') \n line = line.split(\"=\")\n line = line.map(function(str) {\n return str.trim().match((/(\".*?\"|[^\"\\s]+)+(?=\\s*|\\s*$)/g))\n })\n\n var data = []\n for (var i = 0; i < line.length; i++) {\n var dt = line[i]\n if (i === 0) {\n data.push({\n key: dt[0],\n data: \"\"\n })\n } else if (i === line.length - 1) {\n data[data.length - 1].data = parseData(dt[0])\n } else {\n data[data.length - 1].data = parseData(dt[0])\n data.push({\n key: dt[1],\n data: \"\"\n })\n }\n }\n\n var out = {\n key: key,\n data: {}\n }\n\n data.forEach(function(v) {\n out.data[v.key] = v.data;\n })\n\n return out\n}\n\nfunction parseData(data) {\n if (!data || data.length === 0)\n return \"\"\n\n if (data.indexOf('\"') === 0 || data.indexOf(\"'\") === 0)\n return data.substring(1, data.length - 1)\n if (data.indexOf(',') !== -1)\n return parseIntList(data)\n return parseInt(data, 10)\n}\n\nfunction parseIntList(data) {\n return data.split(',').map(function(val) {\n return parseInt(val, 10)\n })\n}","var HEADER = [66, 77, 70]\n\nmodule.exports = function readBMFontBinary(buf) {\n if (buf.length < 6)\n throw new Error('invalid buffer length for BMFont')\n\n var header = HEADER.every(function(byte, i) {\n return buf.readUInt8(i) === byte\n })\n\n if (!header)\n throw new Error('BMFont missing BMF byte header')\n\n var i = 3\n var vers = buf.readUInt8(i++)\n if (vers > 3)\n throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')\n \n var target = { kernings: [], chars: [] }\n for (var b=0; b<5; b++)\n i += readBlock(target, buf, i)\n return target\n}\n\nfunction readBlock(target, buf, i) {\n if (i > buf.length-1)\n return 0\n\n var blockID = buf.readUInt8(i++)\n var blockSize = buf.readInt32LE(i)\n i += 4\n\n switch(blockID) {\n case 1: \n target.info = readInfo(buf, i)\n break\n case 2:\n target.common = readCommon(buf, i)\n break\n case 3:\n target.pages = readPages(buf, i, blockSize)\n break\n case 4:\n target.chars = readChars(buf, i, blockSize)\n break\n case 5:\n target.kernings = readKernings(buf, i, blockSize)\n break\n }\n return 5 + blockSize\n}\n\nfunction readInfo(buf, i) {\n var info = {}\n info.size = buf.readInt16LE(i)\n\n var bitField = buf.readUInt8(i+2)\n info.smooth = (bitField >> 7) & 1\n info.unicode = (bitField >> 6) & 1\n info.italic = (bitField >> 5) & 1\n info.bold = (bitField >> 4) & 1\n \n //fixedHeight is only mentioned in binary spec \n if ((bitField >> 3) & 1)\n info.fixedHeight = 1\n \n info.charset = buf.readUInt8(i+3) || ''\n info.stretchH = buf.readUInt16LE(i+4)\n info.aa = buf.readUInt8(i+6)\n info.padding = [\n buf.readInt8(i+7),\n buf.readInt8(i+8),\n buf.readInt8(i+9),\n buf.readInt8(i+10)\n ]\n info.spacing = [\n buf.readInt8(i+11),\n buf.readInt8(i+12)\n ]\n info.outline = buf.readUInt8(i+13)\n info.face = readStringNT(buf, i+14)\n return info\n}\n\nfunction readCommon(buf, i) {\n var common = {}\n common.lineHeight = buf.readUInt16LE(i)\n common.base = buf.readUInt16LE(i+2)\n common.scaleW = buf.readUInt16LE(i+4)\n common.scaleH = buf.readUInt16LE(i+6)\n common.pages = buf.readUInt16LE(i+8)\n var bitField = buf.readUInt8(i+10)\n common.packed = 0\n common.alphaChnl = buf.readUInt8(i+11)\n common.redChnl = buf.readUInt8(i+12)\n common.greenChnl = buf.readUInt8(i+13)\n common.blueChnl = buf.readUInt8(i+14)\n return common\n}\n\nfunction readPages(buf, i, size) {\n var pages = []\n var text = readNameNT(buf, i)\n var len = text.length+1\n var count = size / len\n for (var c=0; c element')\n var pages = pageRoot.getElementsByTagName('page')\n for (var i=0; i 2) {\n var lastSlashIndex = res.lastIndexOf('/');\n if (lastSlashIndex !== res.length - 1) {\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n } else {\n res = res.slice(0, lastSlashIndex);\n lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n }\n lastSlash = i;\n dots = 0;\n continue;\n }\n } else if (res.length === 2 || res.length === 1) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0)\n res += '/..';\n else\n res = '..';\n lastSegmentLength = 2;\n }\n } else {\n if (res.length > 0)\n res += '/' + path.slice(lastSlash + 1, i);\n else\n res = path.slice(lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === 46 /*.*/ && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n\nfunction _format(sep, pathObject) {\n var dir = pathObject.dir || pathObject.root;\n var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');\n if (!dir) {\n return base;\n }\n if (dir === pathObject.root) {\n return dir + base;\n }\n return dir + sep + base;\n}\n\nvar posix = {\n // path.resolve([from ...], to)\n resolve: function resolve() {\n var resolvedPath = '';\n var resolvedAbsolute = false;\n var cwd;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path;\n if (i >= 0)\n path = arguments[i];\n else {\n if (cwd === undefined)\n cwd = process.cwd();\n path = cwd;\n }\n\n assertPath(path);\n\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n\n if (resolvedAbsolute) {\n if (resolvedPath.length > 0)\n return '/' + resolvedPath;\n else\n return '/';\n } else if (resolvedPath.length > 0) {\n return resolvedPath;\n } else {\n return '.';\n }\n },\n\n normalize: function normalize(path) {\n assertPath(path);\n\n if (path.length === 0) return '.';\n\n var isAbsolute = path.charCodeAt(0) === 47 /*/*/;\n var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;\n\n // Normalize the path\n path = normalizeStringPosix(path, !isAbsolute);\n\n if (path.length === 0 && !isAbsolute) path = '.';\n if (path.length > 0 && trailingSeparator) path += '/';\n\n if (isAbsolute) return '/' + path;\n return path;\n },\n\n isAbsolute: function isAbsolute(path) {\n assertPath(path);\n return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;\n },\n\n join: function join() {\n if (arguments.length === 0)\n return '.';\n var joined;\n for (var i = 0; i < arguments.length; ++i) {\n var arg = arguments[i];\n assertPath(arg);\n if (arg.length > 0) {\n if (joined === undefined)\n joined = arg;\n else\n joined += '/' + arg;\n }\n }\n if (joined === undefined)\n return '.';\n return posix.normalize(joined);\n },\n\n relative: function relative(from, to) {\n assertPath(from);\n assertPath(to);\n\n if (from === to) return '';\n\n from = posix.resolve(from);\n to = posix.resolve(to);\n\n if (from === to) return '';\n\n // Trim any leading backslashes\n var fromStart = 1;\n for (; fromStart < from.length; ++fromStart) {\n if (from.charCodeAt(fromStart) !== 47 /*/*/)\n break;\n }\n var fromEnd = from.length;\n var fromLen = fromEnd - fromStart;\n\n // Trim any leading backslashes\n var toStart = 1;\n for (; toStart < to.length; ++toStart) {\n if (to.charCodeAt(toStart) !== 47 /*/*/)\n break;\n }\n var toEnd = to.length;\n var toLen = toEnd - toStart;\n\n // Compare paths to find the longest common path from root\n var length = fromLen < toLen ? fromLen : toLen;\n var lastCommonSep = -1;\n var i = 0;\n for (; i <= length; ++i) {\n if (i === length) {\n if (toLen > length) {\n if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1);\n } else if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i);\n }\n } else if (fromLen > length) {\n if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n } else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo'; to='/'\n lastCommonSep = 0;\n }\n }\n break;\n }\n var fromCode = from.charCodeAt(fromStart + i);\n var toCode = to.charCodeAt(toStart + i);\n if (fromCode !== toCode)\n break;\n else if (fromCode === 47 /*/*/)\n lastCommonSep = i;\n }\n\n var out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n if (out.length === 0)\n out += '..';\n else\n out += '/..';\n }\n }\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts\n if (out.length > 0)\n return out + to.slice(toStart + lastCommonSep);\n else {\n toStart += lastCommonSep;\n if (to.charCodeAt(toStart) === 47 /*/*/)\n ++toStart;\n return to.slice(toStart);\n }\n },\n\n _makeLong: function _makeLong(path) {\n return path;\n },\n\n dirname: function dirname(path) {\n assertPath(path);\n if (path.length === 0) return '.';\n var code = path.charCodeAt(0);\n var hasRoot = code === 47 /*/*/;\n var end = -1;\n var matchedSlash = true;\n for (var i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) return hasRoot ? '/' : '.';\n if (hasRoot && end === 1) return '//';\n return path.slice(0, end);\n },\n\n basename: function basename(path, ext) {\n if (ext !== undefined && typeof ext !== 'string') throw new TypeError('\"ext\" argument must be a string');\n assertPath(path);\n\n var start = 0;\n var end = -1;\n var matchedSlash = true;\n var i;\n\n if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n if (ext.length === path.length && ext === path) return '';\n var extIdx = ext.length - 1;\n var firstNonSlashEnd = -1;\n for (i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === ext.charCodeAt(extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n\n if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;\n return path.slice(start, end);\n } else {\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1) return '';\n return path.slice(start, end);\n }\n },\n\n extname: function extname(path) {\n assertPath(path);\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n for (var i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n return '';\n }\n return path.slice(startDot, end);\n },\n\n format: function format(pathObject) {\n if (pathObject === null || typeof pathObject !== 'object') {\n throw new TypeError('The \"pathObject\" argument must be of type Object. Received type ' + typeof pathObject);\n }\n return _format('/', pathObject);\n },\n\n parse: function parse(path) {\n assertPath(path);\n\n var ret = { root: '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0) return ret;\n var code = path.charCodeAt(0);\n var isAbsolute = code === 47 /*/*/;\n var start;\n if (isAbsolute) {\n ret.root = '/';\n start = 1;\n } else {\n start = 0;\n }\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n var i = path.length - 1;\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n\n // Get non-dir info\n for (; i >= start; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n if (end !== -1) {\n if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);\n }\n } else {\n if (startPart === 0 && isAbsolute) {\n ret.name = path.slice(1, startDot);\n ret.base = path.slice(1, end);\n } else {\n ret.name = path.slice(startPart, startDot);\n ret.base = path.slice(startPart, end);\n }\n ret.ext = path.slice(startDot, end);\n }\n\n if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';\n\n return ret;\n },\n\n sep: '/',\n delimiter: ':',\n win32: null,\n posix: null\n};\n\nposix.posix = posix;\n\nmodule.exports = posix;\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.Deferred = void 0;\r\nclass Deferred {\r\n constructor() {\r\n this.resolve = () => null;\r\n this.reject = () => null;\r\n this.promise = new Promise((resolve, reject) => {\r\n this.reject = reject;\r\n this.resolve = resolve;\r\n });\r\n }\r\n}\r\nexports.Deferred = Deferred;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.EndOfStreamError = exports.defaultMessages = void 0;\r\nexports.defaultMessages = 'End-Of-Stream';\r\n/**\r\n * Thrown on read operation of the end of file or stream has been reached\r\n */\r\nclass EndOfStreamError extends Error {\r\n constructor() {\r\n super(exports.defaultMessages);\r\n }\r\n}\r\nexports.EndOfStreamError = EndOfStreamError;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.StreamReader = exports.EndOfStreamError = void 0;\r\nconst EndOfFileStream_1 = require(\"./EndOfFileStream\");\r\nconst Deferred_1 = require(\"./Deferred\");\r\nvar EndOfFileStream_2 = require(\"./EndOfFileStream\");\r\nObject.defineProperty(exports, \"EndOfStreamError\", { enumerable: true, get: function () { return EndOfFileStream_2.EndOfStreamError; } });\r\nconst maxStreamReadSize = 1 * 1024 * 1024; // Maximum request length on read-stream operation\r\nclass StreamReader {\r\n constructor(s) {\r\n this.s = s;\r\n /**\r\n * Deferred used for postponed read request (as not data is yet available to read)\r\n */\r\n this.deferred = null;\r\n this.endOfStream = false;\r\n /**\r\n * Store peeked data\r\n * @type {Array}\r\n */\r\n this.peekQueue = [];\r\n if (!s.read || !s.once) {\r\n throw new Error('Expected an instance of stream.Readable');\r\n }\r\n this.s.once('end', () => this.reject(new EndOfFileStream_1.EndOfStreamError()));\r\n this.s.once('error', err => this.reject(err));\r\n this.s.once('close', () => this.reject(new Error('Stream closed')));\r\n }\r\n /**\r\n * Read ahead (peek) from stream. Subsequent read or peeks will return the same data\r\n * @param uint8Array - Uint8Array (or Buffer) to store data read from stream in\r\n * @param offset - Offset target\r\n * @param length - Number of bytes to read\r\n * @returns Number of bytes peeked\r\n */\r\n async peek(uint8Array, offset, length) {\r\n const bytesRead = await this.read(uint8Array, offset, length);\r\n this.peekQueue.push(uint8Array.subarray(offset, offset + bytesRead)); // Put read data back to peek buffer\r\n return bytesRead;\r\n }\r\n /**\r\n * Read chunk from stream\r\n * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in\r\n * @param offset - Offset target\r\n * @param length - Number of bytes to read\r\n * @returns Number of bytes read\r\n */\r\n async read(buffer, offset, length) {\r\n if (length === 0) {\r\n return 0;\r\n }\r\n if (this.peekQueue.length === 0 && this.endOfStream) {\r\n throw new EndOfFileStream_1.EndOfStreamError();\r\n }\r\n let remaining = length;\r\n let bytesRead = 0;\r\n // consume peeked data first\r\n while (this.peekQueue.length > 0 && remaining > 0) {\r\n const peekData = this.peekQueue.pop(); // Front of queue\r\n if (!peekData)\r\n throw new Error('peekData should be defined');\r\n const lenCopy = Math.min(peekData.length, remaining);\r\n buffer.set(peekData.subarray(0, lenCopy), offset + bytesRead);\r\n bytesRead += lenCopy;\r\n remaining -= lenCopy;\r\n if (lenCopy < peekData.length) {\r\n // remainder back to queue\r\n this.peekQueue.push(peekData.subarray(lenCopy));\r\n }\r\n }\r\n // continue reading from stream if required\r\n while (remaining > 0 && !this.endOfStream) {\r\n const reqLen = Math.min(remaining, maxStreamReadSize);\r\n const chunkLen = await this.readFromStream(buffer, offset + bytesRead, reqLen);\r\n bytesRead += chunkLen;\r\n if (chunkLen < reqLen)\r\n break;\r\n remaining -= chunkLen;\r\n }\r\n return bytesRead;\r\n }\r\n /**\r\n * Read chunk from stream\r\n * @param buffer Target Uint8Array (or Buffer) to store data read from stream in\r\n * @param offset Offset target\r\n * @param length Number of bytes to read\r\n * @returns Number of bytes read\r\n */\r\n async readFromStream(buffer, offset, length) {\r\n const readBuffer = this.s.read(length);\r\n if (readBuffer) {\r\n buffer.set(readBuffer, offset);\r\n return readBuffer.length;\r\n }\r\n else {\r\n const request = {\r\n buffer,\r\n offset,\r\n length,\r\n deferred: new Deferred_1.Deferred()\r\n };\r\n this.deferred = request.deferred;\r\n this.s.once('readable', () => {\r\n this.readDeferred(request);\r\n });\r\n return request.deferred.promise;\r\n }\r\n }\r\n /**\r\n * Process deferred read request\r\n * @param request Deferred read request\r\n */\r\n readDeferred(request) {\r\n const readBuffer = this.s.read(request.length);\r\n if (readBuffer) {\r\n request.buffer.set(readBuffer, request.offset);\r\n request.deferred.resolve(readBuffer.length);\r\n this.deferred = null;\r\n }\r\n else {\r\n this.s.once('readable', () => {\r\n this.readDeferred(request);\r\n });\r\n }\r\n }\r\n reject(err) {\r\n this.endOfStream = true;\r\n if (this.deferred) {\r\n this.deferred.reject(err);\r\n this.deferred = null;\r\n }\r\n }\r\n}\r\nexports.StreamReader = StreamReader;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.StreamReader = exports.EndOfStreamError = void 0;\r\nvar EndOfFileStream_1 = require(\"./EndOfFileStream\");\r\nObject.defineProperty(exports, \"EndOfStreamError\", { enumerable: true, get: function () { return EndOfFileStream_1.EndOfStreamError; } });\r\nvar StreamReader_1 = require(\"./StreamReader\");\r\nObject.defineProperty(exports, \"StreamReader\", { enumerable: true, get: function () { return StreamReader_1.StreamReader; } });\r\n","'use strict';\n\nmodule.exports = pixelmatch;\n\nfunction pixelmatch(img1, img2, output, width, height, options) {\n\n if (!options) options = {};\n\n var threshold = options.threshold === undefined ? 0.1 : options.threshold;\n\n // maximum acceptable square distance between two colors;\n // 35215 is the maximum possible value for the YIQ difference metric\n var maxDelta = 35215 * threshold * threshold,\n diff = 0;\n\n // compare each pixel of one image against the other one\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n\n var pos = (y * width + x) * 4;\n\n // squared YUV distance between colors at this pixel position\n var delta = colorDelta(img1, img2, pos, pos);\n\n // the color difference is above the threshold\n if (delta > maxDelta) {\n // check it's a real rendering difference or just anti-aliasing\n if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) ||\n antialiased(img2, x, y, width, height, img1))) {\n // one of the pixels is anti-aliasing; draw as yellow and do not count as difference\n if (output) drawPixel(output, pos, 255, 255, 0);\n\n } else {\n // found substantial difference not caused by anti-aliasing; draw it as red\n if (output) drawPixel(output, pos, 255, 0, 0);\n diff++;\n }\n\n } else if (output) {\n // pixels are similar; draw background as grayscale image blended with white\n var val = blend(grayPixel(img1, pos), 0.1);\n drawPixel(output, pos, val, val, val);\n }\n }\n }\n\n // return the number of different pixels\n return diff;\n}\n\n// check if a pixel is likely a part of anti-aliasing;\n// based on \"Anti-aliased Pixel and Intensity Slope Detector\" paper by V. Vysniauskas, 2009\n\nfunction antialiased(img, x1, y1, width, height, img2) {\n var x0 = Math.max(x1 - 1, 0),\n y0 = Math.max(y1 - 1, 0),\n x2 = Math.min(x1 + 1, width - 1),\n y2 = Math.min(y1 + 1, height - 1),\n pos = (y1 * width + x1) * 4,\n zeroes = 0,\n positives = 0,\n negatives = 0,\n min = 0,\n max = 0,\n minX, minY, maxX, maxY;\n\n // go through 8 adjacent pixels\n for (var x = x0; x <= x2; x++) {\n for (var y = y0; y <= y2; y++) {\n if (x === x1 && y === y1) continue;\n\n // brightness delta between the center pixel and adjacent one\n var delta = colorDelta(img, img, pos, (y * width + x) * 4, true);\n\n // count the number of equal, darker and brighter adjacent pixels\n if (delta === 0) zeroes++;\n else if (delta < 0) negatives++;\n else if (delta > 0) positives++;\n\n // if found more than 2 equal siblings, it's definitely not anti-aliasing\n if (zeroes > 2) return false;\n\n if (!img2) continue;\n\n // remember the darkest pixel\n if (delta < min) {\n min = delta;\n minX = x;\n minY = y;\n }\n // remember the brightest pixel\n if (delta > max) {\n max = delta;\n maxX = x;\n maxY = y;\n }\n }\n }\n\n if (!img2) return true;\n\n // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing\n if (negatives === 0 || positives === 0) return false;\n\n // if either the darkest or the brightest pixel has more than 2 equal siblings in both images\n // (definitely not anti-aliased), this pixel is anti-aliased\n return (!antialiased(img, minX, minY, width, height) && !antialiased(img2, minX, minY, width, height)) ||\n (!antialiased(img, maxX, maxY, width, height) && !antialiased(img2, maxX, maxY, width, height));\n}\n\n// calculate color difference according to the paper \"Measuring perceived color difference\n// using YIQ NTSC transmission color space in mobile applications\" by Y. Kotsarenko and F. Ramos\n\nfunction colorDelta(img1, img2, k, m, yOnly) {\n var a1 = img1[k + 3] / 255,\n a2 = img2[m + 3] / 255,\n\n r1 = blend(img1[k + 0], a1),\n g1 = blend(img1[k + 1], a1),\n b1 = blend(img1[k + 2], a1),\n\n r2 = blend(img2[m + 0], a2),\n g2 = blend(img2[m + 1], a2),\n b2 = blend(img2[m + 2], a2),\n\n y = rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2);\n\n if (yOnly) return y; // brightness difference only\n\n var i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2),\n q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);\n\n return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;\n}\n\nfunction rgb2y(r, g, b) { return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; }\nfunction rgb2i(r, g, b) { return r * 0.59597799 - g * 0.27417610 - b * 0.32180189; }\nfunction rgb2q(r, g, b) { return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; }\n\n// blend semi-transparent color with white\nfunction blend(c, a) {\n return 255 + (c - 255) * a;\n}\n\nfunction drawPixel(output, pos, r, g, b) {\n output[pos + 0] = r;\n output[pos + 1] = g;\n output[pos + 2] = b;\n output[pos + 3] = 255;\n}\n\nfunction grayPixel(img, i) {\n var a = img[i + 3] / 255,\n r = blend(img[i + 0], a),\n g = blend(img[i + 1], a),\n b = blend(img[i + 2], a);\n return rgb2y(r, g, b);\n}\n","(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.png = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o= data.length) {\n throw new Error(\"Ran out of data\");\n }\n\n let pixel = data[rawPos];\n pxData[pxPos] = pixel;\n pxData[pxPos + 1] = pixel;\n pxData[pxPos + 2] = pixel;\n pxData[pxPos + 3] = data[rawPos + 1];\n },\n\n // 3 - RGB\n // 0: 0, 1: 1, 2: 2, 3: 0xff\n function (pxData, data, pxPos, rawPos) {\n if (rawPos + 2 >= data.length) {\n throw new Error(\"Ran out of data\");\n }\n\n pxData[pxPos] = data[rawPos];\n pxData[pxPos + 1] = data[rawPos + 1];\n pxData[pxPos + 2] = data[rawPos + 2];\n pxData[pxPos + 3] = 0xff;\n },\n\n // 4 - RGBA\n // 0: 0, 1: 1, 2: 2, 3: 3\n function (pxData, data, pxPos, rawPos) {\n if (rawPos + 3 >= data.length) {\n throw new Error(\"Ran out of data\");\n }\n\n pxData[pxPos] = data[rawPos];\n pxData[pxPos + 1] = data[rawPos + 1];\n pxData[pxPos + 2] = data[rawPos + 2];\n pxData[pxPos + 3] = data[rawPos + 3];\n },\n];\n\nlet pixelBppCustomMapper = [\n // 0 - dummy entry\n function () {},\n\n // 1 - L\n // 0: 0, 1: 0, 2: 0, 3: 0xff\n function (pxData, pixelData, pxPos, maxBit) {\n let pixel = pixelData[0];\n pxData[pxPos] = pixel;\n pxData[pxPos + 1] = pixel;\n pxData[pxPos + 2] = pixel;\n pxData[pxPos + 3] = maxBit;\n },\n\n // 2 - LA\n // 0: 0, 1: 0, 2: 0, 3: 1\n function (pxData, pixelData, pxPos) {\n let pixel = pixelData[0];\n pxData[pxPos] = pixel;\n pxData[pxPos + 1] = pixel;\n pxData[pxPos + 2] = pixel;\n pxData[pxPos + 3] = pixelData[1];\n },\n\n // 3 - RGB\n // 0: 0, 1: 1, 2: 2, 3: 0xff\n function (pxData, pixelData, pxPos, maxBit) {\n pxData[pxPos] = pixelData[0];\n pxData[pxPos + 1] = pixelData[1];\n pxData[pxPos + 2] = pixelData[2];\n pxData[pxPos + 3] = maxBit;\n },\n\n // 4 - RGBA\n // 0: 0, 1: 1, 2: 2, 3: 3\n function (pxData, pixelData, pxPos) {\n pxData[pxPos] = pixelData[0];\n pxData[pxPos + 1] = pixelData[1];\n pxData[pxPos + 2] = pixelData[2];\n pxData[pxPos + 3] = pixelData[3];\n },\n];\n\nfunction bitRetriever(data, depth) {\n let leftOver = [];\n let i = 0;\n\n function split() {\n if (i === data.length) {\n throw new Error(\"Ran out of data\");\n }\n let byte = data[i];\n i++;\n let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;\n switch (depth) {\n default:\n throw new Error(\"unrecognised depth\");\n case 16:\n byte2 = data[i];\n i++;\n leftOver.push((byte << 8) + byte2);\n break;\n case 4:\n byte2 = byte & 0x0f;\n byte1 = byte >> 4;\n leftOver.push(byte1, byte2);\n break;\n case 2:\n byte4 = byte & 3;\n byte3 = (byte >> 2) & 3;\n byte2 = (byte >> 4) & 3;\n byte1 = (byte >> 6) & 3;\n leftOver.push(byte1, byte2, byte3, byte4);\n break;\n case 1:\n byte8 = byte & 1;\n byte7 = (byte >> 1) & 1;\n byte6 = (byte >> 2) & 1;\n byte5 = (byte >> 3) & 1;\n byte4 = (byte >> 4) & 1;\n byte3 = (byte >> 5) & 1;\n byte2 = (byte >> 6) & 1;\n byte1 = (byte >> 7) & 1;\n leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);\n break;\n }\n }\n\n return {\n get: function (count) {\n while (leftOver.length < count) {\n split();\n }\n let returner = leftOver.slice(0, count);\n leftOver = leftOver.slice(count);\n return returner;\n },\n resetAfterLine: function () {\n leftOver.length = 0;\n },\n end: function () {\n if (i !== data.length) {\n throw new Error(\"extra data found\");\n }\n },\n };\n}\n\nfunction mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) {\n // eslint-disable-line max-params\n let imageWidth = image.width;\n let imageHeight = image.height;\n let imagePass = image.index;\n for (let y = 0; y < imageHeight; y++) {\n for (let x = 0; x < imageWidth; x++) {\n let pxPos = getPxPos(x, y, imagePass);\n pixelBppMapper[bpp](pxData, data, pxPos, rawPos);\n rawPos += bpp; //eslint-disable-line no-param-reassign\n }\n }\n return rawPos;\n}\n\nfunction mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) {\n // eslint-disable-line max-params\n let imageWidth = image.width;\n let imageHeight = image.height;\n let imagePass = image.index;\n for (let y = 0; y < imageHeight; y++) {\n for (let x = 0; x < imageWidth; x++) {\n let pixelData = bits.get(bpp);\n let pxPos = getPxPos(x, y, imagePass);\n pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);\n }\n bits.resetAfterLine();\n }\n}\n\nexports.dataToBitMap = function (data, bitmapInfo) {\n let width = bitmapInfo.width;\n let height = bitmapInfo.height;\n let depth = bitmapInfo.depth;\n let bpp = bitmapInfo.bpp;\n let interlace = bitmapInfo.interlace;\n let bits;\n\n if (depth !== 8) {\n bits = bitRetriever(data, depth);\n }\n let pxData;\n if (depth <= 8) {\n pxData = Buffer.alloc(width * height * 4);\n } else {\n pxData = new Uint16Array(width * height * 4);\n }\n let maxBit = Math.pow(2, depth) - 1;\n let rawPos = 0;\n let images;\n let getPxPos;\n\n if (interlace) {\n images = interlaceUtils.getImagePasses(width, height);\n getPxPos = interlaceUtils.getInterlaceIterator(width, height);\n } else {\n let nonInterlacedPxPos = 0;\n getPxPos = function () {\n let returner = nonInterlacedPxPos;\n nonInterlacedPxPos += 4;\n return returner;\n };\n images = [{ width: width, height: height }];\n }\n\n for (let imageIndex = 0; imageIndex < images.length; imageIndex++) {\n if (depth === 8) {\n rawPos = mapImage8Bit(\n images[imageIndex],\n pxData,\n getPxPos,\n bpp,\n data,\n rawPos\n );\n } else {\n mapImageCustomBit(\n images[imageIndex],\n pxData,\n getPxPos,\n bpp,\n bits,\n maxBit\n );\n }\n }\n if (depth === 8) {\n if (rawPos !== data.length) {\n throw new Error(\"extra data found\");\n }\n } else {\n bits.end();\n }\n\n return pxData;\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./interlace\":11,\"buffer\":33}],2:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet constants = require(\"./constants\");\n\nmodule.exports = function (dataIn, width, height, options) {\n let outHasAlpha =\n [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(\n options.colorType\n ) !== -1;\n if (options.colorType === options.inputColorType) {\n let bigEndian = (function () {\n let buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 256, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] !== 256;\n })();\n // If no need to convert to grayscale and alpha is present/absent in both, take a fast route\n if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {\n return dataIn;\n }\n }\n\n // map to a UInt16 array if data is 16bit, fix endianness below\n let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);\n\n let maxValue = 255;\n let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];\n if (inBpp === 4 && !options.inputHasAlpha) {\n inBpp = 3;\n }\n let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];\n if (options.bitDepth === 16) {\n maxValue = 65535;\n outBpp *= 2;\n }\n let outData = Buffer.alloc(width * height * outBpp);\n\n let inIndex = 0;\n let outIndex = 0;\n\n let bgColor = options.bgColor || {};\n if (bgColor.red === undefined) {\n bgColor.red = maxValue;\n }\n if (bgColor.green === undefined) {\n bgColor.green = maxValue;\n }\n if (bgColor.blue === undefined) {\n bgColor.blue = maxValue;\n }\n\n function getRGBA() {\n let red;\n let green;\n let blue;\n let alpha = maxValue;\n switch (options.inputColorType) {\n case constants.COLORTYPE_COLOR_ALPHA:\n alpha = data[inIndex + 3];\n red = data[inIndex];\n green = data[inIndex + 1];\n blue = data[inIndex + 2];\n break;\n case constants.COLORTYPE_COLOR:\n red = data[inIndex];\n green = data[inIndex + 1];\n blue = data[inIndex + 2];\n break;\n case constants.COLORTYPE_ALPHA:\n alpha = data[inIndex + 1];\n red = data[inIndex];\n green = red;\n blue = red;\n break;\n case constants.COLORTYPE_GRAYSCALE:\n red = data[inIndex];\n green = red;\n blue = red;\n break;\n default:\n throw new Error(\n \"input color type:\" +\n options.inputColorType +\n \" is not supported at present\"\n );\n }\n\n if (options.inputHasAlpha) {\n if (!outHasAlpha) {\n alpha /= maxValue;\n red = Math.min(\n Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0),\n maxValue\n );\n green = Math.min(\n Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0),\n maxValue\n );\n blue = Math.min(\n Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0),\n maxValue\n );\n }\n }\n return { red: red, green: green, blue: blue, alpha: alpha };\n }\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n let rgba = getRGBA(data, inIndex);\n\n switch (options.colorType) {\n case constants.COLORTYPE_COLOR_ALPHA:\n case constants.COLORTYPE_COLOR:\n if (options.bitDepth === 8) {\n outData[outIndex] = rgba.red;\n outData[outIndex + 1] = rgba.green;\n outData[outIndex + 2] = rgba.blue;\n if (outHasAlpha) {\n outData[outIndex + 3] = rgba.alpha;\n }\n } else {\n outData.writeUInt16BE(rgba.red, outIndex);\n outData.writeUInt16BE(rgba.green, outIndex + 2);\n outData.writeUInt16BE(rgba.blue, outIndex + 4);\n if (outHasAlpha) {\n outData.writeUInt16BE(rgba.alpha, outIndex + 6);\n }\n }\n break;\n case constants.COLORTYPE_ALPHA:\n case constants.COLORTYPE_GRAYSCALE: {\n // Convert to grayscale and alpha\n let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;\n if (options.bitDepth === 8) {\n outData[outIndex] = grayscale;\n if (outHasAlpha) {\n outData[outIndex + 1] = rgba.alpha;\n }\n } else {\n outData.writeUInt16BE(grayscale, outIndex);\n if (outHasAlpha) {\n outData.writeUInt16BE(rgba.alpha, outIndex + 2);\n }\n }\n break;\n }\n default:\n throw new Error(\"unrecognised color Type \" + options.colorType);\n }\n\n inIndex += inBpp;\n outIndex += outBpp;\n }\n }\n\n return outData;\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./constants\":4,\"buffer\":33}],3:[function(require,module,exports){\n(function (process,Buffer){(function (){\n\"use strict\";\n\nlet util = require(\"util\");\nlet Stream = require(\"stream\");\n\nlet ChunkStream = (module.exports = function () {\n Stream.call(this);\n\n this._buffers = [];\n this._buffered = 0;\n\n this._reads = [];\n this._paused = false;\n\n this._encoding = \"utf8\";\n this.writable = true;\n});\nutil.inherits(ChunkStream, Stream);\n\nChunkStream.prototype.read = function (length, callback) {\n this._reads.push({\n length: Math.abs(length), // if length < 0 then at most this length\n allowLess: length < 0,\n func: callback,\n });\n\n process.nextTick(\n function () {\n this._process();\n\n // its paused and there is not enought data then ask for more\n if (this._paused && this._reads && this._reads.length > 0) {\n this._paused = false;\n\n this.emit(\"drain\");\n }\n }.bind(this)\n );\n};\n\nChunkStream.prototype.write = function (data, encoding) {\n if (!this.writable) {\n this.emit(\"error\", new Error(\"Stream not writable\"));\n return false;\n }\n\n let dataBuffer;\n if (Buffer.isBuffer(data)) {\n dataBuffer = data;\n } else {\n dataBuffer = Buffer.from(data, encoding || this._encoding);\n }\n\n this._buffers.push(dataBuffer);\n this._buffered += dataBuffer.length;\n\n this._process();\n\n // ok if there are no more read requests\n if (this._reads && this._reads.length === 0) {\n this._paused = true;\n }\n\n return this.writable && !this._paused;\n};\n\nChunkStream.prototype.end = function (data, encoding) {\n if (data) {\n this.write(data, encoding);\n }\n\n this.writable = false;\n\n // already destroyed\n if (!this._buffers) {\n return;\n }\n\n // enqueue or handle end\n if (this._buffers.length === 0) {\n this._end();\n } else {\n this._buffers.push(null);\n this._process();\n }\n};\n\nChunkStream.prototype.destroySoon = ChunkStream.prototype.end;\n\nChunkStream.prototype._end = function () {\n if (this._reads.length > 0) {\n this.emit(\"error\", new Error(\"Unexpected end of input\"));\n }\n\n this.destroy();\n};\n\nChunkStream.prototype.destroy = function () {\n if (!this._buffers) {\n return;\n }\n\n this.writable = false;\n this._reads = null;\n this._buffers = null;\n\n this.emit(\"close\");\n};\n\nChunkStream.prototype._processReadAllowingLess = function (read) {\n // ok there is any data so that we can satisfy this request\n this._reads.shift(); // == read\n\n // first we need to peek into first buffer\n let smallerBuf = this._buffers[0];\n\n // ok there is more data than we need\n if (smallerBuf.length > read.length) {\n this._buffered -= read.length;\n this._buffers[0] = smallerBuf.slice(read.length);\n\n read.func.call(this, smallerBuf.slice(0, read.length));\n } else {\n // ok this is less than maximum length so use it all\n this._buffered -= smallerBuf.length;\n this._buffers.shift(); // == smallerBuf\n\n read.func.call(this, smallerBuf);\n }\n};\n\nChunkStream.prototype._processRead = function (read) {\n this._reads.shift(); // == read\n\n let pos = 0;\n let count = 0;\n let data = Buffer.alloc(read.length);\n\n // create buffer for all data\n while (pos < read.length) {\n let buf = this._buffers[count++];\n let len = Math.min(buf.length, read.length - pos);\n\n buf.copy(data, pos, 0, len);\n pos += len;\n\n // last buffer wasn't used all so just slice it and leave\n if (len !== buf.length) {\n this._buffers[--count] = buf.slice(len);\n }\n }\n\n // remove all used buffers\n if (count > 0) {\n this._buffers.splice(0, count);\n }\n\n this._buffered -= read.length;\n\n read.func.call(this, data);\n};\n\nChunkStream.prototype._process = function () {\n try {\n // as long as there is any data and read requests\n while (this._buffered > 0 && this._reads && this._reads.length > 0) {\n let read = this._reads[0];\n\n // read any data (but no more than length)\n if (read.allowLess) {\n this._processReadAllowingLess(read);\n } else if (this._buffered >= read.length) {\n // ok we can meet some expectations\n\n this._processRead(read);\n } else {\n // not enought data to satisfy first request in queue\n // so we need to wait for more\n break;\n }\n }\n\n if (this._buffers && !this.writable) {\n this._end();\n }\n } catch (ex) {\n this.emit(\"error\", ex);\n }\n};\n\n}).call(this)}).call(this,require('_process'),require(\"buffer\").Buffer)\n},{\"_process\":60,\"buffer\":33,\"stream\":61,\"util\":81}],4:[function(require,module,exports){\n\"use strict\";\n\nmodule.exports = {\n PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],\n\n TYPE_IHDR: 0x49484452,\n TYPE_IEND: 0x49454e44,\n TYPE_IDAT: 0x49444154,\n TYPE_PLTE: 0x504c5445,\n TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase\n TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase\n\n // color-type bits\n COLORTYPE_GRAYSCALE: 0,\n COLORTYPE_PALETTE: 1,\n COLORTYPE_COLOR: 2,\n COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha\n\n // color-type combinations\n COLORTYPE_PALETTE_COLOR: 3,\n COLORTYPE_COLOR_ALPHA: 6,\n\n COLORTYPE_TO_BPP_MAP: {\n 0: 1,\n 2: 3,\n 3: 1,\n 4: 2,\n 6: 4,\n },\n\n GAMMA_DIVISION: 100000,\n};\n\n},{}],5:[function(require,module,exports){\n\"use strict\";\n\nlet crcTable = [];\n\n(function () {\n for (let i = 0; i < 256; i++) {\n let currentCrc = i;\n for (let j = 0; j < 8; j++) {\n if (currentCrc & 1) {\n currentCrc = 0xedb88320 ^ (currentCrc >>> 1);\n } else {\n currentCrc = currentCrc >>> 1;\n }\n }\n crcTable[i] = currentCrc;\n }\n})();\n\nlet CrcCalculator = (module.exports = function () {\n this._crc = -1;\n});\n\nCrcCalculator.prototype.write = function (data) {\n for (let i = 0; i < data.length; i++) {\n this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);\n }\n return true;\n};\n\nCrcCalculator.prototype.crc32 = function () {\n return this._crc ^ -1;\n};\n\nCrcCalculator.crc32 = function (buf) {\n let crc = -1;\n for (let i = 0; i < buf.length; i++) {\n crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);\n }\n return crc ^ -1;\n};\n\n},{}],6:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet paethPredictor = require(\"./paeth-predictor\");\n\nfunction filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {\n for (let x = 0; x < byteWidth; x++) {\n rawData[rawPos + x] = pxData[pxPos + x];\n }\n}\n\nfunction filterSumNone(pxData, pxPos, byteWidth) {\n let sum = 0;\n let length = pxPos + byteWidth;\n\n for (let i = pxPos; i < length; i++) {\n sum += Math.abs(pxData[i]);\n }\n return sum;\n}\n\nfunction filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let val = pxData[pxPos + x] - left;\n\n rawData[rawPos + x] = val;\n }\n}\n\nfunction filterSumSub(pxData, pxPos, byteWidth, bpp) {\n let sum = 0;\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let val = pxData[pxPos + x] - left;\n\n sum += Math.abs(val);\n }\n\n return sum;\n}\n\nfunction filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {\n for (let x = 0; x < byteWidth; x++) {\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let val = pxData[pxPos + x] - up;\n\n rawData[rawPos + x] = val;\n }\n}\n\nfunction filterSumUp(pxData, pxPos, byteWidth) {\n let sum = 0;\n let length = pxPos + byteWidth;\n for (let x = pxPos; x < length; x++) {\n let up = pxPos > 0 ? pxData[x - byteWidth] : 0;\n let val = pxData[x] - up;\n\n sum += Math.abs(val);\n }\n\n return sum;\n}\n\nfunction filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let val = pxData[pxPos + x] - ((left + up) >> 1);\n\n rawData[rawPos + x] = val;\n }\n}\n\nfunction filterSumAvg(pxData, pxPos, byteWidth, bpp) {\n let sum = 0;\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let val = pxData[pxPos + x] - ((left + up) >> 1);\n\n sum += Math.abs(val);\n }\n\n return sum;\n}\n\nfunction filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let upleft =\n pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;\n let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);\n\n rawData[rawPos + x] = val;\n }\n}\n\nfunction filterSumPaeth(pxData, pxPos, byteWidth, bpp) {\n let sum = 0;\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let upleft =\n pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;\n let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);\n\n sum += Math.abs(val);\n }\n\n return sum;\n}\n\nlet filters = {\n 0: filterNone,\n 1: filterSub,\n 2: filterUp,\n 3: filterAvg,\n 4: filterPaeth,\n};\n\nlet filterSums = {\n 0: filterSumNone,\n 1: filterSumSub,\n 2: filterSumUp,\n 3: filterSumAvg,\n 4: filterSumPaeth,\n};\n\nmodule.exports = function (pxData, width, height, options, bpp) {\n let filterTypes;\n if (!(\"filterType\" in options) || options.filterType === -1) {\n filterTypes = [0, 1, 2, 3, 4];\n } else if (typeof options.filterType === \"number\") {\n filterTypes = [options.filterType];\n } else {\n throw new Error(\"unrecognised filter types\");\n }\n\n if (options.bitDepth === 16) {\n bpp *= 2;\n }\n let byteWidth = width * bpp;\n let rawPos = 0;\n let pxPos = 0;\n let rawData = Buffer.alloc((byteWidth + 1) * height);\n\n let sel = filterTypes[0];\n\n for (let y = 0; y < height; y++) {\n if (filterTypes.length > 1) {\n // find best filter for this line (with lowest sum of values)\n let min = Infinity;\n\n for (let i = 0; i < filterTypes.length; i++) {\n let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);\n if (sum < min) {\n sel = filterTypes[i];\n min = sum;\n }\n }\n }\n\n rawData[rawPos] = sel;\n rawPos++;\n filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);\n rawPos += byteWidth;\n pxPos += byteWidth;\n }\n return rawData;\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./paeth-predictor\":15,\"buffer\":33}],7:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet util = require(\"util\");\nlet ChunkStream = require(\"./chunkstream\");\nlet Filter = require(\"./filter-parse\");\n\nlet FilterAsync = (module.exports = function (bitmapInfo) {\n ChunkStream.call(this);\n\n let buffers = [];\n let that = this;\n this._filter = new Filter(bitmapInfo, {\n read: this.read.bind(this),\n write: function (buffer) {\n buffers.push(buffer);\n },\n complete: function () {\n that.emit(\"complete\", Buffer.concat(buffers));\n },\n });\n\n this._filter.start();\n});\nutil.inherits(FilterAsync, ChunkStream);\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./chunkstream\":3,\"./filter-parse\":9,\"buffer\":33,\"util\":81}],8:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet SyncReader = require(\"./sync-reader\");\nlet Filter = require(\"./filter-parse\");\n\nexports.process = function (inBuffer, bitmapInfo) {\n let outBuffers = [];\n let reader = new SyncReader(inBuffer);\n let filter = new Filter(bitmapInfo, {\n read: reader.read.bind(reader),\n write: function (bufferPart) {\n outBuffers.push(bufferPart);\n },\n complete: function () {},\n });\n\n filter.start();\n reader.process();\n\n return Buffer.concat(outBuffers);\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./filter-parse\":9,\"./sync-reader\":22,\"buffer\":33}],9:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet interlaceUtils = require(\"./interlace\");\nlet paethPredictor = require(\"./paeth-predictor\");\n\nfunction getByteWidth(width, bpp, depth) {\n let byteWidth = width * bpp;\n if (depth !== 8) {\n byteWidth = Math.ceil(byteWidth / (8 / depth));\n }\n return byteWidth;\n}\n\nlet Filter = (module.exports = function (bitmapInfo, dependencies) {\n let width = bitmapInfo.width;\n let height = bitmapInfo.height;\n let interlace = bitmapInfo.interlace;\n let bpp = bitmapInfo.bpp;\n let depth = bitmapInfo.depth;\n\n this.read = dependencies.read;\n this.write = dependencies.write;\n this.complete = dependencies.complete;\n\n this._imageIndex = 0;\n this._images = [];\n if (interlace) {\n let passes = interlaceUtils.getImagePasses(width, height);\n for (let i = 0; i < passes.length; i++) {\n this._images.push({\n byteWidth: getByteWidth(passes[i].width, bpp, depth),\n height: passes[i].height,\n lineIndex: 0,\n });\n }\n } else {\n this._images.push({\n byteWidth: getByteWidth(width, bpp, depth),\n height: height,\n lineIndex: 0,\n });\n }\n\n // when filtering the line we look at the pixel to the left\n // the spec also says it is done on a byte level regardless of the number of pixels\n // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back\n // a pixel rather than just a different byte part. However if we are sub byte, we ignore.\n if (depth === 8) {\n this._xComparison = bpp;\n } else if (depth === 16) {\n this._xComparison = bpp * 2;\n } else {\n this._xComparison = 1;\n }\n});\n\nFilter.prototype.start = function () {\n this.read(\n this._images[this._imageIndex].byteWidth + 1,\n this._reverseFilterLine.bind(this)\n );\n};\n\nFilter.prototype._unFilterType1 = function (\n rawData,\n unfilteredLine,\n byteWidth\n) {\n let xComparison = this._xComparison;\n let xBiggerThan = xComparison - 1;\n\n for (let x = 0; x < byteWidth; x++) {\n let rawByte = rawData[1 + x];\n let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;\n unfilteredLine[x] = rawByte + f1Left;\n }\n};\n\nFilter.prototype._unFilterType2 = function (\n rawData,\n unfilteredLine,\n byteWidth\n) {\n let lastLine = this._lastLine;\n\n for (let x = 0; x < byteWidth; x++) {\n let rawByte = rawData[1 + x];\n let f2Up = lastLine ? lastLine[x] : 0;\n unfilteredLine[x] = rawByte + f2Up;\n }\n};\n\nFilter.prototype._unFilterType3 = function (\n rawData,\n unfilteredLine,\n byteWidth\n) {\n let xComparison = this._xComparison;\n let xBiggerThan = xComparison - 1;\n let lastLine = this._lastLine;\n\n for (let x = 0; x < byteWidth; x++) {\n let rawByte = rawData[1 + x];\n let f3Up = lastLine ? lastLine[x] : 0;\n let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;\n let f3Add = Math.floor((f3Left + f3Up) / 2);\n unfilteredLine[x] = rawByte + f3Add;\n }\n};\n\nFilter.prototype._unFilterType4 = function (\n rawData,\n unfilteredLine,\n byteWidth\n) {\n let xComparison = this._xComparison;\n let xBiggerThan = xComparison - 1;\n let lastLine = this._lastLine;\n\n for (let x = 0; x < byteWidth; x++) {\n let rawByte = rawData[1 + x];\n let f4Up = lastLine ? lastLine[x] : 0;\n let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;\n let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;\n let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);\n unfilteredLine[x] = rawByte + f4Add;\n }\n};\n\nFilter.prototype._reverseFilterLine = function (rawData) {\n let filter = rawData[0];\n let unfilteredLine;\n let currentImage = this._images[this._imageIndex];\n let byteWidth = currentImage.byteWidth;\n\n if (filter === 0) {\n unfilteredLine = rawData.slice(1, byteWidth + 1);\n } else {\n unfilteredLine = Buffer.alloc(byteWidth);\n\n switch (filter) {\n case 1:\n this._unFilterType1(rawData, unfilteredLine, byteWidth);\n break;\n case 2:\n this._unFilterType2(rawData, unfilteredLine, byteWidth);\n break;\n case 3:\n this._unFilterType3(rawData, unfilteredLine, byteWidth);\n break;\n case 4:\n this._unFilterType4(rawData, unfilteredLine, byteWidth);\n break;\n default:\n throw new Error(\"Unrecognised filter type - \" + filter);\n }\n }\n\n this.write(unfilteredLine);\n\n currentImage.lineIndex++;\n if (currentImage.lineIndex >= currentImage.height) {\n this._lastLine = null;\n this._imageIndex++;\n currentImage = this._images[this._imageIndex];\n } else {\n this._lastLine = unfilteredLine;\n }\n\n if (currentImage) {\n // read, using the byte width that may be from the new current image\n this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));\n } else {\n this._lastLine = null;\n this.complete();\n }\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./interlace\":11,\"./paeth-predictor\":15,\"buffer\":33}],10:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nfunction dePalette(indata, outdata, width, height, palette) {\n let pxPos = 0;\n // use values from palette\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n let color = palette[indata[pxPos]];\n\n if (!color) {\n throw new Error(\"index \" + indata[pxPos] + \" not in palette\");\n }\n\n for (let i = 0; i < 4; i++) {\n outdata[pxPos + i] = color[i];\n }\n pxPos += 4;\n }\n }\n}\n\nfunction replaceTransparentColor(indata, outdata, width, height, transColor) {\n let pxPos = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n let makeTrans = false;\n\n if (transColor.length === 1) {\n if (transColor[0] === indata[pxPos]) {\n makeTrans = true;\n }\n } else if (\n transColor[0] === indata[pxPos] &&\n transColor[1] === indata[pxPos + 1] &&\n transColor[2] === indata[pxPos + 2]\n ) {\n makeTrans = true;\n }\n if (makeTrans) {\n for (let i = 0; i < 4; i++) {\n outdata[pxPos + i] = 0;\n }\n }\n pxPos += 4;\n }\n }\n}\n\nfunction scaleDepth(indata, outdata, width, height, depth) {\n let maxOutSample = 255;\n let maxInSample = Math.pow(2, depth) - 1;\n let pxPos = 0;\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n for (let i = 0; i < 4; i++) {\n outdata[pxPos + i] = Math.floor(\n (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5\n );\n }\n pxPos += 4;\n }\n }\n}\n\nmodule.exports = function (indata, imageData, skipRescale = false) {\n let depth = imageData.depth;\n let width = imageData.width;\n let height = imageData.height;\n let colorType = imageData.colorType;\n let transColor = imageData.transColor;\n let palette = imageData.palette;\n\n let outdata = indata; // only different for 16 bits\n\n if (colorType === 3) {\n // paletted\n dePalette(indata, outdata, width, height, palette);\n } else {\n if (transColor) {\n replaceTransparentColor(indata, outdata, width, height, transColor);\n }\n // if it needs scaling\n if (depth !== 8 && !skipRescale) {\n // if we need to change the buffer size\n if (depth === 16) {\n outdata = Buffer.alloc(width * height * 4);\n }\n scaleDepth(indata, outdata, width, height, depth);\n }\n }\n return outdata;\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"buffer\":33}],11:[function(require,module,exports){\n\"use strict\";\n\n// Adam 7\n// 0 1 2 3 4 5 6 7\n// 0 x 6 4 6 x 6 4 6\n// 1 7 7 7 7 7 7 7 7\n// 2 5 6 5 6 5 6 5 6\n// 3 7 7 7 7 7 7 7 7\n// 4 3 6 4 6 3 6 4 6\n// 5 7 7 7 7 7 7 7 7\n// 6 5 6 5 6 5 6 5 6\n// 7 7 7 7 7 7 7 7 7\n\nlet imagePasses = [\n {\n // pass 1 - 1px\n x: [0],\n y: [0],\n },\n {\n // pass 2 - 1px\n x: [4],\n y: [0],\n },\n {\n // pass 3 - 2px\n x: [0, 4],\n y: [4],\n },\n {\n // pass 4 - 4px\n x: [2, 6],\n y: [0, 4],\n },\n {\n // pass 5 - 8px\n x: [0, 2, 4, 6],\n y: [2, 6],\n },\n {\n // pass 6 - 16px\n x: [1, 3, 5, 7],\n y: [0, 2, 4, 6],\n },\n {\n // pass 7 - 32px\n x: [0, 1, 2, 3, 4, 5, 6, 7],\n y: [1, 3, 5, 7],\n },\n];\n\nexports.getImagePasses = function (width, height) {\n let images = [];\n let xLeftOver = width % 8;\n let yLeftOver = height % 8;\n let xRepeats = (width - xLeftOver) / 8;\n let yRepeats = (height - yLeftOver) / 8;\n for (let i = 0; i < imagePasses.length; i++) {\n let pass = imagePasses[i];\n let passWidth = xRepeats * pass.x.length;\n let passHeight = yRepeats * pass.y.length;\n for (let j = 0; j < pass.x.length; j++) {\n if (pass.x[j] < xLeftOver) {\n passWidth++;\n } else {\n break;\n }\n }\n for (let j = 0; j < pass.y.length; j++) {\n if (pass.y[j] < yLeftOver) {\n passHeight++;\n } else {\n break;\n }\n }\n if (passWidth > 0 && passHeight > 0) {\n images.push({ width: passWidth, height: passHeight, index: i });\n }\n }\n return images;\n};\n\nexports.getInterlaceIterator = function (width) {\n return function (x, y, pass) {\n let outerXLeftOver = x % imagePasses[pass].x.length;\n let outerX =\n ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 +\n imagePasses[pass].x[outerXLeftOver];\n let outerYLeftOver = y % imagePasses[pass].y.length;\n let outerY =\n ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 +\n imagePasses[pass].y[outerYLeftOver];\n return outerX * 4 + outerY * width * 4;\n };\n};\n\n},{}],12:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet util = require(\"util\");\nlet Stream = require(\"stream\");\nlet constants = require(\"./constants\");\nlet Packer = require(\"./packer\");\n\nlet PackerAsync = (module.exports = function (opt) {\n Stream.call(this);\n\n let options = opt || {};\n\n this._packer = new Packer(options);\n this._deflate = this._packer.createDeflate();\n\n this.readable = true;\n});\nutil.inherits(PackerAsync, Stream);\n\nPackerAsync.prototype.pack = function (data, width, height, gamma) {\n // Signature\n this.emit(\"data\", Buffer.from(constants.PNG_SIGNATURE));\n this.emit(\"data\", this._packer.packIHDR(width, height));\n\n if (gamma) {\n this.emit(\"data\", this._packer.packGAMA(gamma));\n }\n\n let filteredData = this._packer.filterData(data, width, height);\n\n // compress it\n this._deflate.on(\"error\", this.emit.bind(this, \"error\"));\n\n this._deflate.on(\n \"data\",\n function (compressedData) {\n this.emit(\"data\", this._packer.packIDAT(compressedData));\n }.bind(this)\n );\n\n this._deflate.on(\n \"end\",\n function () {\n this.emit(\"data\", this._packer.packIEND());\n this.emit(\"end\");\n }.bind(this)\n );\n\n this._deflate.end(filteredData);\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./constants\":4,\"./packer\":14,\"buffer\":33,\"stream\":61,\"util\":81}],13:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet hasSyncZlib = true;\nlet zlib = require(\"zlib\");\nif (!zlib.deflateSync) {\n hasSyncZlib = false;\n}\nlet constants = require(\"./constants\");\nlet Packer = require(\"./packer\");\n\nmodule.exports = function (metaData, opt) {\n if (!hasSyncZlib) {\n throw new Error(\n \"To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0\"\n );\n }\n\n let options = opt || {};\n\n let packer = new Packer(options);\n\n let chunks = [];\n\n // Signature\n chunks.push(Buffer.from(constants.PNG_SIGNATURE));\n\n // Header\n chunks.push(packer.packIHDR(metaData.width, metaData.height));\n\n if (metaData.gamma) {\n chunks.push(packer.packGAMA(metaData.gamma));\n }\n\n let filteredData = packer.filterData(\n metaData.data,\n metaData.width,\n metaData.height\n );\n\n // compress it\n let compressedData = zlib.deflateSync(\n filteredData,\n packer.getDeflateOptions()\n );\n filteredData = null;\n\n if (!compressedData || !compressedData.length) {\n throw new Error(\"bad png - invalid compressed data response\");\n }\n chunks.push(packer.packIDAT(compressedData));\n\n // End\n chunks.push(packer.packIEND());\n\n return Buffer.concat(chunks);\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./constants\":4,\"./packer\":14,\"buffer\":33,\"zlib\":32}],14:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet constants = require(\"./constants\");\nlet CrcStream = require(\"./crc\");\nlet bitPacker = require(\"./bitpacker\");\nlet filter = require(\"./filter-pack\");\nlet zlib = require(\"zlib\");\n\nlet Packer = (module.exports = function (options) {\n this._options = options;\n\n options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;\n options.deflateLevel =\n options.deflateLevel != null ? options.deflateLevel : 9;\n options.deflateStrategy =\n options.deflateStrategy != null ? options.deflateStrategy : 3;\n options.inputHasAlpha =\n options.inputHasAlpha != null ? options.inputHasAlpha : true;\n options.deflateFactory = options.deflateFactory || zlib.createDeflate;\n options.bitDepth = options.bitDepth || 8;\n // This is outputColorType\n options.colorType =\n typeof options.colorType === \"number\"\n ? options.colorType\n : constants.COLORTYPE_COLOR_ALPHA;\n options.inputColorType =\n typeof options.inputColorType === \"number\"\n ? options.inputColorType\n : constants.COLORTYPE_COLOR_ALPHA;\n\n if (\n [\n constants.COLORTYPE_GRAYSCALE,\n constants.COLORTYPE_COLOR,\n constants.COLORTYPE_COLOR_ALPHA,\n constants.COLORTYPE_ALPHA,\n ].indexOf(options.colorType) === -1\n ) {\n throw new Error(\n \"option color type:\" + options.colorType + \" is not supported at present\"\n );\n }\n if (\n [\n constants.COLORTYPE_GRAYSCALE,\n constants.COLORTYPE_COLOR,\n constants.COLORTYPE_COLOR_ALPHA,\n constants.COLORTYPE_ALPHA,\n ].indexOf(options.inputColorType) === -1\n ) {\n throw new Error(\n \"option input color type:\" +\n options.inputColorType +\n \" is not supported at present\"\n );\n }\n if (options.bitDepth !== 8 && options.bitDepth !== 16) {\n throw new Error(\n \"option bit depth:\" + options.bitDepth + \" is not supported at present\"\n );\n }\n});\n\nPacker.prototype.getDeflateOptions = function () {\n return {\n chunkSize: this._options.deflateChunkSize,\n level: this._options.deflateLevel,\n strategy: this._options.deflateStrategy,\n };\n};\n\nPacker.prototype.createDeflate = function () {\n return this._options.deflateFactory(this.getDeflateOptions());\n};\n\nPacker.prototype.filterData = function (data, width, height) {\n // convert to correct format for filtering (e.g. right bpp and bit depth)\n let packedData = bitPacker(data, width, height, this._options);\n\n // filter pixel data\n let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];\n let filteredData = filter(packedData, width, height, this._options, bpp);\n return filteredData;\n};\n\nPacker.prototype._packChunk = function (type, data) {\n let len = data ? data.length : 0;\n let buf = Buffer.alloc(len + 12);\n\n buf.writeUInt32BE(len, 0);\n buf.writeUInt32BE(type, 4);\n\n if (data) {\n data.copy(buf, 8);\n }\n\n buf.writeInt32BE(\n CrcStream.crc32(buf.slice(4, buf.length - 4)),\n buf.length - 4\n );\n return buf;\n};\n\nPacker.prototype.packGAMA = function (gamma) {\n let buf = Buffer.alloc(4);\n buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);\n return this._packChunk(constants.TYPE_gAMA, buf);\n};\n\nPacker.prototype.packIHDR = function (width, height) {\n let buf = Buffer.alloc(13);\n buf.writeUInt32BE(width, 0);\n buf.writeUInt32BE(height, 4);\n buf[8] = this._options.bitDepth; // Bit depth\n buf[9] = this._options.colorType; // colorType\n buf[10] = 0; // compression\n buf[11] = 0; // filter\n buf[12] = 0; // interlace\n\n return this._packChunk(constants.TYPE_IHDR, buf);\n};\n\nPacker.prototype.packIDAT = function (data) {\n return this._packChunk(constants.TYPE_IDAT, data);\n};\n\nPacker.prototype.packIEND = function () {\n return this._packChunk(constants.TYPE_IEND, null);\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./bitpacker\":2,\"./constants\":4,\"./crc\":5,\"./filter-pack\":6,\"buffer\":33,\"zlib\":32}],15:[function(require,module,exports){\n\"use strict\";\n\nmodule.exports = function paethPredictor(left, above, upLeft) {\n let paeth = left + above - upLeft;\n let pLeft = Math.abs(paeth - left);\n let pAbove = Math.abs(paeth - above);\n let pUpLeft = Math.abs(paeth - upLeft);\n\n if (pLeft <= pAbove && pLeft <= pUpLeft) {\n return left;\n }\n if (pAbove <= pUpLeft) {\n return above;\n }\n return upLeft;\n};\n\n},{}],16:[function(require,module,exports){\n\"use strict\";\n\nlet util = require(\"util\");\nlet zlib = require(\"zlib\");\nlet ChunkStream = require(\"./chunkstream\");\nlet FilterAsync = require(\"./filter-parse-async\");\nlet Parser = require(\"./parser\");\nlet bitmapper = require(\"./bitmapper\");\nlet formatNormaliser = require(\"./format-normaliser\");\n\nlet ParserAsync = (module.exports = function (options) {\n ChunkStream.call(this);\n\n this._parser = new Parser(options, {\n read: this.read.bind(this),\n error: this._handleError.bind(this),\n metadata: this._handleMetaData.bind(this),\n gamma: this.emit.bind(this, \"gamma\"),\n palette: this._handlePalette.bind(this),\n transColor: this._handleTransColor.bind(this),\n finished: this._finished.bind(this),\n inflateData: this._inflateData.bind(this),\n simpleTransparency: this._simpleTransparency.bind(this),\n headersFinished: this._headersFinished.bind(this),\n });\n this._options = options;\n this.writable = true;\n\n this._parser.start();\n});\nutil.inherits(ParserAsync, ChunkStream);\n\nParserAsync.prototype._handleError = function (err) {\n this.emit(\"error\", err);\n\n this.writable = false;\n\n this.destroy();\n\n if (this._inflate && this._inflate.destroy) {\n this._inflate.destroy();\n }\n\n if (this._filter) {\n this._filter.destroy();\n // For backward compatibility with Node 7 and below.\n // Suppress errors due to _inflate calling write() even after\n // it's destroy()'ed.\n this._filter.on(\"error\", function () {});\n }\n\n this.errord = true;\n};\n\nParserAsync.prototype._inflateData = function (data) {\n if (!this._inflate) {\n if (this._bitmapInfo.interlace) {\n this._inflate = zlib.createInflate();\n\n this._inflate.on(\"error\", this.emit.bind(this, \"error\"));\n this._filter.on(\"complete\", this._complete.bind(this));\n\n this._inflate.pipe(this._filter);\n } else {\n let rowSize =\n ((this._bitmapInfo.width *\n this._bitmapInfo.bpp *\n this._bitmapInfo.depth +\n 7) >>\n 3) +\n 1;\n let imageSize = rowSize * this._bitmapInfo.height;\n let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);\n\n this._inflate = zlib.createInflate({ chunkSize: chunkSize });\n let leftToInflate = imageSize;\n\n let emitError = this.emit.bind(this, \"error\");\n this._inflate.on(\"error\", function (err) {\n if (!leftToInflate) {\n return;\n }\n\n emitError(err);\n });\n this._filter.on(\"complete\", this._complete.bind(this));\n\n let filterWrite = this._filter.write.bind(this._filter);\n this._inflate.on(\"data\", function (chunk) {\n if (!leftToInflate) {\n return;\n }\n\n if (chunk.length > leftToInflate) {\n chunk = chunk.slice(0, leftToInflate);\n }\n\n leftToInflate -= chunk.length;\n\n filterWrite(chunk);\n });\n\n this._inflate.on(\"end\", this._filter.end.bind(this._filter));\n }\n }\n this._inflate.write(data);\n};\n\nParserAsync.prototype._handleMetaData = function (metaData) {\n this._metaData = metaData;\n this._bitmapInfo = Object.create(metaData);\n\n this._filter = new FilterAsync(this._bitmapInfo);\n};\n\nParserAsync.prototype._handleTransColor = function (transColor) {\n this._bitmapInfo.transColor = transColor;\n};\n\nParserAsync.prototype._handlePalette = function (palette) {\n this._bitmapInfo.palette = palette;\n};\n\nParserAsync.prototype._simpleTransparency = function () {\n this._metaData.alpha = true;\n};\n\nParserAsync.prototype._headersFinished = function () {\n // Up until this point, we don't know if we have a tRNS chunk (alpha)\n // so we can't emit metadata any earlier\n this.emit(\"metadata\", this._metaData);\n};\n\nParserAsync.prototype._finished = function () {\n if (this.errord) {\n return;\n }\n\n if (!this._inflate) {\n this.emit(\"error\", \"No Inflate block\");\n } else {\n // no more data to inflate\n this._inflate.end();\n }\n};\n\nParserAsync.prototype._complete = function (filteredData) {\n if (this.errord) {\n return;\n }\n\n let normalisedBitmapData;\n\n try {\n let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);\n\n normalisedBitmapData = formatNormaliser(\n bitmapData,\n this._bitmapInfo,\n this._options.skipRescale\n );\n bitmapData = null;\n } catch (ex) {\n this._handleError(ex);\n return;\n }\n\n this.emit(\"parsed\", normalisedBitmapData);\n};\n\n},{\"./bitmapper\":1,\"./chunkstream\":3,\"./filter-parse-async\":7,\"./format-normaliser\":10,\"./parser\":18,\"util\":81,\"zlib\":32}],17:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet hasSyncZlib = true;\nlet zlib = require(\"zlib\");\nlet inflateSync = require(\"./sync-inflate\");\nif (!zlib.deflateSync) {\n hasSyncZlib = false;\n}\nlet SyncReader = require(\"./sync-reader\");\nlet FilterSync = require(\"./filter-parse-sync\");\nlet Parser = require(\"./parser\");\nlet bitmapper = require(\"./bitmapper\");\nlet formatNormaliser = require(\"./format-normaliser\");\n\nmodule.exports = function (buffer, options) {\n if (!hasSyncZlib) {\n throw new Error(\n \"To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0\"\n );\n }\n\n let err;\n function handleError(_err_) {\n err = _err_;\n }\n\n let metaData;\n function handleMetaData(_metaData_) {\n metaData = _metaData_;\n }\n\n function handleTransColor(transColor) {\n metaData.transColor = transColor;\n }\n\n function handlePalette(palette) {\n metaData.palette = palette;\n }\n\n function handleSimpleTransparency() {\n metaData.alpha = true;\n }\n\n let gamma;\n function handleGamma(_gamma_) {\n gamma = _gamma_;\n }\n\n let inflateDataList = [];\n function handleInflateData(inflatedData) {\n inflateDataList.push(inflatedData);\n }\n\n let reader = new SyncReader(buffer);\n\n let parser = new Parser(options, {\n read: reader.read.bind(reader),\n error: handleError,\n metadata: handleMetaData,\n gamma: handleGamma,\n palette: handlePalette,\n transColor: handleTransColor,\n inflateData: handleInflateData,\n simpleTransparency: handleSimpleTransparency,\n });\n\n parser.start();\n reader.process();\n\n if (err) {\n throw err;\n }\n\n //join together the inflate datas\n let inflateData = Buffer.concat(inflateDataList);\n inflateDataList.length = 0;\n\n let inflatedData;\n if (metaData.interlace) {\n inflatedData = zlib.inflateSync(inflateData);\n } else {\n let rowSize =\n ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;\n let imageSize = rowSize * metaData.height;\n inflatedData = inflateSync(inflateData, {\n chunkSize: imageSize,\n maxLength: imageSize,\n });\n }\n inflateData = null;\n\n if (!inflatedData || !inflatedData.length) {\n throw new Error(\"bad png - invalid inflate data response\");\n }\n\n let unfilteredData = FilterSync.process(inflatedData, metaData);\n inflateData = null;\n\n let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);\n unfilteredData = null;\n\n let normalisedBitmapData = formatNormaliser(\n bitmapData,\n metaData,\n options.skipRescale\n );\n\n metaData.data = normalisedBitmapData;\n metaData.gamma = gamma || 0;\n\n return metaData;\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./bitmapper\":1,\"./filter-parse-sync\":8,\"./format-normaliser\":10,\"./parser\":18,\"./sync-inflate\":21,\"./sync-reader\":22,\"buffer\":33,\"zlib\":32}],18:[function(require,module,exports){\n(function (Buffer){(function (){\n\"use strict\";\n\nlet constants = require(\"./constants\");\nlet CrcCalculator = require(\"./crc\");\n\nlet Parser = (module.exports = function (options, dependencies) {\n this._options = options;\n options.checkCRC = options.checkCRC !== false;\n\n this._hasIHDR = false;\n this._hasIEND = false;\n this._emittedHeadersFinished = false;\n\n // input flags/metadata\n this._palette = [];\n this._colorType = 0;\n\n this._chunks = {};\n this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);\n this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);\n this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);\n this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);\n this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);\n this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);\n\n this.read = dependencies.read;\n this.error = dependencies.error;\n this.metadata = dependencies.metadata;\n this.gamma = dependencies.gamma;\n this.transColor = dependencies.transColor;\n this.palette = dependencies.palette;\n this.parsed = dependencies.parsed;\n this.inflateData = dependencies.inflateData;\n this.finished = dependencies.finished;\n this.simpleTransparency = dependencies.simpleTransparency;\n this.headersFinished = dependencies.headersFinished || function () {};\n});\n\nParser.prototype.start = function () {\n this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));\n};\n\nParser.prototype._parseSignature = function (data) {\n let signature = constants.PNG_SIGNATURE;\n\n for (let i = 0; i < signature.length; i++) {\n if (data[i] !== signature[i]) {\n this.error(new Error(\"Invalid file signature\"));\n return;\n }\n }\n this.read(8, this._parseChunkBegin.bind(this));\n};\n\nParser.prototype._parseChunkBegin = function (data) {\n // chunk content length\n let length = data.readUInt32BE(0);\n\n // chunk type\n let type = data.readUInt32BE(4);\n let name = \"\";\n for (let i = 4; i < 8; i++) {\n name += String.fromCharCode(data[i]);\n }\n\n //console.log('chunk ', name, length);\n\n // chunk flags\n let ancillary = Boolean(data[4] & 0x20); // or critical\n // priv = Boolean(data[5] & 0x20), // or public\n // safeToCopy = Boolean(data[7] & 0x20); // or unsafe\n\n if (!this._hasIHDR && type !== constants.TYPE_IHDR) {\n this.error(new Error(\"Expected IHDR on beggining\"));\n return;\n }\n\n this._crc = new CrcCalculator();\n this._crc.write(Buffer.from(name));\n\n if (this._chunks[type]) {\n return this._chunks[type](length);\n }\n\n if (!ancillary) {\n this.error(new Error(\"Unsupported critical chunk type \" + name));\n return;\n }\n\n this.read(length + 4, this._skipChunk.bind(this));\n};\n\nParser.prototype._skipChunk = function (/*data*/) {\n this.read(8, this._parseChunkBegin.bind(this));\n};\n\nParser.prototype._handleChunkEnd = function () {\n this.read(4, this._parseChunkEnd.bind(this));\n};\n\nParser.prototype._parseChunkEnd = function (data) {\n let fileCrc = data.readInt32BE(0);\n let calcCrc = this._crc.crc32();\n\n // check CRC\n if (this._options.checkCRC && calcCrc !== fileCrc) {\n this.error(new Error(\"Crc error - \" + fileCrc + \" - \" + calcCrc));\n return;\n }\n\n if (!this._hasIEND) {\n this.read(8, this._parseChunkBegin.bind(this));\n }\n};\n\nParser.prototype._handleIHDR = function (length) {\n this.read(length, this._parseIHDR.bind(this));\n};\nParser.prototype._parseIHDR = function (data) {\n this._crc.write(data);\n\n let width = data.readUInt32BE(0);\n let height = data.readUInt32BE(4);\n let depth = data[8];\n let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha\n let compr = data[10];\n let filter = data[11];\n let interlace = data[12];\n\n // console.log(' width', width, 'height', height,\n // 'depth', depth, 'colorType', colorType,\n // 'compr', compr, 'filter', filter, 'interlace', interlace\n // );\n\n if (\n depth !== 8 &&\n depth !== 4 &&\n depth !== 2 &&\n depth !== 1 &&\n depth !== 16\n ) {\n this.error(new Error(\"Unsupported bit depth \" + depth));\n return;\n }\n if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {\n this.error(new Error(\"Unsupported color type\"));\n return;\n }\n if (compr !== 0) {\n this.error(new Error(\"Unsupported compression method\"));\n return;\n }\n if (filter !== 0) {\n this.error(new Error(\"Unsupported filter method\"));\n return;\n }\n if (interlace !== 0 && interlace !== 1) {\n this.error(new Error(\"Unsupported interlace method\"));\n return;\n }\n\n this._colorType = colorType;\n\n let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];\n\n this._hasIHDR = true;\n\n this.metadata({\n width: width,\n height: height,\n depth: depth,\n interlace: Boolean(interlace),\n palette: Boolean(colorType & constants.COLORTYPE_PALETTE),\n color: Boolean(colorType & constants.COLORTYPE_COLOR),\n alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),\n bpp: bpp,\n colorType: colorType,\n });\n\n this._handleChunkEnd();\n};\n\nParser.prototype._handlePLTE = function (length) {\n this.read(length, this._parsePLTE.bind(this));\n};\nParser.prototype._parsePLTE = function (data) {\n this._crc.write(data);\n\n let entries = Math.floor(data.length / 3);\n // console.log('Palette:', entries);\n\n for (let i = 0; i < entries; i++) {\n this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]);\n }\n\n this.palette(this._palette);\n\n this._handleChunkEnd();\n};\n\nParser.prototype._handleTRNS = function (length) {\n this.simpleTransparency();\n this.read(length, this._parseTRNS.bind(this));\n};\nParser.prototype._parseTRNS = function (data) {\n this._crc.write(data);\n\n // palette\n if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {\n if (this._palette.length === 0) {\n this.error(new Error(\"Transparency chunk must be after palette\"));\n return;\n }\n if (data.length > this._palette.length) {\n this.error(new Error(\"More transparent colors than palette size\"));\n return;\n }\n for (let i = 0; i < data.length; i++) {\n this._palette[i][3] = data[i];\n }\n this.palette(this._palette);\n }\n\n // for colorType 0 (grayscale) and 2 (rgb)\n // there might be one gray/color defined as transparent\n if (this._colorType === constants.COLORTYPE_GRAYSCALE) {\n // grey, 2 bytes\n this.transColor([data.readUInt16BE(0)]);\n }\n if (this._colorType === constants.COLORTYPE_COLOR) {\n this.transColor([\n data.readUInt16BE(0),\n data.readUInt16BE(2),\n data.readUInt16BE(4),\n ]);\n }\n\n this._handleChunkEnd();\n};\n\nParser.prototype._handleGAMA = function (length) {\n this.read(length, this._parseGAMA.bind(this));\n};\nParser.prototype._parseGAMA = function (data) {\n this._crc.write(data);\n this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);\n\n this._handleChunkEnd();\n};\n\nParser.prototype._handleIDAT = function (length) {\n if (!this._emittedHeadersFinished) {\n this._emittedHeadersFinished = true;\n this.headersFinished();\n }\n this.read(-length, this._parseIDAT.bind(this, length));\n};\nParser.prototype._parseIDAT = function (length, data) {\n this._crc.write(data);\n\n if (\n this._colorType === constants.COLORTYPE_PALETTE_COLOR &&\n this._palette.length === 0\n ) {\n throw new Error(\"Expected palette not found\");\n }\n\n this.inflateData(data);\n let leftOverLength = length - data.length;\n\n if (leftOverLength > 0) {\n this._handleIDAT(leftOverLength);\n } else {\n this._handleChunkEnd();\n }\n};\n\nParser.prototype._handleIEND = function (length) {\n this.read(length, this._parseIEND.bind(this));\n};\nParser.prototype._parseIEND = function (data) {\n this._crc.write(data);\n\n this._hasIEND = true;\n this._handleChunkEnd();\n\n if (this.finished) {\n this.finished();\n }\n};\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"./constants\":4,\"./crc\":5,\"buffer\":33}],19:[function(require,module,exports){\n\"use strict\";\n\nlet parse = require(\"./parser-sync\");\nlet pack = require(\"./packer-sync\");\n\nexports.read = function (buffer, options) {\n return parse(buffer, options || {});\n};\n\nexports.write = function (png, options) {\n return pack(png, options);\n};\n\n},{\"./packer-sync\":13,\"./parser-sync\":17}],20:[function(require,module,exports){\n(function (process,Buffer){(function (){\n\"use strict\";\n\nlet util = require(\"util\");\nlet Stream = require(\"stream\");\nlet Parser = require(\"./parser-async\");\nlet Packer = require(\"./packer-async\");\nlet PNGSync = require(\"./png-sync\");\n\nlet PNG = (exports.PNG = function (options) {\n Stream.call(this);\n\n options = options || {}; // eslint-disable-line no-param-reassign\n\n // coerce pixel dimensions to integers (also coerces undefined -> 0):\n this.width = options.width | 0;\n this.height = options.height | 0;\n\n this.data =\n this.width > 0 && this.height > 0\n ? Buffer.alloc(4 * this.width * this.height)\n : null;\n\n if (options.fill && this.data) {\n this.data.fill(0);\n }\n\n this.gamma = 0;\n this.readable = this.writable = true;\n\n this._parser = new Parser(options);\n\n this._parser.on(\"error\", this.emit.bind(this, \"error\"));\n this._parser.on(\"close\", this._handleClose.bind(this));\n this._parser.on(\"metadata\", this._metadata.bind(this));\n this._parser.on(\"gamma\", this._gamma.bind(this));\n this._parser.on(\n \"parsed\",\n function (data) {\n this.data = data;\n this.emit(\"parsed\", data);\n }.bind(this)\n );\n\n this._packer = new Packer(options);\n this._packer.on(\"data\", this.emit.bind(this, \"data\"));\n this._packer.on(\"end\", this.emit.bind(this, \"end\"));\n this._parser.on(\"close\", this._handleClose.bind(this));\n this._packer.on(\"error\", this.emit.bind(this, \"error\"));\n});\nutil.inherits(PNG, Stream);\n\nPNG.sync = PNGSync;\n\nPNG.prototype.pack = function () {\n if (!this.data || !this.data.length) {\n this.emit(\"error\", \"No data provided\");\n return this;\n }\n\n process.nextTick(\n function () {\n this._packer.pack(this.data, this.width, this.height, this.gamma);\n }.bind(this)\n );\n\n return this;\n};\n\nPNG.prototype.parse = function (data, callback) {\n if (callback) {\n let onParsed, onError;\n\n onParsed = function (parsedData) {\n this.removeListener(\"error\", onError);\n\n this.data = parsedData;\n callback(null, this);\n }.bind(this);\n\n onError = function (err) {\n this.removeListener(\"parsed\", onParsed);\n\n callback(err, null);\n }.bind(this);\n\n this.once(\"parsed\", onParsed);\n this.once(\"error\", onError);\n }\n\n this.end(data);\n return this;\n};\n\nPNG.prototype.write = function (data) {\n this._parser.write(data);\n return true;\n};\n\nPNG.prototype.end = function (data) {\n this._parser.end(data);\n};\n\nPNG.prototype._metadata = function (metadata) {\n this.width = metadata.width;\n this.height = metadata.height;\n\n this.emit(\"metadata\", metadata);\n};\n\nPNG.prototype._gamma = function (gamma) {\n this.gamma = gamma;\n};\n\nPNG.prototype._handleClose = function () {\n if (!this._parser.writable && !this._packer.readable) {\n this.emit(\"close\");\n }\n};\n\nPNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) {\n // eslint-disable-line max-params\n // coerce pixel dimensions to integers (also coerces undefined -> 0):\n /* eslint-disable no-param-reassign */\n srcX |= 0;\n srcY |= 0;\n width |= 0;\n height |= 0;\n deltaX |= 0;\n deltaY |= 0;\n /* eslint-enable no-param-reassign */\n\n if (\n srcX > src.width ||\n srcY > src.height ||\n srcX + width > src.width ||\n srcY + height > src.height\n ) {\n throw new Error(\"bitblt reading outside image\");\n }\n\n if (\n deltaX > dst.width ||\n deltaY > dst.height ||\n deltaX + width > dst.width ||\n deltaY + height > dst.height\n ) {\n throw new Error(\"bitblt writing outside image\");\n }\n\n for (let y = 0; y < height; y++) {\n src.data.copy(\n dst.data,\n ((deltaY + y) * dst.width + deltaX) << 2,\n ((srcY + y) * src.width + srcX) << 2,\n ((srcY + y) * src.width + srcX + width) << 2\n );\n }\n};\n\nPNG.prototype.bitblt = function (\n dst,\n srcX,\n srcY,\n width,\n height,\n deltaX,\n deltaY\n) {\n // eslint-disable-line max-params\n\n PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);\n return this;\n};\n\nPNG.adjustGamma = function (src) {\n if (src.gamma) {\n for (let y = 0; y < src.height; y++) {\n for (let x = 0; x < src.width; x++) {\n let idx = (src.width * y + x) << 2;\n\n for (let i = 0; i < 3; i++) {\n let sample = src.data[idx + i] / 255;\n sample = Math.pow(sample, 1 / 2.2 / src.gamma);\n src.data[idx + i] = Math.round(sample * 255);\n }\n }\n }\n src.gamma = 0;\n }\n};\n\nPNG.prototype.adjustGamma = function () {\n PNG.adjustGamma(this);\n};\n\n}).call(this)}).call(this,require('_process'),require(\"buffer\").Buffer)\n},{\"./packer-async\":12,\"./parser-async\":16,\"./png-sync\":19,\"_process\":60,\"buffer\":33,\"stream\":61,\"util\":81}],21:[function(require,module,exports){\n(function (process,Buffer){(function (){\n\"use strict\";\n\nlet assert = require(\"assert\").ok;\nlet zlib = require(\"zlib\");\nlet util = require(\"util\");\n\nlet kMaxLength = require(\"buffer\").kMaxLength;\n\nfunction Inflate(opts) {\n if (!(this instanceof Inflate)) {\n return new Inflate(opts);\n }\n\n if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {\n opts.chunkSize = zlib.Z_MIN_CHUNK;\n }\n\n zlib.Inflate.call(this, opts);\n\n // Node 8 --> 9 compatibility check\n this._offset = this._offset === undefined ? this._outOffset : this._offset;\n this._buffer = this._buffer || this._outBuffer;\n\n if (opts && opts.maxLength != null) {\n this._maxLength = opts.maxLength;\n }\n}\n\nfunction createInflate(opts) {\n return new Inflate(opts);\n}\n\nfunction _close(engine, callback) {\n if (callback) {\n process.nextTick(callback);\n }\n\n // Caller may invoke .close after a zlib error (which will null _handle).\n if (!engine._handle) {\n return;\n }\n\n engine._handle.close();\n engine._handle = null;\n}\n\nInflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) {\n if (typeof asyncCb === \"function\") {\n return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);\n }\n\n let self = this;\n\n let availInBefore = chunk && chunk.length;\n let availOutBefore = this._chunkSize - this._offset;\n let leftToInflate = this._maxLength;\n let inOff = 0;\n\n let buffers = [];\n let nread = 0;\n\n let error;\n this.on(\"error\", function (err) {\n error = err;\n });\n\n function handleChunk(availInAfter, availOutAfter) {\n if (self._hadError) {\n return;\n }\n\n let have = availOutBefore - availOutAfter;\n assert(have >= 0, \"have should not go down\");\n\n if (have > 0) {\n let out = self._buffer.slice(self._offset, self._offset + have);\n self._offset += have;\n\n if (out.length > leftToInflate) {\n out = out.slice(0, leftToInflate);\n }\n\n buffers.push(out);\n nread += out.length;\n leftToInflate -= out.length;\n\n if (leftToInflate === 0) {\n return false;\n }\n }\n\n if (availOutAfter === 0 || self._offset >= self._chunkSize) {\n availOutBefore = self._chunkSize;\n self._offset = 0;\n self._buffer = Buffer.allocUnsafe(self._chunkSize);\n }\n\n if (availOutAfter === 0) {\n inOff += availInBefore - availInAfter;\n availInBefore = availInAfter;\n\n return true;\n }\n\n return false;\n }\n\n assert(this._handle, \"zlib binding closed\");\n let res;\n do {\n res = this._handle.writeSync(\n flushFlag,\n chunk, // in\n inOff, // in_off\n availInBefore, // in_len\n this._buffer, // out\n this._offset, //out_off\n availOutBefore\n ); // out_len\n // Node 8 --> 9 compatibility check\n res = res || this._writeState;\n } while (!this._hadError && handleChunk(res[0], res[1]));\n\n if (this._hadError) {\n throw error;\n }\n\n if (nread >= kMaxLength) {\n _close(this);\n throw new RangeError(\n \"Cannot create final Buffer. It would be larger than 0x\" +\n kMaxLength.toString(16) +\n \" bytes\"\n );\n }\n\n let buf = Buffer.concat(buffers, nread);\n _close(this);\n\n return buf;\n};\n\nutil.inherits(Inflate, zlib.Inflate);\n\nfunction zlibBufferSync(engine, buffer) {\n if (typeof buffer === \"string\") {\n buffer = Buffer.from(buffer);\n }\n if (!(buffer instanceof Buffer)) {\n throw new TypeError(\"Not a string or buffer\");\n }\n\n let flushFlag = engine._finishFlushFlag;\n if (flushFlag == null) {\n flushFlag = zlib.Z_FINISH;\n }\n\n return engine._processChunk(buffer, flushFlag);\n}\n\nfunction inflateSync(buffer, opts) {\n return zlibBufferSync(new Inflate(opts), buffer);\n}\n\nmodule.exports = exports = inflateSync;\nexports.Inflate = Inflate;\nexports.createInflate = createInflate;\nexports.inflateSync = inflateSync;\n\n}).call(this)}).call(this,require('_process'),require(\"buffer\").Buffer)\n},{\"_process\":60,\"assert\":23,\"buffer\":33,\"util\":81,\"zlib\":32}],22:[function(require,module,exports){\n\"use strict\";\n\nlet SyncReader = (module.exports = function (buffer) {\n this._buffer = buffer;\n this._reads = [];\n});\n\nSyncReader.prototype.read = function (length, callback) {\n this._reads.push({\n length: Math.abs(length), // if length < 0 then at most this length\n allowLess: length < 0,\n func: callback,\n });\n};\n\nSyncReader.prototype.process = function () {\n // as long as there is any data and read requests\n while (this._reads.length > 0 && this._buffer.length) {\n let read = this._reads[0];\n\n if (\n this._buffer.length &&\n (this._buffer.length >= read.length || read.allowLess)\n ) {\n // ok there is any data so that we can satisfy this request\n this._reads.shift(); // == read\n\n let buf = this._buffer;\n\n this._buffer = buf.slice(read.length);\n\n read.func.call(this, buf.slice(0, read.length));\n } else {\n break;\n }\n }\n\n if (this._reads.length > 0) {\n throw new Error(\"There are some read requests waitng on finished stream\");\n }\n\n if (this._buffer.length > 0) {\n throw new Error(\"unrecognised content at end of stream\");\n }\n};\n\n},{}],23:[function(require,module,exports){\n(function (global){(function (){\n'use strict';\n\n// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js\n// original notice:\n\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\nfunction compare(a, b) {\n if (a === b) {\n return 0;\n }\n\n var x = a.length;\n var y = b.length;\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i];\n y = b[i];\n break;\n }\n }\n\n if (x < y) {\n return -1;\n }\n if (y < x) {\n return 1;\n }\n return 0;\n}\nfunction isBuffer(b) {\n if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {\n return global.Buffer.isBuffer(b);\n }\n return !!(b != null && b._isBuffer);\n}\n\n// based on node assert, original notice:\n\n// http://wiki.commonjs.org/wiki/Unit_Testing/1.0\n//\n// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!\n//\n// Originally from narwhal.js (http://narwhaljs.org)\n// Copyright (c) 2009 Thomas Robinson <280north.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the 'Software'), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar util = require('util/');\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar pSlice = Array.prototype.slice;\nvar functionsHaveNames = (function () {\n return function foo() {}.name === 'foo';\n}());\nfunction pToString (obj) {\n return Object.prototype.toString.call(obj);\n}\nfunction isView(arrbuf) {\n if (isBuffer(arrbuf)) {\n return false;\n }\n if (typeof global.ArrayBuffer !== 'function') {\n return false;\n }\n if (typeof ArrayBuffer.isView === 'function') {\n return ArrayBuffer.isView(arrbuf);\n }\n if (!arrbuf) {\n return false;\n }\n if (arrbuf instanceof DataView) {\n return true;\n }\n if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {\n return true;\n }\n return false;\n}\n// 1. The assert module provides functions that throw\n// AssertionError's when particular conditions are not met. The\n// assert module must conform to the following interface.\n\nvar assert = module.exports = ok;\n\n// 2. The AssertionError is defined in assert.\n// new assert.AssertionError({ message: message,\n// actual: actual,\n// expected: expected })\n\nvar regex = /\\s*function\\s+([^\\(\\s]*)\\s*/;\n// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js\nfunction getName(func) {\n if (!util.isFunction(func)) {\n return;\n }\n if (functionsHaveNames) {\n return func.name;\n }\n var str = func.toString();\n var match = str.match(regex);\n return match && match[1];\n}\nassert.AssertionError = function AssertionError(options) {\n this.name = 'AssertionError';\n this.actual = options.actual;\n this.expected = options.expected;\n this.operator = options.operator;\n if (options.message) {\n this.message = options.message;\n this.generatedMessage = false;\n } else {\n this.message = getMessage(this);\n this.generatedMessage = true;\n }\n var stackStartFunction = options.stackStartFunction || fail;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, stackStartFunction);\n } else {\n // non v8 browsers so we can have a stacktrace\n var err = new Error();\n if (err.stack) {\n var out = err.stack;\n\n // try to strip useless frames\n var fn_name = getName(stackStartFunction);\n var idx = out.indexOf('\\n' + fn_name);\n if (idx >= 0) {\n // once we have located the function frame\n // we need to strip out everything before it (and its line)\n var next_line = out.indexOf('\\n', idx + 1);\n out = out.substring(next_line + 1);\n }\n\n this.stack = out;\n }\n }\n};\n\n// assert.AssertionError instanceof Error\nutil.inherits(assert.AssertionError, Error);\n\nfunction truncate(s, n) {\n if (typeof s === 'string') {\n return s.length < n ? s : s.slice(0, n);\n } else {\n return s;\n }\n}\nfunction inspect(something) {\n if (functionsHaveNames || !util.isFunction(something)) {\n return util.inspect(something);\n }\n var rawname = getName(something);\n var name = rawname ? ': ' + rawname : '';\n return '[Function' + name + ']';\n}\nfunction getMessage(self) {\n return truncate(inspect(self.actual), 128) + ' ' +\n self.operator + ' ' +\n truncate(inspect(self.expected), 128);\n}\n\n// At present only the three keys mentioned above are used and\n// understood by the spec. Implementations or sub modules can pass\n// other keys to the AssertionError's constructor - they will be\n// ignored.\n\n// 3. All of the following functions must throw an AssertionError\n// when a corresponding condition is not met, with a message that\n// may be undefined if not provided. All assertion methods provide\n// both the actual and expected values to the assertion error for\n// display purposes.\n\nfunction fail(actual, expected, message, operator, stackStartFunction) {\n throw new assert.AssertionError({\n message: message,\n actual: actual,\n expected: expected,\n operator: operator,\n stackStartFunction: stackStartFunction\n });\n}\n\n// EXTENSION! allows for well behaved errors defined elsewhere.\nassert.fail = fail;\n\n// 4. Pure assertion tests whether a value is truthy, as determined\n// by !!guard.\n// assert.ok(guard, message_opt);\n// This statement is equivalent to assert.equal(true, !!guard,\n// message_opt);. To test strictly for the value true, use\n// assert.strictEqual(true, guard, message_opt);.\n\nfunction ok(value, message) {\n if (!value) fail(value, true, message, '==', assert.ok);\n}\nassert.ok = ok;\n\n// 5. The equality assertion tests shallow, coercive equality with\n// ==.\n// assert.equal(actual, expected, message_opt);\n\nassert.equal = function equal(actual, expected, message) {\n if (actual != expected) fail(actual, expected, message, '==', assert.equal);\n};\n\n// 6. The non-equality assertion tests for whether two objects are not equal\n// with != assert.notEqual(actual, expected, message_opt);\n\nassert.notEqual = function notEqual(actual, expected, message) {\n if (actual == expected) {\n fail(actual, expected, message, '!=', assert.notEqual);\n }\n};\n\n// 7. The equivalence assertion tests a deep equality relation.\n// assert.deepEqual(actual, expected, message_opt);\n\nassert.deepEqual = function deepEqual(actual, expected, message) {\n if (!_deepEqual(actual, expected, false)) {\n fail(actual, expected, message, 'deepEqual', assert.deepEqual);\n }\n};\n\nassert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {\n if (!_deepEqual(actual, expected, true)) {\n fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);\n }\n};\n\nfunction _deepEqual(actual, expected, strict, memos) {\n // 7.1. All identical values are equivalent, as determined by ===.\n if (actual === expected) {\n return true;\n } else if (isBuffer(actual) && isBuffer(expected)) {\n return compare(actual, expected) === 0;\n\n // 7.2. If the expected value is a Date object, the actual value is\n // equivalent if it is also a Date object that refers to the same time.\n } else if (util.isDate(actual) && util.isDate(expected)) {\n return actual.getTime() === expected.getTime();\n\n // 7.3 If the expected value is a RegExp object, the actual value is\n // equivalent if it is also a RegExp object with the same source and\n // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).\n } else if (util.isRegExp(actual) && util.isRegExp(expected)) {\n return actual.source === expected.source &&\n actual.global === expected.global &&\n actual.multiline === expected.multiline &&\n actual.lastIndex === expected.lastIndex &&\n actual.ignoreCase === expected.ignoreCase;\n\n // 7.4. Other pairs that do not both pass typeof value == 'object',\n // equivalence is determined by ==.\n } else if ((actual === null || typeof actual !== 'object') &&\n (expected === null || typeof expected !== 'object')) {\n return strict ? actual === expected : actual == expected;\n\n // If both values are instances of typed arrays, wrap their underlying\n // ArrayBuffers in a Buffer each to increase performance\n // This optimization requires the arrays to have the same type as checked by\n // Object.prototype.toString (aka pToString). Never perform binary\n // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their\n // bit patterns are not identical.\n } else if (isView(actual) && isView(expected) &&\n pToString(actual) === pToString(expected) &&\n !(actual instanceof Float32Array ||\n actual instanceof Float64Array)) {\n return compare(new Uint8Array(actual.buffer),\n new Uint8Array(expected.buffer)) === 0;\n\n // 7.5 For all other Object pairs, including Array objects, equivalence is\n // determined by having the same number of owned properties (as verified\n // with Object.prototype.hasOwnProperty.call), the same set of keys\n // (although not necessarily the same order), equivalent values for every\n // corresponding key, and an identical 'prototype' property. Note: this\n // accounts for both named and indexed properties on Arrays.\n } else if (isBuffer(actual) !== isBuffer(expected)) {\n return false;\n } else {\n memos = memos || {actual: [], expected: []};\n\n var actualIndex = memos.actual.indexOf(actual);\n if (actualIndex !== -1) {\n if (actualIndex === memos.expected.indexOf(expected)) {\n return true;\n }\n }\n\n memos.actual.push(actual);\n memos.expected.push(expected);\n\n return objEquiv(actual, expected, strict, memos);\n }\n}\n\nfunction isArguments(object) {\n return Object.prototype.toString.call(object) == '[object Arguments]';\n}\n\nfunction objEquiv(a, b, strict, actualVisitedObjects) {\n if (a === null || a === undefined || b === null || b === undefined)\n return false;\n // if one is a primitive, the other must be same\n if (util.isPrimitive(a) || util.isPrimitive(b))\n return a === b;\n if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))\n return false;\n var aIsArgs = isArguments(a);\n var bIsArgs = isArguments(b);\n if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))\n return false;\n if (aIsArgs) {\n a = pSlice.call(a);\n b = pSlice.call(b);\n return _deepEqual(a, b, strict);\n }\n var ka = objectKeys(a);\n var kb = objectKeys(b);\n var key, i;\n // having the same number of owned properties (keys incorporates\n // hasOwnProperty)\n if (ka.length !== kb.length)\n return false;\n //the same set of keys (although not necessarily the same order),\n ka.sort();\n kb.sort();\n //~~~cheap key test\n for (i = ka.length - 1; i >= 0; i--) {\n if (ka[i] !== kb[i])\n return false;\n }\n //equivalent values for every corresponding key, and\n //~~~possibly expensive deep test\n for (i = ka.length - 1; i >= 0; i--) {\n key = ka[i];\n if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))\n return false;\n }\n return true;\n}\n\n// 8. The non-equivalence assertion tests for any deep inequality.\n// assert.notDeepEqual(actual, expected, message_opt);\n\nassert.notDeepEqual = function notDeepEqual(actual, expected, message) {\n if (_deepEqual(actual, expected, false)) {\n fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);\n }\n};\n\nassert.notDeepStrictEqual = notDeepStrictEqual;\nfunction notDeepStrictEqual(actual, expected, message) {\n if (_deepEqual(actual, expected, true)) {\n fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);\n }\n}\n\n\n// 9. The strict equality assertion tests strict equality, as determined by ===.\n// assert.strictEqual(actual, expected, message_opt);\n\nassert.strictEqual = function strictEqual(actual, expected, message) {\n if (actual !== expected) {\n fail(actual, expected, message, '===', assert.strictEqual);\n }\n};\n\n// 10. The strict non-equality assertion tests for strict inequality, as\n// determined by !==. assert.notStrictEqual(actual, expected, message_opt);\n\nassert.notStrictEqual = function notStrictEqual(actual, expected, message) {\n if (actual === expected) {\n fail(actual, expected, message, '!==', assert.notStrictEqual);\n }\n};\n\nfunction expectedException(actual, expected) {\n if (!actual || !expected) {\n return false;\n }\n\n if (Object.prototype.toString.call(expected) == '[object RegExp]') {\n return expected.test(actual);\n }\n\n try {\n if (actual instanceof expected) {\n return true;\n }\n } catch (e) {\n // Ignore. The instanceof check doesn't work for arrow functions.\n }\n\n if (Error.isPrototypeOf(expected)) {\n return false;\n }\n\n return expected.call({}, actual) === true;\n}\n\nfunction _tryBlock(block) {\n var error;\n try {\n block();\n } catch (e) {\n error = e;\n }\n return error;\n}\n\nfunction _throws(shouldThrow, block, expected, message) {\n var actual;\n\n if (typeof block !== 'function') {\n throw new TypeError('\"block\" argument must be a function');\n }\n\n if (typeof expected === 'string') {\n message = expected;\n expected = null;\n }\n\n actual = _tryBlock(block);\n\n message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +\n (message ? ' ' + message : '.');\n\n if (shouldThrow && !actual) {\n fail(actual, expected, 'Missing expected exception' + message);\n }\n\n var userProvidedMessage = typeof message === 'string';\n var isUnwantedException = !shouldThrow && util.isError(actual);\n var isUnexpectedException = !shouldThrow && actual && !expected;\n\n if ((isUnwantedException &&\n userProvidedMessage &&\n expectedException(actual, expected)) ||\n isUnexpectedException) {\n fail(actual, expected, 'Got unwanted exception' + message);\n }\n\n if ((shouldThrow && actual && expected &&\n !expectedException(actual, expected)) || (!shouldThrow && actual)) {\n throw actual;\n }\n}\n\n// 11. Expected to throw an error:\n// assert.throws(block, Error_opt, message_opt);\n\nassert.throws = function(block, /*optional*/error, /*optional*/message) {\n _throws(true, block, error, message);\n};\n\n// EXTENSION! This is annoying to write outside this module.\nassert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {\n _throws(false, block, error, message);\n};\n\nassert.ifError = function(err) { if (err) throw err; };\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n if (hasOwn.call(obj, key)) keys.push(key);\n }\n return keys;\n};\n\n}).call(this)}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"util/\":26}],24:[function(require,module,exports){\nif (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n\n},{}],25:[function(require,module,exports){\nmodule.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}\n},{}],26:[function(require,module,exports){\n(function (process,global){(function (){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n // Allow for deprecating things in the process of starting up.\n if (isUndefined(global.process)) {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n if (process.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n}).call(this)}).call(this,require('_process'),typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"./support/isBuffer\":25,\"_process\":60,\"inherits\":24}],27:[function(require,module,exports){\n(function (global){(function (){\n'use strict';\n\nvar filter = require('array-filter');\n\nmodule.exports = function availableTypedArrays() {\n\treturn filter([\n\t\t'BigInt64Array',\n\t\t'BigUint64Array',\n\t\t'Float32Array',\n\t\t'Float64Array',\n\t\t'Int16Array',\n\t\t'Int32Array',\n\t\t'Int8Array',\n\t\t'Uint16Array',\n\t\t'Uint32Array',\n\t\t'Uint8Array',\n\t\t'Uint8ClampedArray'\n\t], function (typedArray) {\n\t\treturn typeof global[typedArray] === 'function';\n\t});\n};\n\n}).call(this)}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"array-filter\":28}],28:[function(require,module,exports){\n\n/**\n * Array#filter.\n *\n * @param {Array} arr\n * @param {Function} fn\n * @param {Object=} self\n * @return {Array}\n * @throw TypeError\n */\n\nmodule.exports = function (arr, fn, self) {\n if (arr.filter) return arr.filter(fn, self);\n if (void 0 === arr || null === arr) throw new TypeError;\n if ('function' != typeof fn) throw new TypeError;\n var ret = [];\n for (var i = 0; i < arr.length; i++) {\n if (!hasOwn.call(arr, i)) continue;\n var val = arr[i];\n if (fn.call(self, val, i, arr)) ret.push(val);\n }\n return ret;\n};\n\nvar hasOwn = Object.prototype.hasOwnProperty;\n\n},{}],29:[function(require,module,exports){\n'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(\n uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)\n ))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n\n},{}],30:[function(require,module,exports){\n\n},{}],31:[function(require,module,exports){\n(function (process,Buffer){(function (){\n'use strict';\n/* eslint camelcase: \"off\" */\n\nvar assert = require('assert');\n\nvar Zstream = require('pako/lib/zlib/zstream');\nvar zlib_deflate = require('pako/lib/zlib/deflate.js');\nvar zlib_inflate = require('pako/lib/zlib/inflate.js');\nvar constants = require('pako/lib/zlib/constants');\n\nfor (var key in constants) {\n exports[key] = constants[key];\n}\n\n// zlib modes\nexports.NONE = 0;\nexports.DEFLATE = 1;\nexports.INFLATE = 2;\nexports.GZIP = 3;\nexports.GUNZIP = 4;\nexports.DEFLATERAW = 5;\nexports.INFLATERAW = 6;\nexports.UNZIP = 7;\n\nvar GZIP_HEADER_ID1 = 0x1f;\nvar GZIP_HEADER_ID2 = 0x8b;\n\n/**\n * Emulate Node's zlib C++ layer for use by the JS layer in index.js\n */\nfunction Zlib(mode) {\n if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {\n throw new TypeError('Bad argument');\n }\n\n this.dictionary = null;\n this.err = 0;\n this.flush = 0;\n this.init_done = false;\n this.level = 0;\n this.memLevel = 0;\n this.mode = mode;\n this.strategy = 0;\n this.windowBits = 0;\n this.write_in_progress = false;\n this.pending_close = false;\n this.gzip_id_bytes_read = 0;\n}\n\nZlib.prototype.close = function () {\n if (this.write_in_progress) {\n this.pending_close = true;\n return;\n }\n\n this.pending_close = false;\n\n assert(this.init_done, 'close before init');\n assert(this.mode <= exports.UNZIP);\n\n if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {\n zlib_deflate.deflateEnd(this.strm);\n } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {\n zlib_inflate.inflateEnd(this.strm);\n }\n\n this.mode = exports.NONE;\n\n this.dictionary = null;\n};\n\nZlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {\n return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);\n};\n\nZlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {\n return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);\n};\n\nZlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {\n assert.equal(arguments.length, 8);\n\n assert(this.init_done, 'write before init');\n assert(this.mode !== exports.NONE, 'already finalized');\n assert.equal(false, this.write_in_progress, 'write already in progress');\n assert.equal(false, this.pending_close, 'close is pending');\n\n this.write_in_progress = true;\n\n assert.equal(false, flush === undefined, 'must provide flush value');\n\n this.write_in_progress = true;\n\n if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {\n throw new Error('Invalid flush value');\n }\n\n if (input == null) {\n input = Buffer.alloc(0);\n in_len = 0;\n in_off = 0;\n }\n\n this.strm.avail_in = in_len;\n this.strm.input = input;\n this.strm.next_in = in_off;\n this.strm.avail_out = out_len;\n this.strm.output = out;\n this.strm.next_out = out_off;\n this.flush = flush;\n\n if (!async) {\n // sync version\n this._process();\n\n if (this._checkError()) {\n return this._afterSync();\n }\n return;\n }\n\n // async version\n var self = this;\n process.nextTick(function () {\n self._process();\n self._after();\n });\n\n return this;\n};\n\nZlib.prototype._afterSync = function () {\n var avail_out = this.strm.avail_out;\n var avail_in = this.strm.avail_in;\n\n this.write_in_progress = false;\n\n return [avail_in, avail_out];\n};\n\nZlib.prototype._process = function () {\n var next_expected_header_byte = null;\n\n // If the avail_out is left at 0, then it means that it ran out\n // of room. If there was avail_out left over, then it means\n // that all of the input was consumed.\n switch (this.mode) {\n case exports.DEFLATE:\n case exports.GZIP:\n case exports.DEFLATERAW:\n this.err = zlib_deflate.deflate(this.strm, this.flush);\n break;\n case exports.UNZIP:\n if (this.strm.avail_in > 0) {\n next_expected_header_byte = this.strm.next_in;\n }\n\n switch (this.gzip_id_bytes_read) {\n case 0:\n if (next_expected_header_byte === null) {\n break;\n }\n\n if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {\n this.gzip_id_bytes_read = 1;\n next_expected_header_byte++;\n\n if (this.strm.avail_in === 1) {\n // The only available byte was already read.\n break;\n }\n } else {\n this.mode = exports.INFLATE;\n break;\n }\n\n // fallthrough\n case 1:\n if (next_expected_header_byte === null) {\n break;\n }\n\n if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {\n this.gzip_id_bytes_read = 2;\n this.mode = exports.GUNZIP;\n } else {\n // There is no actual difference between INFLATE and INFLATERAW\n // (after initialization).\n this.mode = exports.INFLATE;\n }\n\n break;\n default:\n throw new Error('invalid number of gzip magic number bytes read');\n }\n\n // fallthrough\n case exports.INFLATE:\n case exports.GUNZIP:\n case exports.INFLATERAW:\n this.err = zlib_inflate.inflate(this.strm, this.flush\n\n // If data was encoded with dictionary\n );if (this.err === exports.Z_NEED_DICT && this.dictionary) {\n // Load it\n this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);\n if (this.err === exports.Z_OK) {\n // And try to decode again\n this.err = zlib_inflate.inflate(this.strm, this.flush);\n } else if (this.err === exports.Z_DATA_ERROR) {\n // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.\n // Make it possible for After() to tell a bad dictionary from bad\n // input.\n this.err = exports.Z_NEED_DICT;\n }\n }\n while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {\n // Bytes remain in input buffer. Perhaps this is another compressed\n // member in the same archive, or just trailing garbage.\n // Trailing zero bytes are okay, though, since they are frequently\n // used for padding.\n\n this.reset();\n this.err = zlib_inflate.inflate(this.strm, this.flush);\n }\n break;\n default:\n throw new Error('Unknown mode ' + this.mode);\n }\n};\n\nZlib.prototype._checkError = function () {\n // Acceptable error states depend on the type of zlib stream.\n switch (this.err) {\n case exports.Z_OK:\n case exports.Z_BUF_ERROR:\n if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {\n this._error('unexpected end of file');\n return false;\n }\n break;\n case exports.Z_STREAM_END:\n // normal statuses, not fatal\n break;\n case exports.Z_NEED_DICT:\n if (this.dictionary == null) {\n this._error('Missing dictionary');\n } else {\n this._error('Bad dictionary');\n }\n return false;\n default:\n // something else.\n this._error('Zlib error');\n return false;\n }\n\n return true;\n};\n\nZlib.prototype._after = function () {\n if (!this._checkError()) {\n return;\n }\n\n var avail_out = this.strm.avail_out;\n var avail_in = this.strm.avail_in;\n\n this.write_in_progress = false;\n\n // call the write() cb\n this.callback(avail_in, avail_out);\n\n if (this.pending_close) {\n this.close();\n }\n};\n\nZlib.prototype._error = function (message) {\n if (this.strm.msg) {\n message = this.strm.msg;\n }\n this.onerror(message, this.err\n\n // no hope of rescue.\n );this.write_in_progress = false;\n if (this.pending_close) {\n this.close();\n }\n};\n\nZlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {\n assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');\n\n assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');\n assert(level >= -1 && level <= 9, 'invalid compression level');\n\n assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');\n\n assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');\n\n this._init(level, windowBits, memLevel, strategy, dictionary);\n this._setDictionary();\n};\n\nZlib.prototype.params = function () {\n throw new Error('deflateParams Not supported');\n};\n\nZlib.prototype.reset = function () {\n this._reset();\n this._setDictionary();\n};\n\nZlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {\n this.level = level;\n this.windowBits = windowBits;\n this.memLevel = memLevel;\n this.strategy = strategy;\n\n this.flush = exports.Z_NO_FLUSH;\n\n this.err = exports.Z_OK;\n\n if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {\n this.windowBits += 16;\n }\n\n if (this.mode === exports.UNZIP) {\n this.windowBits += 32;\n }\n\n if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {\n this.windowBits = -1 * this.windowBits;\n }\n\n this.strm = new Zstream();\n\n switch (this.mode) {\n case exports.DEFLATE:\n case exports.GZIP:\n case exports.DEFLATERAW:\n this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);\n break;\n case exports.INFLATE:\n case exports.GUNZIP:\n case exports.INFLATERAW:\n case exports.UNZIP:\n this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);\n break;\n default:\n throw new Error('Unknown mode ' + this.mode);\n }\n\n if (this.err !== exports.Z_OK) {\n this._error('Init error');\n }\n\n this.dictionary = dictionary;\n\n this.write_in_progress = false;\n this.init_done = true;\n};\n\nZlib.prototype._setDictionary = function () {\n if (this.dictionary == null) {\n return;\n }\n\n this.err = exports.Z_OK;\n\n switch (this.mode) {\n case exports.DEFLATE:\n case exports.DEFLATERAW:\n this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);\n break;\n default:\n break;\n }\n\n if (this.err !== exports.Z_OK) {\n this._error('Failed to set dictionary');\n }\n};\n\nZlib.prototype._reset = function () {\n this.err = exports.Z_OK;\n\n switch (this.mode) {\n case exports.DEFLATE:\n case exports.DEFLATERAW:\n case exports.GZIP:\n this.err = zlib_deflate.deflateReset(this.strm);\n break;\n case exports.INFLATE:\n case exports.INFLATERAW:\n case exports.GUNZIP:\n this.err = zlib_inflate.inflateReset(this.strm);\n break;\n default:\n break;\n }\n\n if (this.err !== exports.Z_OK) {\n this._error('Failed to reset stream');\n }\n};\n\nexports.Zlib = Zlib;\n}).call(this)}).call(this,require('_process'),require(\"buffer\").Buffer)\n},{\"_process\":60,\"assert\":23,\"buffer\":33,\"pako/lib/zlib/constants\":51,\"pako/lib/zlib/deflate.js\":53,\"pako/lib/zlib/inflate.js\":55,\"pako/lib/zlib/zstream\":59}],32:[function(require,module,exports){\n(function (process){(function (){\n'use strict';\n\nvar Buffer = require('buffer').Buffer;\nvar Transform = require('stream').Transform;\nvar binding = require('./binding');\nvar util = require('util');\nvar assert = require('assert').ok;\nvar kMaxLength = require('buffer').kMaxLength;\nvar kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';\n\n// zlib doesn't provide these, so kludge them in following the same\n// const naming scheme zlib uses.\nbinding.Z_MIN_WINDOWBITS = 8;\nbinding.Z_MAX_WINDOWBITS = 15;\nbinding.Z_DEFAULT_WINDOWBITS = 15;\n\n// fewer than 64 bytes per chunk is stupid.\n// technically it could work with as few as 8, but even 64 bytes\n// is absurdly low. Usually a MB or more is best.\nbinding.Z_MIN_CHUNK = 64;\nbinding.Z_MAX_CHUNK = Infinity;\nbinding.Z_DEFAULT_CHUNK = 16 * 1024;\n\nbinding.Z_MIN_MEMLEVEL = 1;\nbinding.Z_MAX_MEMLEVEL = 9;\nbinding.Z_DEFAULT_MEMLEVEL = 8;\n\nbinding.Z_MIN_LEVEL = -1;\nbinding.Z_MAX_LEVEL = 9;\nbinding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;\n\n// expose all the zlib constants\nvar bkeys = Object.keys(binding);\nfor (var bk = 0; bk < bkeys.length; bk++) {\n var bkey = bkeys[bk];\n if (bkey.match(/^Z/)) {\n Object.defineProperty(exports, bkey, {\n enumerable: true, value: binding[bkey], writable: false\n });\n }\n}\n\n// translation table for return codes.\nvar codes = {\n Z_OK: binding.Z_OK,\n Z_STREAM_END: binding.Z_STREAM_END,\n Z_NEED_DICT: binding.Z_NEED_DICT,\n Z_ERRNO: binding.Z_ERRNO,\n Z_STREAM_ERROR: binding.Z_STREAM_ERROR,\n Z_DATA_ERROR: binding.Z_DATA_ERROR,\n Z_MEM_ERROR: binding.Z_MEM_ERROR,\n Z_BUF_ERROR: binding.Z_BUF_ERROR,\n Z_VERSION_ERROR: binding.Z_VERSION_ERROR\n};\n\nvar ckeys = Object.keys(codes);\nfor (var ck = 0; ck < ckeys.length; ck++) {\n var ckey = ckeys[ck];\n codes[codes[ckey]] = ckey;\n}\n\nObject.defineProperty(exports, 'codes', {\n enumerable: true, value: Object.freeze(codes), writable: false\n});\n\nexports.Deflate = Deflate;\nexports.Inflate = Inflate;\nexports.Gzip = Gzip;\nexports.Gunzip = Gunzip;\nexports.DeflateRaw = DeflateRaw;\nexports.InflateRaw = InflateRaw;\nexports.Unzip = Unzip;\n\nexports.createDeflate = function (o) {\n return new Deflate(o);\n};\n\nexports.createInflate = function (o) {\n return new Inflate(o);\n};\n\nexports.createDeflateRaw = function (o) {\n return new DeflateRaw(o);\n};\n\nexports.createInflateRaw = function (o) {\n return new InflateRaw(o);\n};\n\nexports.createGzip = function (o) {\n return new Gzip(o);\n};\n\nexports.createGunzip = function (o) {\n return new Gunzip(o);\n};\n\nexports.createUnzip = function (o) {\n return new Unzip(o);\n};\n\n// Convenience methods.\n// compress/decompress a string or buffer in one step.\nexports.deflate = function (buffer, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n return zlibBuffer(new Deflate(opts), buffer, callback);\n};\n\nexports.deflateSync = function (buffer, opts) {\n return zlibBufferSync(new Deflate(opts), buffer);\n};\n\nexports.gzip = function (buffer, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n return zlibBuffer(new Gzip(opts), buffer, callback);\n};\n\nexports.gzipSync = function (buffer, opts) {\n return zlibBufferSync(new Gzip(opts), buffer);\n};\n\nexports.deflateRaw = function (buffer, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n return zlibBuffer(new DeflateRaw(opts), buffer, callback);\n};\n\nexports.deflateRawSync = function (buffer, opts) {\n return zlibBufferSync(new DeflateRaw(opts), buffer);\n};\n\nexports.unzip = function (buffer, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n return zlibBuffer(new Unzip(opts), buffer, callback);\n};\n\nexports.unzipSync = function (buffer, opts) {\n return zlibBufferSync(new Unzip(opts), buffer);\n};\n\nexports.inflate = function (buffer, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n return zlibBuffer(new Inflate(opts), buffer, callback);\n};\n\nexports.inflateSync = function (buffer, opts) {\n return zlibBufferSync(new Inflate(opts), buffer);\n};\n\nexports.gunzip = function (buffer, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n return zlibBuffer(new Gunzip(opts), buffer, callback);\n};\n\nexports.gunzipSync = function (buffer, opts) {\n return zlibBufferSync(new Gunzip(opts), buffer);\n};\n\nexports.inflateRaw = function (buffer, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n return zlibBuffer(new InflateRaw(opts), buffer, callback);\n};\n\nexports.inflateRawSync = function (buffer, opts) {\n return zlibBufferSync(new InflateRaw(opts), buffer);\n};\n\nfunction zlibBuffer(engine, buffer, callback) {\n var buffers = [];\n var nread = 0;\n\n engine.on('error', onError);\n engine.on('end', onEnd);\n\n engine.end(buffer);\n flow();\n\n function flow() {\n var chunk;\n while (null !== (chunk = engine.read())) {\n buffers.push(chunk);\n nread += chunk.length;\n }\n engine.once('readable', flow);\n }\n\n function onError(err) {\n engine.removeListener('end', onEnd);\n engine.removeListener('readable', flow);\n callback(err);\n }\n\n function onEnd() {\n var buf;\n var err = null;\n\n if (nread >= kMaxLength) {\n err = new RangeError(kRangeErrorMessage);\n } else {\n buf = Buffer.concat(buffers, nread);\n }\n\n buffers = [];\n engine.close();\n callback(err, buf);\n }\n}\n\nfunction zlibBufferSync(engine, buffer) {\n if (typeof buffer === 'string') buffer = Buffer.from(buffer);\n\n if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');\n\n var flushFlag = engine._finishFlushFlag;\n\n return engine._processChunk(buffer, flushFlag);\n}\n\n// generic zlib\n// minimal 2-byte header\nfunction Deflate(opts) {\n if (!(this instanceof Deflate)) return new Deflate(opts);\n Zlib.call(this, opts, binding.DEFLATE);\n}\n\nfunction Inflate(opts) {\n if (!(this instanceof Inflate)) return new Inflate(opts);\n Zlib.call(this, opts, binding.INFLATE);\n}\n\n// gzip - bigger header, same deflate compression\nfunction Gzip(opts) {\n if (!(this instanceof Gzip)) return new Gzip(opts);\n Zlib.call(this, opts, binding.GZIP);\n}\n\nfunction Gunzip(opts) {\n if (!(this instanceof Gunzip)) return new Gunzip(opts);\n Zlib.call(this, opts, binding.GUNZIP);\n}\n\n// raw - no header\nfunction DeflateRaw(opts) {\n if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);\n Zlib.call(this, opts, binding.DEFLATERAW);\n}\n\nfunction InflateRaw(opts) {\n if (!(this instanceof InflateRaw)) return new InflateRaw(opts);\n Zlib.call(this, opts, binding.INFLATERAW);\n}\n\n// auto-detect header.\nfunction Unzip(opts) {\n if (!(this instanceof Unzip)) return new Unzip(opts);\n Zlib.call(this, opts, binding.UNZIP);\n}\n\nfunction isValidFlushFlag(flag) {\n return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;\n}\n\n// the Zlib class they all inherit from\n// This thing manages the queue of requests, and returns\n// true or false if there is anything in the queue when\n// you call the .write() method.\n\nfunction Zlib(opts, mode) {\n var _this = this;\n\n this._opts = opts = opts || {};\n this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;\n\n Transform.call(this, opts);\n\n if (opts.flush && !isValidFlushFlag(opts.flush)) {\n throw new Error('Invalid flush flag: ' + opts.flush);\n }\n if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {\n throw new Error('Invalid flush flag: ' + opts.finishFlush);\n }\n\n this._flushFlag = opts.flush || binding.Z_NO_FLUSH;\n this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;\n\n if (opts.chunkSize) {\n if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {\n throw new Error('Invalid chunk size: ' + opts.chunkSize);\n }\n }\n\n if (opts.windowBits) {\n if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {\n throw new Error('Invalid windowBits: ' + opts.windowBits);\n }\n }\n\n if (opts.level) {\n if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {\n throw new Error('Invalid compression level: ' + opts.level);\n }\n }\n\n if (opts.memLevel) {\n if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {\n throw new Error('Invalid memLevel: ' + opts.memLevel);\n }\n }\n\n if (opts.strategy) {\n if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {\n throw new Error('Invalid strategy: ' + opts.strategy);\n }\n }\n\n if (opts.dictionary) {\n if (!Buffer.isBuffer(opts.dictionary)) {\n throw new Error('Invalid dictionary: it should be a Buffer instance');\n }\n }\n\n this._handle = new binding.Zlib(mode);\n\n var self = this;\n this._hadError = false;\n this._handle.onerror = function (message, errno) {\n // there is no way to cleanly recover.\n // continuing only obscures problems.\n _close(self);\n self._hadError = true;\n\n var error = new Error(message);\n error.errno = errno;\n error.code = exports.codes[errno];\n self.emit('error', error);\n };\n\n var level = exports.Z_DEFAULT_COMPRESSION;\n if (typeof opts.level === 'number') level = opts.level;\n\n var strategy = exports.Z_DEFAULT_STRATEGY;\n if (typeof opts.strategy === 'number') strategy = opts.strategy;\n\n this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);\n\n this._buffer = Buffer.allocUnsafe(this._chunkSize);\n this._offset = 0;\n this._level = level;\n this._strategy = strategy;\n\n this.once('end', this.close);\n\n Object.defineProperty(this, '_closed', {\n get: function () {\n return !_this._handle;\n },\n configurable: true,\n enumerable: true\n });\n}\n\nutil.inherits(Zlib, Transform);\n\nZlib.prototype.params = function (level, strategy, callback) {\n if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {\n throw new RangeError('Invalid compression level: ' + level);\n }\n if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {\n throw new TypeError('Invalid strategy: ' + strategy);\n }\n\n if (this._level !== level || this._strategy !== strategy) {\n var self = this;\n this.flush(binding.Z_SYNC_FLUSH, function () {\n assert(self._handle, 'zlib binding closed');\n self._handle.params(level, strategy);\n if (!self._hadError) {\n self._level = level;\n self._strategy = strategy;\n if (callback) callback();\n }\n });\n } else {\n process.nextTick(callback);\n }\n};\n\nZlib.prototype.reset = function () {\n assert(this._handle, 'zlib binding closed');\n return this._handle.reset();\n};\n\n// This is the _flush function called by the transform class,\n// internally, when the last chunk has been written.\nZlib.prototype._flush = function (callback) {\n this._transform(Buffer.alloc(0), '', callback);\n};\n\nZlib.prototype.flush = function (kind, callback) {\n var _this2 = this;\n\n var ws = this._writableState;\n\n if (typeof kind === 'function' || kind === undefined && !callback) {\n callback = kind;\n kind = binding.Z_FULL_FLUSH;\n }\n\n if (ws.ended) {\n if (callback) process.nextTick(callback);\n } else if (ws.ending) {\n if (callback) this.once('end', callback);\n } else if (ws.needDrain) {\n if (callback) {\n this.once('drain', function () {\n return _this2.flush(kind, callback);\n });\n }\n } else {\n this._flushFlag = kind;\n this.write(Buffer.alloc(0), '', callback);\n }\n};\n\nZlib.prototype.close = function (callback) {\n _close(this, callback);\n process.nextTick(emitCloseNT, this);\n};\n\nfunction _close(engine, callback) {\n if (callback) process.nextTick(callback);\n\n // Caller may invoke .close after a zlib error (which will null _handle).\n if (!engine._handle) return;\n\n engine._handle.close();\n engine._handle = null;\n}\n\nfunction emitCloseNT(self) {\n self.emit('close');\n}\n\nZlib.prototype._transform = function (chunk, encoding, cb) {\n var flushFlag;\n var ws = this._writableState;\n var ending = ws.ending || ws.ended;\n var last = ending && (!chunk || ws.length === chunk.length);\n\n if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));\n\n if (!this._handle) return cb(new Error('zlib binding closed'));\n\n // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag\n // (or whatever flag was provided using opts.finishFlush).\n // If it's explicitly flushing at some other time, then we use\n // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression\n // goodness.\n if (last) flushFlag = this._finishFlushFlag;else {\n flushFlag = this._flushFlag;\n // once we've flushed the last of the queue, stop flushing and\n // go back to the normal behavior.\n if (chunk.length >= ws.length) {\n this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;\n }\n }\n\n this._processChunk(chunk, flushFlag, cb);\n};\n\nZlib.prototype._processChunk = function (chunk, flushFlag, cb) {\n var availInBefore = chunk && chunk.length;\n var availOutBefore = this._chunkSize - this._offset;\n var inOff = 0;\n\n var self = this;\n\n var async = typeof cb === 'function';\n\n if (!async) {\n var buffers = [];\n var nread = 0;\n\n var error;\n this.on('error', function (er) {\n error = er;\n });\n\n assert(this._handle, 'zlib binding closed');\n do {\n var res = this._handle.writeSync(flushFlag, chunk, // in\n inOff, // in_off\n availInBefore, // in_len\n this._buffer, // out\n this._offset, //out_off\n availOutBefore); // out_len\n } while (!this._hadError && callback(res[0], res[1]));\n\n if (this._hadError) {\n throw error;\n }\n\n if (nread >= kMaxLength) {\n _close(this);\n throw new RangeError(kRangeErrorMessage);\n }\n\n var buf = Buffer.concat(buffers, nread);\n _close(this);\n\n return buf;\n }\n\n assert(this._handle, 'zlib binding closed');\n var req = this._handle.write(flushFlag, chunk, // in\n inOff, // in_off\n availInBefore, // in_len\n this._buffer, // out\n this._offset, //out_off\n availOutBefore); // out_len\n\n req.buffer = chunk;\n req.callback = callback;\n\n function callback(availInAfter, availOutAfter) {\n // When the callback is used in an async write, the callback's\n // context is the `req` object that was created. The req object\n // is === this._handle, and that's why it's important to null\n // out the values after they are done being used. `this._handle`\n // can stay in memory longer than the callback and buffer are needed.\n if (this) {\n this.buffer = null;\n this.callback = null;\n }\n\n if (self._hadError) return;\n\n var have = availOutBefore - availOutAfter;\n assert(have >= 0, 'have should not go down');\n\n if (have > 0) {\n var out = self._buffer.slice(self._offset, self._offset + have);\n self._offset += have;\n // serve some output to the consumer.\n if (async) {\n self.push(out);\n } else {\n buffers.push(out);\n nread += out.length;\n }\n }\n\n // exhausted the output buffer, or used all the input create a new one.\n if (availOutAfter === 0 || self._offset >= self._chunkSize) {\n availOutBefore = self._chunkSize;\n self._offset = 0;\n self._buffer = Buffer.allocUnsafe(self._chunkSize);\n }\n\n if (availOutAfter === 0) {\n // Not actually done. Need to reprocess.\n // Also, update the availInBefore to the availInAfter value,\n // so that if we have to hit it a third (fourth, etc.) time,\n // it'll have the correct byte counts.\n inOff += availInBefore - availInAfter;\n availInBefore = availInAfter;\n\n if (!async) return true;\n\n var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);\n newReq.callback = callback; // this same function\n newReq.buffer = chunk;\n return;\n }\n\n if (!async) return false;\n\n // finished with the chunk.\n cb();\n }\n};\n\nutil.inherits(Deflate, Zlib);\nutil.inherits(Inflate, Zlib);\nutil.inherits(Gzip, Zlib);\nutil.inherits(Gunzip, Zlib);\nutil.inherits(DeflateRaw, Zlib);\nutil.inherits(InflateRaw, Zlib);\nutil.inherits(Unzip, Zlib);\n}).call(this)}).call(this,require('_process'))\n},{\"./binding\":31,\"_process\":60,\"assert\":23,\"buffer\":33,\"stream\":61,\"util\":81}],33:[function(require,module,exports){\n(function (Buffer){(function (){\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\n// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\nif (typeof Symbol !== 'undefined' && Symbol.species != null &&\n Buffer[Symbol.species] === Buffer) {\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true,\n enumerable: false,\n writable: false\n })\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayLike(value)\n }\n\n if (value == null) {\n throw TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nBuffer.prototype.__proto__ = Uint8Array.prototype\nBuffer.__proto__ = Uint8Array\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n buf = Buffer.from(buf)\n }\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n newBuf.__proto__ = Buffer.prototype\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (var i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n},{\"base64-js\":29,\"buffer\":33,\"ieee754\":44}],34:[function(require,module,exports){\n'use strict';\n\n/* globals\n\tAtomics,\n\tSharedArrayBuffer,\n*/\n\nvar undefined;\n\nvar $TypeError = TypeError;\n\nvar $gOPD = Object.getOwnPropertyDescriptor;\nif ($gOPD) {\n\ttry {\n\t\t$gOPD({}, '');\n\t} catch (e) {\n\t\t$gOPD = null; // this is IE 8, which has a broken gOPD\n\t}\n}\n\nvar throwTypeError = function () { throw new $TypeError(); };\nvar ThrowTypeError = $gOPD\n\t? (function () {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties\n\t\t\targuments.callee; // IE 8 does not throw here\n\t\t\treturn throwTypeError;\n\t\t} catch (calleeThrows) {\n\t\t\ttry {\n\t\t\t\t// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')\n\t\t\t\treturn $gOPD(arguments, 'callee').get;\n\t\t\t} catch (gOPDthrows) {\n\t\t\t\treturn throwTypeError;\n\t\t\t}\n\t\t}\n\t}())\n\t: throwTypeError;\n\nvar hasSymbols = require('has-symbols')();\n\nvar getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto\n\nvar generator; // = function * () {};\nvar generatorFunction = generator ? getProto(generator) : undefined;\nvar asyncFn; // async function() {};\nvar asyncFunction = asyncFn ? asyncFn.constructor : undefined;\nvar asyncGen; // async function * () {};\nvar asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined;\nvar asyncGenIterator = asyncGen ? asyncGen() : undefined;\n\nvar TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);\n\nvar INTRINSICS = {\n\t'%Array%': Array,\n\t'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,\n\t'%ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype,\n\t'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,\n\t'%ArrayPrototype%': Array.prototype,\n\t'%ArrayProto_entries%': Array.prototype.entries,\n\t'%ArrayProto_forEach%': Array.prototype.forEach,\n\t'%ArrayProto_keys%': Array.prototype.keys,\n\t'%ArrayProto_values%': Array.prototype.values,\n\t'%AsyncFromSyncIteratorPrototype%': undefined,\n\t'%AsyncFunction%': asyncFunction,\n\t'%AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined,\n\t'%AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined,\n\t'%AsyncGeneratorFunction%': asyncGenFunction,\n\t'%AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined,\n\t'%AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined,\n\t'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,\n\t'%Boolean%': Boolean,\n\t'%BooleanPrototype%': Boolean.prototype,\n\t'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,\n\t'%DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype,\n\t'%Date%': Date,\n\t'%DatePrototype%': Date.prototype,\n\t'%decodeURI%': decodeURI,\n\t'%decodeURIComponent%': decodeURIComponent,\n\t'%encodeURI%': encodeURI,\n\t'%encodeURIComponent%': encodeURIComponent,\n\t'%Error%': Error,\n\t'%ErrorPrototype%': Error.prototype,\n\t'%eval%': eval, // eslint-disable-line no-eval\n\t'%EvalError%': EvalError,\n\t'%EvalErrorPrototype%': EvalError.prototype,\n\t'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,\n\t'%Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype,\n\t'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,\n\t'%Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype,\n\t'%Function%': Function,\n\t'%FunctionPrototype%': Function.prototype,\n\t'%Generator%': generator ? getProto(generator()) : undefined,\n\t'%GeneratorFunction%': generatorFunction,\n\t'%GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined,\n\t'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,\n\t'%Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype,\n\t'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,\n\t'%Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype,\n\t'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,\n\t'%Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype,\n\t'%isFinite%': isFinite,\n\t'%isNaN%': isNaN,\n\t'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,\n\t'%JSON%': typeof JSON === 'object' ? JSON : undefined,\n\t'%JSONParse%': typeof JSON === 'object' ? JSON.parse : undefined,\n\t'%Map%': typeof Map === 'undefined' ? undefined : Map,\n\t'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),\n\t'%MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype,\n\t'%Math%': Math,\n\t'%Number%': Number,\n\t'%NumberPrototype%': Number.prototype,\n\t'%Object%': Object,\n\t'%ObjectPrototype%': Object.prototype,\n\t'%ObjProto_toString%': Object.prototype.toString,\n\t'%ObjProto_valueOf%': Object.prototype.valueOf,\n\t'%parseFloat%': parseFloat,\n\t'%parseInt%': parseInt,\n\t'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,\n\t'%PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype,\n\t'%PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then,\n\t'%Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all,\n\t'%Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject,\n\t'%Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve,\n\t'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,\n\t'%RangeError%': RangeError,\n\t'%RangeErrorPrototype%': RangeError.prototype,\n\t'%ReferenceError%': ReferenceError,\n\t'%ReferenceErrorPrototype%': ReferenceError.prototype,\n\t'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,\n\t'%RegExp%': RegExp,\n\t'%RegExpPrototype%': RegExp.prototype,\n\t'%Set%': typeof Set === 'undefined' ? undefined : Set,\n\t'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),\n\t'%SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype,\n\t'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,\n\t'%SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype,\n\t'%String%': String,\n\t'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,\n\t'%StringPrototype%': String.prototype,\n\t'%Symbol%': hasSymbols ? Symbol : undefined,\n\t'%SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined,\n\t'%SyntaxError%': SyntaxError,\n\t'%SyntaxErrorPrototype%': SyntaxError.prototype,\n\t'%ThrowTypeError%': ThrowTypeError,\n\t'%TypedArray%': TypedArray,\n\t'%TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined,\n\t'%TypeError%': $TypeError,\n\t'%TypeErrorPrototype%': $TypeError.prototype,\n\t'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,\n\t'%Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype,\n\t'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,\n\t'%Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype,\n\t'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,\n\t'%Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype,\n\t'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,\n\t'%Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype,\n\t'%URIError%': URIError,\n\t'%URIErrorPrototype%': URIError.prototype,\n\t'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,\n\t'%WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype,\n\t'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet,\n\t'%WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype\n};\n\nvar bind = require('function-bind');\nvar $replace = bind.call(Function.call, String.prototype.replace);\n\n/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */\nvar rePropName = /[^%.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|%$))/g;\nvar reEscapeChar = /\\\\(\\\\)?/g; /** Used to match backslashes in property paths. */\nvar stringToPath = function stringToPath(string) {\n\tvar result = [];\n\t$replace(string, rePropName, function (match, number, quote, subString) {\n\t\tresult[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match);\n\t});\n\treturn result;\n};\n/* end adaptation */\n\nvar getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {\n\tif (!(name in INTRINSICS)) {\n\t\tthrow new SyntaxError('intrinsic ' + name + ' does not exist!');\n\t}\n\n\t// istanbul ignore if // hopefully this is impossible to test :-)\n\tif (typeof INTRINSICS[name] === 'undefined' && !allowMissing) {\n\t\tthrow new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');\n\t}\n\n\treturn INTRINSICS[name];\n};\n\nmodule.exports = function GetIntrinsic(name, allowMissing) {\n\tif (typeof name !== 'string' || name.length === 0) {\n\t\tthrow new TypeError('intrinsic name must be a non-empty string');\n\t}\n\tif (arguments.length > 1 && typeof allowMissing !== 'boolean') {\n\t\tthrow new TypeError('\"allowMissing\" argument must be a boolean');\n\t}\n\n\tvar parts = stringToPath(name);\n\n\tvar value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing);\n\tfor (var i = 1; i < parts.length; i += 1) {\n\t\tif (value != null) {\n\t\t\tif ($gOPD && (i + 1) >= parts.length) {\n\t\t\t\tvar desc = $gOPD(value, parts[i]);\n\t\t\t\tif (!allowMissing && !(parts[i] in value)) {\n\t\t\t\t\tthrow new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');\n\t\t\t\t}\n\t\t\t\tvalue = desc ? (desc.get || desc.value) : value[parts[i]];\n\t\t\t} else {\n\t\t\t\tvalue = value[parts[i]];\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n};\n\n},{\"function-bind\":41,\"has-symbols\":42}],35:[function(require,module,exports){\n'use strict';\n\nvar bind = require('function-bind');\n\nvar GetIntrinsic = require('../GetIntrinsic');\n\nvar $Function = GetIntrinsic('%Function%');\nvar $apply = $Function.apply;\nvar $call = $Function.call;\n\nmodule.exports = function callBind() {\n\treturn bind.apply($call, arguments);\n};\n\nmodule.exports.apply = function applyBind() {\n\treturn bind.apply($apply, arguments);\n};\n\n},{\"../GetIntrinsic\":34,\"function-bind\":41}],36:[function(require,module,exports){\n'use strict';\n\nvar GetIntrinsic = require('../GetIntrinsic');\n\nvar callBind = require('./callBind');\n\nvar $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));\n\nmodule.exports = function callBoundIntrinsic(name, allowMissing) {\n\tvar intrinsic = GetIntrinsic(name, !!allowMissing);\n\tif (typeof intrinsic === 'function' && $indexOf(name, '.prototype.')) {\n\t\treturn callBind(intrinsic);\n\t}\n\treturn intrinsic;\n};\n\n},{\"../GetIntrinsic\":34,\"./callBind\":35}],37:[function(require,module,exports){\n'use strict';\n\nvar GetIntrinsic = require('../GetIntrinsic');\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%');\nif ($gOPD) {\n\ttry {\n\t\t$gOPD([], 'length');\n\t} catch (e) {\n\t\t// IE 8 has a broken gOPD\n\t\t$gOPD = null;\n\t}\n}\n\nmodule.exports = $gOPD;\n\n},{\"../GetIntrinsic\":34}],38:[function(require,module,exports){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function eventListener() {\n if (errorListener !== undefined) {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n var errorListener;\n\n // Adding an error listener is not optional because\n // if an error is thrown on an event emitter we cannot\n // guarantee that the actual event we are waiting will\n // be fired. The result could be a silent way to create\n // memory or file descriptor leaks, which is something\n // we should avoid.\n if (name !== 'error') {\n errorListener = function errorListener(err) {\n emitter.removeListener(name, eventListener);\n reject(err);\n };\n\n emitter.once('error', errorListener);\n }\n\n emitter.once(name, eventListener);\n });\n}\n\n},{}],39:[function(require,module,exports){\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toString = Object.prototype.toString;\n\nmodule.exports = function forEach (obj, fn, ctx) {\n if (toString.call(fn) !== '[object Function]') {\n throw new TypeError('iterator must be a function');\n }\n var l = obj.length;\n if (l === +l) {\n for (var i = 0; i < l; i++) {\n fn.call(ctx, obj[i], i, obj);\n }\n } else {\n for (var k in obj) {\n if (hasOwn.call(obj, k)) {\n fn.call(ctx, obj[k], k, obj);\n }\n }\n }\n};\n\n\n},{}],40:[function(require,module,exports){\n'use strict';\n\n/* eslint no-invalid-this: 1 */\n\nvar ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';\nvar slice = Array.prototype.slice;\nvar toStr = Object.prototype.toString;\nvar funcType = '[object Function]';\n\nmodule.exports = function bind(that) {\n var target = this;\n if (typeof target !== 'function' || toStr.call(target) !== funcType) {\n throw new TypeError(ERROR_MESSAGE + target);\n }\n var args = slice.call(arguments, 1);\n\n var bound;\n var binder = function () {\n if (this instanceof bound) {\n var result = target.apply(\n this,\n args.concat(slice.call(arguments))\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n } else {\n return target.apply(\n that,\n args.concat(slice.call(arguments))\n );\n }\n };\n\n var boundLength = Math.max(0, target.length - args.length);\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs.push('$' + i);\n }\n\n bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);\n\n if (target.prototype) {\n var Empty = function Empty() {};\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n Empty.prototype = null;\n }\n\n return bound;\n};\n\n},{}],41:[function(require,module,exports){\n'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = Function.prototype.bind || implementation;\n\n},{\"./implementation\":40}],42:[function(require,module,exports){\n(function (global){(function (){\n'use strict';\n\nvar origSymbol = global.Symbol;\nvar hasSymbolSham = require('./shams');\n\nmodule.exports = function hasNativeSymbols() {\n\tif (typeof origSymbol !== 'function') { return false; }\n\tif (typeof Symbol !== 'function') { return false; }\n\tif (typeof origSymbol('foo') !== 'symbol') { return false; }\n\tif (typeof Symbol('bar') !== 'symbol') { return false; }\n\n\treturn hasSymbolSham();\n};\n\n}).call(this)}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"./shams\":43}],43:[function(require,module,exports){\n'use strict';\n\n/* eslint complexity: [2, 18], max-statements: [2, 33] */\nmodule.exports = function hasSymbols() {\n\tif (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }\n\tif (typeof Symbol.iterator === 'symbol') { return true; }\n\n\tvar obj = {};\n\tvar sym = Symbol('test');\n\tvar symObj = Object(sym);\n\tif (typeof sym === 'string') { return false; }\n\n\tif (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }\n\tif (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }\n\n\t// temp disabled per https://github.com/ljharb/object.assign/issues/17\n\t// if (sym instanceof Symbol) { return false; }\n\t// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4\n\t// if (!(symObj instanceof Symbol)) { return false; }\n\n\t// if (typeof Symbol.prototype.toString !== 'function') { return false; }\n\t// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }\n\n\tvar symVal = 42;\n\tobj[sym] = symVal;\n\tfor (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax\n\tif (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }\n\n\tif (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }\n\n\tvar syms = Object.getOwnPropertySymbols(obj);\n\tif (syms.length !== 1 || syms[0] !== sym) { return false; }\n\n\tif (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }\n\n\tif (typeof Object.getOwnPropertyDescriptor === 'function') {\n\t\tvar descriptor = Object.getOwnPropertyDescriptor(obj, sym);\n\t\tif (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }\n\t}\n\n\treturn true;\n};\n\n},{}],44:[function(require,module,exports){\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n\n},{}],45:[function(require,module,exports){\nif (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n\n},{}],46:[function(require,module,exports){\n'use strict';\n\nvar hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';\nvar toStr = Object.prototype.toString;\n\nvar isStandardArguments = function isArguments(value) {\n\tif (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {\n\t\treturn false;\n\t}\n\treturn toStr.call(value) === '[object Arguments]';\n};\n\nvar isLegacyArguments = function isArguments(value) {\n\tif (isStandardArguments(value)) {\n\t\treturn true;\n\t}\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.length === 'number' &&\n\t\tvalue.length >= 0 &&\n\t\ttoStr.call(value) !== '[object Array]' &&\n\t\ttoStr.call(value.callee) === '[object Function]';\n};\n\nvar supportsStandardArguments = (function () {\n\treturn isStandardArguments(arguments);\n}());\n\nisStandardArguments.isLegacyArguments = isLegacyArguments; // for tests\n\nmodule.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;\n\n},{}],47:[function(require,module,exports){\n'use strict';\n\nvar toStr = Object.prototype.toString;\nvar fnToStr = Function.prototype.toString;\nvar isFnRegex = /^\\s*(?:function)?\\*/;\nvar hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';\nvar getProto = Object.getPrototypeOf;\nvar getGeneratorFunc = function () { // eslint-disable-line consistent-return\n\tif (!hasToStringTag) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn Function('return function*() {}')();\n\t} catch (e) {\n\t}\n};\nvar generatorFunc = getGeneratorFunc();\nvar GeneratorFunction = generatorFunc ? getProto(generatorFunc) : {};\n\nmodule.exports = function isGeneratorFunction(fn) {\n\tif (typeof fn !== 'function') {\n\t\treturn false;\n\t}\n\tif (isFnRegex.test(fnToStr.call(fn))) {\n\t\treturn true;\n\t}\n\tif (!hasToStringTag) {\n\t\tvar str = toStr.call(fn);\n\t\treturn str === '[object GeneratorFunction]';\n\t}\n\treturn getProto(fn) === GeneratorFunction;\n};\n\n},{}],48:[function(require,module,exports){\n(function (global){(function (){\n'use strict';\n\nvar forEach = require('foreach');\nvar availableTypedArrays = require('available-typed-arrays');\nvar callBound = require('es-abstract/helpers/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\nvar hasSymbols = require('has-symbols')();\nvar hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol';\n\nvar typedArrays = availableTypedArrays();\n\nvar $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {\n\tfor (var i = 0; i < array.length; i += 1) {\n\t\tif (array[i] === value) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n};\nvar $slice = callBound('String.prototype.slice');\nvar toStrTags = {};\nvar gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');\nvar getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');\nif (hasToStringTag && gOPD && getPrototypeOf) {\n\tforEach(typedArrays, function (typedArray) {\n\t\tvar arr = new global[typedArray]();\n\t\tif (!(Symbol.toStringTag in arr)) {\n\t\t\tthrow new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.');\n\t\t}\n\t\tvar proto = getPrototypeOf(arr);\n\t\tvar descriptor = gOPD(proto, Symbol.toStringTag);\n\t\tif (!descriptor) {\n\t\t\tvar superProto = getPrototypeOf(proto);\n\t\t\tdescriptor = gOPD(superProto, Symbol.toStringTag);\n\t\t}\n\t\ttoStrTags[typedArray] = descriptor.get;\n\t});\n}\n\nvar tryTypedArrays = function tryAllTypedArrays(value) {\n\tvar anyTrue = false;\n\tforEach(toStrTags, function (getter, typedArray) {\n\t\tif (!anyTrue) {\n\t\t\ttry {\n\t\t\t\tanyTrue = getter.call(value) === typedArray;\n\t\t\t} catch (e) { /**/ }\n\t\t}\n\t});\n\treturn anyTrue;\n};\n\nmodule.exports = function isTypedArray(value) {\n\tif (!value || typeof value !== 'object') { return false; }\n\tif (!hasToStringTag) {\n\t\tvar tag = $slice($toString(value), 8, -1);\n\t\treturn $indexOf(typedArrays, tag) > -1;\n\t}\n\tif (!gOPD) { return false; }\n\treturn tryTypedArrays(value);\n};\n\n}).call(this)}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"available-typed-arrays\":27,\"es-abstract/helpers/callBound\":36,\"es-abstract/helpers/getOwnPropertyDescriptor\":37,\"foreach\":39,\"has-symbols\":42}],49:[function(require,module,exports){\n'use strict';\n\n\nvar TYPED_OK = (typeof Uint8Array !== 'undefined') &&\n (typeof Uint16Array !== 'undefined') &&\n (typeof Int32Array !== 'undefined');\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexports.assign = function (obj /*from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// reduce buffer size, avoiding mem copy\nexports.shrinkBuf = function (buf, size) {\n if (buf.length === size) { return buf; }\n if (buf.subarray) { return buf.subarray(0, size); }\n buf.length = size;\n return buf;\n};\n\n\nvar fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n var i, l, len, pos, chunk, result;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nvar fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\nexports.setTyped = function (on) {\n if (on) {\n exports.Buf8 = Uint8Array;\n exports.Buf16 = Uint16Array;\n exports.Buf32 = Int32Array;\n exports.assign(exports, fnTyped);\n } else {\n exports.Buf8 = Array;\n exports.Buf16 = Array;\n exports.Buf32 = Array;\n exports.assign(exports, fnUntyped);\n }\n};\n\nexports.setTyped(TYPED_OK);\n\n},{}],50:[function(require,module,exports){\n'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n\n},{}],51:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n},{}],52:[function(require,module,exports){\n'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n\n},{}],53:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar trees = require('./trees');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar msg = require('./messages');\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nvar Z_NO_FLUSH = 0;\nvar Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\nvar Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\n//var Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\n//var Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\n//var Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n\n/* compression levels */\n//var Z_NO_COMPRESSION = 0;\n//var Z_BEST_SPEED = 1;\n//var Z_BEST_COMPRESSION = 9;\nvar Z_DEFAULT_COMPRESSION = -1;\n\n\nvar Z_FILTERED = 1;\nvar Z_HUFFMAN_ONLY = 2;\nvar Z_RLE = 3;\nvar Z_FIXED = 4;\nvar Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\n//var Z_BINARY = 0;\n//var Z_TEXT = 1;\n//var Z_ASCII = 1; // = Z_TEXT\nvar Z_UNKNOWN = 2;\n\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n/*============================================================================*/\n\n\nvar MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_MEM_LEVEL = 8;\n\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nvar D_CODES = 30;\n/* number of distance codes */\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\nvar MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nvar PRESET_DICT = 0x20;\n\nvar INIT_STATE = 42;\nvar EXTRA_STATE = 69;\nvar NAME_STATE = 73;\nvar COMMENT_STATE = 91;\nvar HCRC_STATE = 103;\nvar BUSY_STATE = 113;\nvar FINISH_STATE = 666;\n\nvar BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nvar BS_BLOCK_DONE = 2; /* block flush performed */\nvar BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nvar BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nvar OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n var s = strm.state;\n\n //_tr_flush_bits(s);\n var len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n// put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n var len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n var _w_size = s.w_size;\n var p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// var curr = s.strstart + s.lookahead;\n// var init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n var max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n var max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n var hash_head; /* head of the hash chain */\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n var hash_head; /* head of hash chain */\n var bflush; /* set if current block must be flushed */\n\n var max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n var bflush; /* set if current block must be flushed */\n var prev; /* byte at distance one to match */\n var scan, strend; /* scan goes up to strend for length of run */\n\n var _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nvar configuration_table;\n\nconfiguration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nfunction deflateResetKeep(strm) {\n var s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n var ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n var wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n var s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n var old_flush, s;\n var beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n var level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n var status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var s;\n var str, n;\n var wrap;\n var avail;\n var next;\n var input;\n var tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\n\nexports.deflateInit = deflateInit;\nexports.deflateInit2 = deflateInit2;\nexports.deflateReset = deflateReset;\nexports.deflateResetKeep = deflateResetKeep;\nexports.deflateSetHeader = deflateSetHeader;\nexports.deflate = deflate;\nexports.deflateEnd = deflateEnd;\nexports.deflateSetDictionary = deflateSetDictionary;\nexports.deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n\n},{\"../utils/common\":49,\"./adler32\":50,\"./crc32\":52,\"./messages\":57,\"./trees\":58}],54:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n},{}],55:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n},{\"../utils/common\":49,\"./adler32\":50,\"./crc32\":52,\"./inffast\":54,\"./inftrees\":56}],56:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n},{\"../utils/common\":49}],57:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n},{}],58:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//var Z_FILTERED = 1;\n//var Z_HUFFMAN_ONLY = 2;\n//var Z_RLE = 3;\nvar Z_FIXED = 4;\n//var Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nvar Z_BINARY = 0;\nvar Z_TEXT = 1;\n//var Z_ASCII = 1; // = Z_TEXT\nvar Z_UNKNOWN = 2;\n\n/*============================================================================*/\n\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nvar STORED_BLOCK = 0;\nvar STATIC_TREES = 1;\nvar DYN_TREES = 2;\n/* The three kinds of block type */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nvar D_CODES = 30;\n/* number of distance codes */\n\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nvar MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nvar END_BLOCK = 256;\n/* end of block literal code */\n\nvar REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nvar REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nvar REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nvar extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nvar extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nvar extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nvar bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nvar DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nvar static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nvar static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nvar _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nvar _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nvar base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nvar base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nvar static_l_desc;\nvar static_d_desc;\nvar static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n var res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var max_code = desc.max_code;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var extra = desc.stat_desc.extra_bits;\n var base = desc.stat_desc.extra_base;\n var max_length = desc.stat_desc.max_length;\n var h; /* heap index */\n var n, m; /* iterate over the tree elements */\n var bits; /* bit length */\n var xbits; /* extra bits */\n var f; /* frequency */\n var overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n var code = 0; /* running code value */\n var bits; /* bit index */\n var n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n var n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s)\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n var _n2 = n * 2;\n var _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n var v = s.heap[k];\n var j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n var dist; /* distance of matched string */\n var lc; /* match length or unmatched char (if dist == 0) */\n var lx = 0; /* running index in l_buf */\n var code; /* the code to send */\n var extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var elems = desc.stat_desc.elems;\n var n, m; /* iterate over heap elements */\n var max_code = -1; /* largest code with non zero frequency */\n var node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n var max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n var rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n var black_mask = 0xf3ffc07f;\n var n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nvar static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s)\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n var opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n var max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexports._tr_init = _tr_init;\nexports._tr_stored_block = _tr_stored_block;\nexports._tr_flush_block = _tr_flush_block;\nexports._tr_tally = _tr_tally;\nexports._tr_align = _tr_align;\n\n},{\"../utils/common\":49}],59:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n\n},{}],60:[function(require,module,exports){\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n},{}],61:[function(require,module,exports){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Stream;\n\nvar EE = require('events').EventEmitter;\nvar inherits = require('inherits');\n\ninherits(Stream, EE);\nStream.Readable = require('readable-stream/lib/_stream_readable.js');\nStream.Writable = require('readable-stream/lib/_stream_writable.js');\nStream.Duplex = require('readable-stream/lib/_stream_duplex.js');\nStream.Transform = require('readable-stream/lib/_stream_transform.js');\nStream.PassThrough = require('readable-stream/lib/_stream_passthrough.js');\nStream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js')\nStream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js')\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\n\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\n};\n\n},{\"events\":38,\"inherits\":45,\"readable-stream/lib/_stream_duplex.js\":63,\"readable-stream/lib/_stream_passthrough.js\":64,\"readable-stream/lib/_stream_readable.js\":65,\"readable-stream/lib/_stream_transform.js\":66,\"readable-stream/lib/_stream_writable.js\":67,\"readable-stream/lib/internal/streams/end-of-stream.js\":71,\"readable-stream/lib/internal/streams/pipeline.js\":73}],62:[function(require,module,exports){\n'use strict';\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\nvar codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error;\n }\n\n function getMessage(arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message;\n } else {\n return message(arg1, arg2, arg3);\n }\n }\n\n var NodeError =\n /*#__PURE__*/\n function (_Base) {\n _inheritsLoose(NodeError, _Base);\n\n function NodeError(arg1, arg2, arg3) {\n return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;\n }\n\n return NodeError;\n }(Base);\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n codes[code] = NodeError;\n} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\n\n\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n var len = expected.length;\n expected = expected.map(function (i) {\n return String(i);\n });\n\n if (len > 2) {\n return \"one of \".concat(thing, \" \").concat(expected.slice(0, len - 1).join(', '), \", or \") + expected[len - 1];\n } else if (len === 2) {\n return \"one of \".concat(thing, \" \").concat(expected[0], \" or \").concat(expected[1]);\n } else {\n return \"of \".concat(thing, \" \").concat(expected[0]);\n }\n } else {\n return \"of \".concat(thing, \" \").concat(String(expected));\n }\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\n\n\nfunction startsWith(str, search, pos) {\n return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\n\n\nfunction endsWith(str, search, this_len) {\n if (this_len === undefined || this_len > str.length) {\n this_len = str.length;\n }\n\n return str.substring(this_len - search.length, this_len) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\n\n\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"';\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n var determiner;\n\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n var msg;\n\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = \"The \".concat(name, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n } else {\n var type = includes(name, '.') ? 'property' : 'argument';\n msg = \"The \\\"\".concat(name, \"\\\" \").concat(type, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n }\n\n msg += \". Received type \".concat(typeof actual);\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented';\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\nmodule.exports.codes = codes;\n\n},{}],63:[function(require,module,exports){\n(function (process){(function (){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n}).call(this)}).call(this,require('_process'))\n},{\"./_stream_readable\":65,\"./_stream_writable\":67,\"_process\":60,\"inherits\":45}],64:[function(require,module,exports){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};\n},{\"./_stream_transform\":66,\"inherits\":45}],65:[function(require,module,exports){\n(function (process,global){(function (){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}\n}).call(this)}).call(this,require('_process'),typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"../errors\":62,\"./_stream_duplex\":63,\"./internal/streams/async_iterator\":68,\"./internal/streams/buffer_list\":69,\"./internal/streams/destroy\":70,\"./internal/streams/from\":72,\"./internal/streams/state\":74,\"./internal/streams/stream\":75,\"_process\":60,\"buffer\":33,\"events\":38,\"inherits\":45,\"string_decoder/\":76,\"util\":30}],66:[function(require,module,exports){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}\n},{\"../errors\":62,\"./_stream_duplex\":63,\"inherits\":45}],67:[function(require,module,exports){\n(function (process,global){(function (){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};\n}).call(this)}).call(this,require('_process'),typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"../errors\":62,\"./_stream_duplex\":63,\"./internal/streams/destroy\":70,\"./internal/streams/state\":74,\"./internal/streams/stream\":75,\"_process\":60,\"buffer\":33,\"inherits\":45,\"util-deprecate\":78}],68:[function(require,module,exports){\n(function (process){(function (){\n'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;\n}).call(this)}).call(this,require('_process'))\n},{\"./end-of-stream\":71,\"_process\":60}],69:[function(require,module,exports){\n'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();\n},{\"buffer\":33,\"util\":30}],70:[function(require,module,exports){\n(function (process){(function (){\n'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};\n}).call(this)}).call(this,require('_process'))\n},{\"_process\":60}],71:[function(require,module,exports){\n// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;\n},{\"../../../errors\":62}],72:[function(require,module,exports){\nmodule.exports = function () {\n throw new Error('Readable.from is not available in the browser')\n};\n\n},{}],73:[function(require,module,exports){\n// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\n\n var error;\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1;\n var writing = i > 0;\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err;\n if (err) destroys.forEach(call);\n if (reading) return;\n destroys.forEach(call);\n callback(error);\n });\n });\n return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;\n},{\"../../../errors\":62,\"./end-of-stream\":71}],74:[function(require,module,exports){\n'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};\n},{\"../../../errors\":62}],75:[function(require,module,exports){\nmodule.exports = require('events').EventEmitter;\n\n},{\"events\":38}],76:[function(require,module,exports){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}\n},{\"safe-buffer\":77}],77:[function(require,module,exports){\n/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n\n},{\"buffer\":33}],78:[function(require,module,exports){\n(function (global){(function (){\n\n/**\n * Module exports.\n */\n\nmodule.exports = deprecate;\n\n/**\n * Mark that a method should not be used.\n * Returns a modified function which warns once by default.\n *\n * If `localStorage.noDeprecation = true` is set, then it is a no-op.\n *\n * If `localStorage.throwDeprecation = true` is set, then deprecated functions\n * will throw an Error when invoked.\n *\n * If `localStorage.traceDeprecation = true` is set, then deprecated functions\n * will invoke `console.trace()` instead of `console.error()`.\n *\n * @param {Function} fn - the function to deprecate\n * @param {String} msg - the string to print to the console when `fn` is invoked\n * @returns {Function} a new \"deprecated\" version of `fn`\n * @api public\n */\n\nfunction deprecate (fn, msg) {\n if (config('noDeprecation')) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (config('throwDeprecation')) {\n throw new Error(msg);\n } else if (config('traceDeprecation')) {\n console.trace(msg);\n } else {\n console.warn(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n}\n\n/**\n * Checks `localStorage` for boolean values for the given `name`.\n *\n * @param {String} name\n * @returns {Boolean}\n * @api private\n */\n\nfunction config (name) {\n // accessing global.localStorage can trigger a DOMException in sandboxed iframes\n try {\n if (!global.localStorage) return false;\n } catch (_) {\n return false;\n }\n var val = global.localStorage[name];\n if (null == val) return false;\n return String(val).toLowerCase() === 'true';\n}\n\n}).call(this)}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],79:[function(require,module,exports){\narguments[4][25][0].apply(exports,arguments)\n},{\"dup\":25}],80:[function(require,module,exports){\n// Currently in sync with Node.js lib/internal/util/types.js\n// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9\n\n'use strict';\n\nvar isArgumentsObject = require('is-arguments');\nvar isGeneratorFunction = require('is-generator-function');\nvar whichTypedArray = require('which-typed-array');\nvar isTypedArray = require('is-typed-array');\n\nfunction uncurryThis(f) {\n return f.call.bind(f);\n}\n\nvar BigIntSupported = typeof BigInt !== 'undefined';\nvar SymbolSupported = typeof Symbol !== 'undefined';\n\nvar ObjectToString = uncurryThis(Object.prototype.toString);\n\nvar numberValue = uncurryThis(Number.prototype.valueOf);\nvar stringValue = uncurryThis(String.prototype.valueOf);\nvar booleanValue = uncurryThis(Boolean.prototype.valueOf);\n\nif (BigIntSupported) {\n var bigIntValue = uncurryThis(BigInt.prototype.valueOf);\n}\n\nif (SymbolSupported) {\n var symbolValue = uncurryThis(Symbol.prototype.valueOf);\n}\n\nfunction checkBoxedPrimitive(value, prototypeValueOf) {\n if (typeof value !== 'object') {\n return false;\n }\n try {\n prototypeValueOf(value);\n return true;\n } catch(e) {\n return false;\n }\n}\n\nexports.isArgumentsObject = isArgumentsObject;\nexports.isGeneratorFunction = isGeneratorFunction;\nexports.isTypedArray = isTypedArray;\n\n// Taken from here and modified for better browser support\n// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js\nfunction isPromise(input) {\n\treturn (\n\t\t(\n\t\t\ttypeof Promise !== 'undefined' &&\n\t\t\tinput instanceof Promise\n\t\t) ||\n\t\t(\n\t\t\tinput !== null &&\n\t\t\ttypeof input === 'object' &&\n\t\t\ttypeof input.then === 'function' &&\n\t\t\ttypeof input.catch === 'function'\n\t\t)\n\t);\n}\nexports.isPromise = isPromise;\n\nfunction isArrayBufferView(value) {\n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {\n return ArrayBuffer.isView(value);\n }\n\n return (\n isTypedArray(value) ||\n isDataView(value)\n );\n}\nexports.isArrayBufferView = isArrayBufferView;\n\n\nfunction isUint8Array(value) {\n return whichTypedArray(value) === 'Uint8Array';\n}\nexports.isUint8Array = isUint8Array;\n\nfunction isUint8ClampedArray(value) {\n return whichTypedArray(value) === 'Uint8ClampedArray';\n}\nexports.isUint8ClampedArray = isUint8ClampedArray;\n\nfunction isUint16Array(value) {\n return whichTypedArray(value) === 'Uint16Array';\n}\nexports.isUint16Array = isUint16Array;\n\nfunction isUint32Array(value) {\n return whichTypedArray(value) === 'Uint32Array';\n}\nexports.isUint32Array = isUint32Array;\n\nfunction isInt8Array(value) {\n return whichTypedArray(value) === 'Int8Array';\n}\nexports.isInt8Array = isInt8Array;\n\nfunction isInt16Array(value) {\n return whichTypedArray(value) === 'Int16Array';\n}\nexports.isInt16Array = isInt16Array;\n\nfunction isInt32Array(value) {\n return whichTypedArray(value) === 'Int32Array';\n}\nexports.isInt32Array = isInt32Array;\n\nfunction isFloat32Array(value) {\n return whichTypedArray(value) === 'Float32Array';\n}\nexports.isFloat32Array = isFloat32Array;\n\nfunction isFloat64Array(value) {\n return whichTypedArray(value) === 'Float64Array';\n}\nexports.isFloat64Array = isFloat64Array;\n\nfunction isBigInt64Array(value) {\n return whichTypedArray(value) === 'BigInt64Array';\n}\nexports.isBigInt64Array = isBigInt64Array;\n\nfunction isBigUint64Array(value) {\n return whichTypedArray(value) === 'BigUint64Array';\n}\nexports.isBigUint64Array = isBigUint64Array;\n\nfunction isMapToString(value) {\n return ObjectToString(value) === '[object Map]';\n}\nisMapToString.working = (\n typeof Map !== 'undefined' &&\n isMapToString(new Map())\n);\n\nfunction isMap(value) {\n if (typeof Map === 'undefined') {\n return false;\n }\n\n return isMapToString.working\n ? isMapToString(value)\n : value instanceof Map;\n}\nexports.isMap = isMap;\n\nfunction isSetToString(value) {\n return ObjectToString(value) === '[object Set]';\n}\nisSetToString.working = (\n typeof Set !== 'undefined' &&\n isSetToString(new Set())\n);\nfunction isSet(value) {\n if (typeof Set === 'undefined') {\n return false;\n }\n\n return isSetToString.working\n ? isSetToString(value)\n : value instanceof Set;\n}\nexports.isSet = isSet;\n\nfunction isWeakMapToString(value) {\n return ObjectToString(value) === '[object WeakMap]';\n}\nisWeakMapToString.working = (\n typeof WeakMap !== 'undefined' &&\n isWeakMapToString(new WeakMap())\n);\nfunction isWeakMap(value) {\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n return isWeakMapToString.working\n ? isWeakMapToString(value)\n : value instanceof WeakMap;\n}\nexports.isWeakMap = isWeakMap;\n\nfunction isWeakSetToString(value) {\n return ObjectToString(value) === '[object WeakSet]';\n}\nisWeakSetToString.working = (\n typeof WeakSet !== 'undefined' &&\n isWeakSetToString(new WeakSet())\n);\nfunction isWeakSet(value) {\n return isWeakSetToString(value);\n}\nexports.isWeakSet = isWeakSet;\n\nfunction isArrayBufferToString(value) {\n return ObjectToString(value) === '[object ArrayBuffer]';\n}\nisArrayBufferToString.working = (\n typeof ArrayBuffer !== 'undefined' &&\n isArrayBufferToString(new ArrayBuffer())\n);\nfunction isArrayBuffer(value) {\n if (typeof ArrayBuffer === 'undefined') {\n return false;\n }\n\n return isArrayBufferToString.working\n ? isArrayBufferToString(value)\n : value instanceof ArrayBuffer;\n}\nexports.isArrayBuffer = isArrayBuffer;\n\nfunction isDataViewToString(value) {\n return ObjectToString(value) === '[object DataView]';\n}\nisDataViewToString.working = (\n typeof ArrayBuffer !== 'undefined' &&\n typeof DataView !== 'undefined' &&\n isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))\n);\nfunction isDataView(value) {\n if (typeof DataView === 'undefined') {\n return false;\n }\n\n return isDataViewToString.working\n ? isDataViewToString(value)\n : value instanceof DataView;\n}\nexports.isDataView = isDataView;\n\nfunction isSharedArrayBufferToString(value) {\n return ObjectToString(value) === '[object SharedArrayBuffer]';\n}\nisSharedArrayBufferToString.working = (\n typeof SharedArrayBuffer !== 'undefined' &&\n isSharedArrayBufferToString(new SharedArrayBuffer())\n);\nfunction isSharedArrayBuffer(value) {\n if (typeof SharedArrayBuffer === 'undefined') {\n return false;\n }\n\n return isSharedArrayBufferToString.working\n ? isSharedArrayBufferToString(value)\n : value instanceof SharedArrayBuffer;\n}\nexports.isSharedArrayBuffer = isSharedArrayBuffer;\n\nfunction isAsyncFunction(value) {\n return ObjectToString(value) === '[object AsyncFunction]';\n}\nexports.isAsyncFunction = isAsyncFunction;\n\nfunction isMapIterator(value) {\n return ObjectToString(value) === '[object Map Iterator]';\n}\nexports.isMapIterator = isMapIterator;\n\nfunction isSetIterator(value) {\n return ObjectToString(value) === '[object Set Iterator]';\n}\nexports.isSetIterator = isSetIterator;\n\nfunction isGeneratorObject(value) {\n return ObjectToString(value) === '[object Generator]';\n}\nexports.isGeneratorObject = isGeneratorObject;\n\nfunction isWebAssemblyCompiledModule(value) {\n return ObjectToString(value) === '[object WebAssembly.Module]';\n}\nexports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;\n\nfunction isNumberObject(value) {\n return checkBoxedPrimitive(value, numberValue);\n}\nexports.isNumberObject = isNumberObject;\n\nfunction isStringObject(value) {\n return checkBoxedPrimitive(value, stringValue);\n}\nexports.isStringObject = isStringObject;\n\nfunction isBooleanObject(value) {\n return checkBoxedPrimitive(value, booleanValue);\n}\nexports.isBooleanObject = isBooleanObject;\n\nfunction isBigIntObject(value) {\n return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);\n}\nexports.isBigIntObject = isBigIntObject;\n\nfunction isSymbolObject(value) {\n return SymbolSupported && checkBoxedPrimitive(value, symbolValue);\n}\nexports.isSymbolObject = isSymbolObject;\n\nfunction isBoxedPrimitive(value) {\n return (\n isNumberObject(value) ||\n isStringObject(value) ||\n isBooleanObject(value) ||\n isBigIntObject(value) ||\n isSymbolObject(value)\n );\n}\nexports.isBoxedPrimitive = isBoxedPrimitive;\n\nfunction isAnyArrayBuffer(value) {\n return typeof Uint8Array !== 'undefined' && (\n isArrayBuffer(value) ||\n isSharedArrayBuffer(value)\n );\n}\nexports.isAnyArrayBuffer = isAnyArrayBuffer;\n\n['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {\n Object.defineProperty(exports, method, {\n enumerable: false,\n value: function() {\n throw new Error(method + ' is not supported in userland');\n }\n });\n});\n\n},{\"is-arguments\":46,\"is-generator-function\":47,\"is-typed-array\":48,\"which-typed-array\":82}],81:[function(require,module,exports){\n(function (process){(function (){\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||\n function getOwnPropertyDescriptors(obj) {\n var keys = Object.keys(obj);\n var descriptors = {};\n for (var i = 0; i < keys.length; i++) {\n descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);\n }\n return descriptors;\n };\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n if (typeof process !== 'undefined' && process.noDeprecation === true) {\n return fn;\n }\n\n // Allow for deprecating things in the process of starting up.\n if (typeof process === 'undefined') {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnvRegex = /^$/;\n\nif (process.env.NODE_DEBUG) {\n var debugEnv = process.env.NODE_DEBUG;\n debugEnv = debugEnv.replace(/[|\\\\{}()[\\]^$+?.]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/,/g, '$|^')\n .toUpperCase();\n debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');\n}\nexports.debuglog = function(set) {\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (debugEnvRegex.test(set)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nexports.types = require('./support/types');\n\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\nexports.types.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\nexports.types.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\nexports.types.isNativeError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nvar kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;\n\nexports.promisify = function promisify(original) {\n if (typeof original !== 'function')\n throw new TypeError('The \"original\" argument must be of type Function');\n\n if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {\n var fn = original[kCustomPromisifiedSymbol];\n if (typeof fn !== 'function') {\n throw new TypeError('The \"util.promisify.custom\" argument must be of type Function');\n }\n Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return fn;\n }\n\n function fn() {\n var promiseResolve, promiseReject;\n var promise = new Promise(function (resolve, reject) {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n args.push(function (err, value) {\n if (err) {\n promiseReject(err);\n } else {\n promiseResolve(value);\n }\n });\n\n try {\n original.apply(this, args);\n } catch (err) {\n promiseReject(err);\n }\n\n return promise;\n }\n\n Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\n if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return Object.defineProperties(\n fn,\n getOwnPropertyDescriptors(original)\n );\n}\n\nexports.promisify.custom = kCustomPromisifiedSymbol\n\nfunction callbackifyOnRejected(reason, cb) {\n // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).\n // Because `null` is a special error value in callbacks which means \"no error\n // occurred\", we error-wrap so the callback consumer can distinguish between\n // \"the promise rejected with null\" or \"the promise fulfilled with undefined\".\n if (!reason) {\n var newReason = new Error('Promise was rejected with a falsy value');\n newReason.reason = reason;\n reason = newReason;\n }\n return cb(reason);\n}\n\nfunction callbackify(original) {\n if (typeof original !== 'function') {\n throw new TypeError('The \"original\" argument must be of type Function');\n }\n\n // We DO NOT return the promise as it gives the user a false sense that\n // the promise is actually somehow related to the callback's execution\n // and that the callback throwing will reject the promise.\n function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) },\n function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });\n }\n\n Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));\n Object.defineProperties(callbackified,\n getOwnPropertyDescriptors(original));\n return callbackified;\n}\nexports.callbackify = callbackify;\n\n}).call(this)}).call(this,require('_process'))\n},{\"./support/isBuffer\":79,\"./support/types\":80,\"_process\":60,\"inherits\":45}],82:[function(require,module,exports){\n(function (global){(function (){\n'use strict';\n\nvar forEach = require('foreach');\nvar availableTypedArrays = require('available-typed-arrays');\nvar callBound = require('es-abstract/helpers/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\nvar hasSymbols = require('has-symbols')();\nvar hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol';\n\nvar typedArrays = availableTypedArrays();\n\nvar $slice = callBound('String.prototype.slice');\nvar toStrTags = {};\nvar gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');\nvar getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');\nif (hasToStringTag && gOPD && getPrototypeOf) {\n\tforEach(typedArrays, function (typedArray) {\n\t\tif (typeof global[typedArray] === 'function') {\n\t\t\tvar arr = new global[typedArray]();\n\t\t\tif (!(Symbol.toStringTag in arr)) {\n\t\t\t\tthrow new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.');\n\t\t\t}\n\t\t\tvar proto = getPrototypeOf(arr);\n\t\t\tvar descriptor = gOPD(proto, Symbol.toStringTag);\n\t\t\tif (!descriptor) {\n\t\t\t\tvar superProto = getPrototypeOf(proto);\n\t\t\t\tdescriptor = gOPD(superProto, Symbol.toStringTag);\n\t\t\t}\n\t\t\ttoStrTags[typedArray] = descriptor.get;\n\t\t}\n\t});\n}\n\nvar tryTypedArrays = function tryAllTypedArrays(value) {\n\tvar foundName = false;\n\tforEach(toStrTags, function (getter, typedArray) {\n\t\tif (!foundName) {\n\t\t\ttry {\n\t\t\t\tvar name = getter.call(value);\n\t\t\t\tif (name === typedArray) {\n\t\t\t\t\tfoundName = name;\n\t\t\t\t}\n\t\t\t} catch (e) {}\n\t\t}\n\t});\n\treturn foundName;\n};\n\nvar isTypedArray = require('is-typed-array');\n\nmodule.exports = function whichTypedArray(value) {\n\tif (!isTypedArray(value)) { return false; }\n\tif (!hasToStringTag) { return $slice($toString(value), 8, -1); }\n\treturn tryTypedArrays(value);\n};\n\n}).call(this)}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"available-typed-arrays\":27,\"es-abstract/helpers/callBound\":36,\"es-abstract/helpers/getOwnPropertyDescriptor\":37,\"foreach\":39,\"has-symbols\":42,\"is-typed-array\":48}]},{},[20])(20)\n});","// shim for using process in browser\n\nvar process = module.exports = {};\n\nprocess.nextTick = (function () {\n var canSetImmediate = typeof window !== 'undefined'\n && window.setImmediate;\n var canPost = typeof window !== 'undefined'\n && window.postMessage && window.addEventListener\n ;\n\n if (canSetImmediate) {\n return function (f) { return window.setImmediate(f) };\n }\n\n if (canPost) {\n var queue = [];\n window.addEventListener('message', function (ev) {\n var source = ev.source;\n if ((source === window || source === null) && ev.data === 'process-tick') {\n ev.stopPropagation();\n if (queue.length > 0) {\n var fn = queue.shift();\n fn();\n }\n }\n }, true);\n\n return function nextTick(fn) {\n queue.push(fn);\n window.postMessage('process-tick', '*');\n };\n }\n\n return function nextTick(fn) {\n setTimeout(fn, 0);\n };\n})();\n\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n}\n\n// TODO(shtylman)\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.AbstractTokenizer = void 0;\r\nconst peek_readable_1 = require(\"peek-readable\");\r\n/**\r\n * Core tokenizer\r\n */\r\nclass AbstractTokenizer {\r\n constructor(fileInfo) {\r\n /**\r\n * Tokenizer-stream position\r\n */\r\n this.position = 0;\r\n this.numBuffer = new Uint8Array(8);\r\n this.fileInfo = fileInfo ? fileInfo : {};\r\n }\r\n /**\r\n * Read a token from the tokenizer-stream\r\n * @param token - The token to read\r\n * @param position - If provided, the desired position in the tokenizer-stream\r\n * @returns Promise with token data\r\n */\r\n async readToken(token, position = this.position) {\r\n const uint8Array = Buffer.alloc(token.len);\r\n const len = await this.readBuffer(uint8Array, { position });\r\n if (len < token.len)\r\n throw new peek_readable_1.EndOfStreamError();\r\n return token.get(uint8Array, 0);\r\n }\r\n /**\r\n * Peek a token from the tokenizer-stream.\r\n * @param token - Token to peek from the tokenizer-stream.\r\n * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.\r\n * @returns Promise with token data\r\n */\r\n async peekToken(token, position = this.position) {\r\n const uint8Array = Buffer.alloc(token.len);\r\n const len = await this.peekBuffer(uint8Array, { position });\r\n if (len < token.len)\r\n throw new peek_readable_1.EndOfStreamError();\r\n return token.get(uint8Array, 0);\r\n }\r\n /**\r\n * Read a numeric token from the stream\r\n * @param token - Numeric token\r\n * @returns Promise with number\r\n */\r\n async readNumber(token) {\r\n const len = await this.readBuffer(this.numBuffer, { length: token.len });\r\n if (len < token.len)\r\n throw new peek_readable_1.EndOfStreamError();\r\n return token.get(this.numBuffer, 0);\r\n }\r\n /**\r\n * Read a numeric token from the stream\r\n * @param token - Numeric token\r\n * @returns Promise with number\r\n */\r\n async peekNumber(token) {\r\n const len = await this.peekBuffer(this.numBuffer, { length: token.len });\r\n if (len < token.len)\r\n throw new peek_readable_1.EndOfStreamError();\r\n return token.get(this.numBuffer, 0);\r\n }\r\n /**\r\n * Ignore number of bytes, advances the pointer in under tokenizer-stream.\r\n * @param length - Number of bytes to ignore\r\n * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available\r\n */\r\n async ignore(length) {\r\n if (this.fileInfo.size !== undefined) {\r\n const bytesLeft = this.fileInfo.size - this.position;\r\n if (length > bytesLeft) {\r\n this.position += bytesLeft;\r\n return bytesLeft;\r\n }\r\n }\r\n this.position += length;\r\n return length;\r\n }\r\n async close() {\r\n // empty\r\n }\r\n normalizeOptions(uint8Array, options) {\r\n if (options && options.position !== undefined && options.position < this.position) {\r\n throw new Error('`options.position` must be equal or greater than `tokenizer.position`');\r\n }\r\n if (options) {\r\n return {\r\n mayBeLess: options.mayBeLess === true,\r\n offset: options.offset ? options.offset : 0,\r\n length: options.length ? options.length : (uint8Array.length - (options.offset ? options.offset : 0)),\r\n position: options.position ? options.position : this.position\r\n };\r\n }\r\n return {\r\n mayBeLess: false,\r\n offset: 0,\r\n length: uint8Array.length,\r\n position: this.position\r\n };\r\n }\r\n}\r\nexports.AbstractTokenizer = AbstractTokenizer;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.BufferTokenizer = void 0;\r\nconst peek_readable_1 = require(\"peek-readable\");\r\nconst AbstractTokenizer_1 = require(\"./AbstractTokenizer\");\r\nclass BufferTokenizer extends AbstractTokenizer_1.AbstractTokenizer {\r\n /**\r\n * Construct BufferTokenizer\r\n * @param uint8Array - Uint8Array to tokenize\r\n * @param fileInfo - Pass additional file information to the tokenizer\r\n */\r\n constructor(uint8Array, fileInfo) {\r\n super(fileInfo);\r\n this.uint8Array = uint8Array;\r\n this.fileInfo.size = this.fileInfo.size ? this.fileInfo.size : uint8Array.length;\r\n }\r\n /**\r\n * Read buffer from tokenizer\r\n * @param uint8Array - Uint8Array to tokenize\r\n * @param options - Read behaviour options\r\n * @returns {Promise}\r\n */\r\n async readBuffer(uint8Array, options) {\r\n if (options && options.position) {\r\n if (options.position < this.position) {\r\n throw new Error('`options.position` must be equal or greater than `tokenizer.position`');\r\n }\r\n this.position = options.position;\r\n }\r\n const bytesRead = await this.peekBuffer(uint8Array, options);\r\n this.position += bytesRead;\r\n return bytesRead;\r\n }\r\n /**\r\n * Peek (read ahead) buffer from tokenizer\r\n * @param uint8Array\r\n * @param options - Read behaviour options\r\n * @returns {Promise}\r\n */\r\n async peekBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length);\r\n if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n else {\r\n uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read), normOptions.offset);\r\n return bytes2read;\r\n }\r\n }\r\n async close() {\r\n // empty\r\n }\r\n}\r\nexports.BufferTokenizer = BufferTokenizer;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.fromFile = exports.FileTokenizer = void 0;\r\nconst AbstractTokenizer_1 = require(\"./AbstractTokenizer\");\r\nconst peek_readable_1 = require(\"peek-readable\");\r\nconst fs = require(\"./FsPromise\");\r\nclass FileTokenizer extends AbstractTokenizer_1.AbstractTokenizer {\r\n constructor(fd, fileInfo) {\r\n super(fileInfo);\r\n this.fd = fd;\r\n }\r\n /**\r\n * Read buffer from file\r\n * @param uint8Array - Uint8Array to write result to\r\n * @param options - Read behaviour options\r\n * @returns Promise number of bytes read\r\n */\r\n async readBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n this.position = normOptions.position;\r\n const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position);\r\n this.position += res.bytesRead;\r\n if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n return res.bytesRead;\r\n }\r\n /**\r\n * Peek buffer from file\r\n * @param uint8Array - Uint8Array (or Buffer) to write data to\r\n * @param options - Read behaviour options\r\n * @returns Promise number of bytes read\r\n */\r\n async peekBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position);\r\n if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n return res.bytesRead;\r\n }\r\n async close() {\r\n return fs.close(this.fd);\r\n }\r\n}\r\nexports.FileTokenizer = FileTokenizer;\r\nasync function fromFile(sourceFilePath) {\r\n const stat = await fs.stat(sourceFilePath);\r\n if (!stat.isFile) {\r\n throw new Error(`File not a file: ${sourceFilePath}`);\r\n }\r\n const fd = await fs.open(sourceFilePath, 'r');\r\n return new FileTokenizer(fd, { path: sourceFilePath, size: stat.size });\r\n}\r\nexports.fromFile = fromFile;\r\n","\"use strict\";\r\n/**\r\n * Module convert fs functions to promise based functions\r\n */\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.readFile = exports.writeFileSync = exports.writeFile = exports.read = exports.open = exports.close = exports.stat = exports.createReadStream = exports.pathExists = void 0;\r\nconst fs = require(\"fs\");\r\nexports.pathExists = fs.existsSync;\r\nexports.createReadStream = fs.createReadStream;\r\nasync function stat(path) {\r\n return new Promise((resolve, reject) => {\r\n fs.stat(path, (err, stats) => {\r\n if (err)\r\n reject(err);\r\n else\r\n resolve(stats);\r\n });\r\n });\r\n}\r\nexports.stat = stat;\r\nasync function close(fd) {\r\n return new Promise((resolve, reject) => {\r\n fs.close(fd, err => {\r\n if (err)\r\n reject(err);\r\n else\r\n resolve();\r\n });\r\n });\r\n}\r\nexports.close = close;\r\nasync function open(path, mode) {\r\n return new Promise((resolve, reject) => {\r\n fs.open(path, mode, (err, fd) => {\r\n if (err)\r\n reject(err);\r\n else\r\n resolve(fd);\r\n });\r\n });\r\n}\r\nexports.open = open;\r\nasync function read(fd, buffer, offset, length, position) {\r\n return new Promise((resolve, reject) => {\r\n fs.read(fd, buffer, offset, length, position, (err, bytesRead, _buffer) => {\r\n if (err)\r\n reject(err);\r\n else\r\n resolve({ bytesRead, buffer: _buffer });\r\n });\r\n });\r\n}\r\nexports.read = read;\r\nasync function writeFile(path, data) {\r\n return new Promise((resolve, reject) => {\r\n fs.writeFile(path, data, err => {\r\n if (err)\r\n reject(err);\r\n else\r\n resolve();\r\n });\r\n });\r\n}\r\nexports.writeFile = writeFile;\r\nfunction writeFileSync(path, data) {\r\n fs.writeFileSync(path, data);\r\n}\r\nexports.writeFileSync = writeFileSync;\r\nasync function readFile(path) {\r\n return new Promise((resolve, reject) => {\r\n fs.readFile(path, (err, buffer) => {\r\n if (err)\r\n reject(err);\r\n else\r\n resolve(buffer);\r\n });\r\n });\r\n}\r\nexports.readFile = readFile;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.ReadStreamTokenizer = void 0;\r\nconst AbstractTokenizer_1 = require(\"./AbstractTokenizer\");\r\nconst peek_readable_1 = require(\"peek-readable\");\r\nconst maxBufferSize = 256000;\r\nclass ReadStreamTokenizer extends AbstractTokenizer_1.AbstractTokenizer {\r\n constructor(stream, fileInfo) {\r\n super(fileInfo);\r\n this.streamReader = new peek_readable_1.StreamReader(stream);\r\n }\r\n /**\r\n * Get file information, an HTTP-client may implement this doing a HEAD request\r\n * @return Promise with file information\r\n */\r\n async getFileInfo() {\r\n return this.fileInfo;\r\n }\r\n /**\r\n * Read buffer from tokenizer\r\n * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream\r\n * @param options - Read behaviour options\r\n * @returns Promise with number of bytes read\r\n */\r\n async readBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n const skipBytes = normOptions.position - this.position;\r\n if (skipBytes > 0) {\r\n await this.ignore(skipBytes);\r\n return this.readBuffer(uint8Array, options);\r\n }\r\n else if (skipBytes < 0) {\r\n throw new Error('`options.position` must be equal or greater than `tokenizer.position`');\r\n }\r\n if (normOptions.length === 0) {\r\n return 0;\r\n }\r\n const bytesRead = await this.streamReader.read(uint8Array, normOptions.offset, normOptions.length);\r\n this.position += bytesRead;\r\n if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n return bytesRead;\r\n }\r\n /**\r\n * Peek (read ahead) buffer from tokenizer\r\n * @param uint8Array - Uint8Array (or Buffer) to write data to\r\n * @param options - Read behaviour options\r\n * @returns Promise with number of bytes peeked\r\n */\r\n async peekBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n let bytesRead = 0;\r\n if (normOptions.position) {\r\n const skipBytes = normOptions.position - this.position;\r\n if (skipBytes > 0) {\r\n const skipBuffer = new Uint8Array(normOptions.length + skipBytes);\r\n bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess });\r\n uint8Array.set(skipBuffer.subarray(skipBytes), normOptions.offset);\r\n return bytesRead - skipBytes;\r\n }\r\n else if (skipBytes < 0) {\r\n throw new Error('Cannot peek from a negative offset in a stream');\r\n }\r\n }\r\n if (normOptions.length > 0) {\r\n try {\r\n bytesRead = await this.streamReader.peek(uint8Array, normOptions.offset, normOptions.length);\r\n }\r\n catch (err) {\r\n if (options && options.mayBeLess && err instanceof peek_readable_1.EndOfStreamError) {\r\n return 0;\r\n }\r\n throw err;\r\n }\r\n if ((!normOptions.mayBeLess) && bytesRead < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n }\r\n return bytesRead;\r\n }\r\n async ignore(length) {\r\n // debug(`ignore ${this.position}...${this.position + length - 1}`);\r\n const bufSize = Math.min(maxBufferSize, length);\r\n const buf = new Uint8Array(bufSize);\r\n let totBytesRead = 0;\r\n while (totBytesRead < length) {\r\n const remaining = length - totBytesRead;\r\n const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) });\r\n if (bytesRead < 0) {\r\n return bytesRead;\r\n }\r\n totBytesRead += bytesRead;\r\n }\r\n return totBytesRead;\r\n }\r\n}\r\nexports.ReadStreamTokenizer = ReadStreamTokenizer;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.fromBuffer = exports.fromStream = exports.EndOfStreamError = void 0;\r\nconst ReadStreamTokenizer_1 = require(\"./ReadStreamTokenizer\");\r\nconst BufferTokenizer_1 = require(\"./BufferTokenizer\");\r\nvar peek_readable_1 = require(\"peek-readable\");\r\nObject.defineProperty(exports, \"EndOfStreamError\", { enumerable: true, get: function () { return peek_readable_1.EndOfStreamError; } });\r\n/**\r\n * Construct ReadStreamTokenizer from given Stream.\r\n * Will set fileSize, if provided given Stream has set the .path property/\r\n * @param stream - Read from Node.js Stream.Readable\r\n * @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream.\r\n * @returns ReadStreamTokenizer\r\n */\r\nfunction fromStream(stream, fileInfo) {\r\n fileInfo = fileInfo ? fileInfo : {};\r\n return new ReadStreamTokenizer_1.ReadStreamTokenizer(stream, fileInfo);\r\n}\r\nexports.fromStream = fromStream;\r\n/**\r\n * Construct ReadStreamTokenizer from given Buffer.\r\n * @param uint8Array - Uint8Array to tokenize\r\n * @param fileInfo - Pass additional file information to the tokenizer\r\n * @returns BufferTokenizer\r\n */\r\nfunction fromBuffer(uint8Array, fileInfo) {\r\n return new BufferTokenizer_1.BufferTokenizer(uint8Array, fileInfo);\r\n}\r\nexports.fromBuffer = fromBuffer;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.fromStream = exports.fromBuffer = exports.EndOfStreamError = exports.fromFile = void 0;\r\nconst fs = require(\"./FsPromise\");\r\nconst core = require(\"./core\");\r\nvar FileTokenizer_1 = require(\"./FileTokenizer\");\r\nObject.defineProperty(exports, \"fromFile\", { enumerable: true, get: function () { return FileTokenizer_1.fromFile; } });\r\nvar core_1 = require(\"./core\");\r\nObject.defineProperty(exports, \"EndOfStreamError\", { enumerable: true, get: function () { return core_1.EndOfStreamError; } });\r\nObject.defineProperty(exports, \"fromBuffer\", { enumerable: true, get: function () { return core_1.fromBuffer; } });\r\n/**\r\n * Construct ReadStreamTokenizer from given Stream.\r\n * Will set fileSize, if provided given Stream has set the .path property.\r\n * @param stream - Node.js Stream.Readable\r\n * @param fileInfo - Pass additional file information to the tokenizer\r\n * @returns Tokenizer\r\n */\r\nasync function fromStream(stream, fileInfo) {\r\n fileInfo = fileInfo ? fileInfo : {};\r\n if (stream.path) {\r\n const stat = await fs.stat(stream.path);\r\n fileInfo.path = stream.path;\r\n fileInfo.size = stat.size;\r\n }\r\n return core.fromStream(stream, fileInfo);\r\n}\r\nexports.fromStream = fromStream;\r\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nexports.clone = clone;\nexports.addLast = addLast;\nexports.addFirst = addFirst;\nexports.removeLast = removeLast;\nexports.removeFirst = removeFirst;\nexports.insert = insert;\nexports.removeAt = removeAt;\nexports.replaceAt = replaceAt;\nexports.getIn = getIn;\nexports.set = set;\nexports.setIn = setIn;\nexports.update = update;\nexports.updateIn = updateIn;\nexports.merge = merge;\nexports.mergeDeep = mergeDeep;\nexports.mergeIn = mergeIn;\nexports.omit = omit;\nexports.addDefaults = addDefaults;\n\n\n/*!\n * Timm\n *\n * Immutability helpers with fast reads and acceptable writes.\n *\n * @copyright Guillermo Grau Panea 2016\n * @license MIT\n */\n\nvar INVALID_ARGS = 'INVALID_ARGS';\n\n// ===============================================\n// ### Helpers\n// ===============================================\n\n\nfunction throwStr(msg) {\n throw new Error(msg);\n}\n\nfunction getKeysAndSymbols(obj) {\n var keys = Object.keys(obj);\n if (Object.getOwnPropertySymbols) {\n return keys.concat(Object.getOwnPropertySymbols(obj));\n }\n return keys;\n}\n\nvar hasOwnProperty = {}.hasOwnProperty;\n\nfunction clone(obj) {\n if (Array.isArray(obj)) return obj.slice();\n var keys = getKeysAndSymbols(obj);\n var out = {};\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n out[key] = obj[key];\n }\n return out;\n}\n\nfunction doMerge(fAddDefaults, fDeep, first) {\n var out = first;\n !(out != null) && throwStr(process.env.NODE_ENV !== 'production' ? 'At least one object should be provided to merge()' : INVALID_ARGS);\n var fChanged = false;\n\n for (var _len = arguments.length, rest = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {\n rest[_key - 3] = arguments[_key];\n }\n\n for (var idx = 0; idx < rest.length; idx++) {\n var obj = rest[idx];\n if (obj == null) continue;\n var keys = getKeysAndSymbols(obj);\n if (!keys.length) continue;\n for (var j = 0; j <= keys.length; j++) {\n var key = keys[j];\n if (fAddDefaults && out[key] !== undefined) continue;\n var nextVal = obj[key];\n if (fDeep && isObject(out[key]) && isObject(nextVal)) {\n nextVal = doMerge(fAddDefaults, fDeep, out[key], nextVal);\n }\n if (nextVal === undefined || nextVal === out[key]) continue;\n if (!fChanged) {\n fChanged = true;\n out = clone(out);\n }\n out[key] = nextVal;\n }\n }\n return out;\n}\n\nfunction isObject(o) {\n var type = typeof o === 'undefined' ? 'undefined' : _typeof(o);\n return o != null && type === 'object';\n}\n\n// _deepFreeze = (obj) ->\n// Object.freeze obj\n// for key in Object.getOwnPropertyNames obj\n// val = obj[key]\n// if isObject(val) and not Object.isFrozen val\n// _deepFreeze val\n// obj\n\n// ===============================================\n// -- ### Arrays\n// ===============================================\n\n// -- #### addLast()\n// -- Returns a new array with an appended item or items.\n// --\n// -- Usage: `addLast(array: Array, val: Array|T): Array`\n// --\n// -- ```js\n// -- arr = ['a', 'b']\n// -- arr2 = addLast(arr, 'c')\n// -- // ['a', 'b', 'c']\n// -- arr2 === arr\n// -- // false\n// -- arr3 = addLast(arr, ['c', 'd'])\n// -- // ['a', 'b', 'c', 'd']\n// -- ```\n// `array.concat(val)` also handles the scalar case,\n// but is apparently very slow\nfunction addLast(array, val) {\n if (Array.isArray(val)) return array.concat(val);\n return array.concat([val]);\n}\n\n// -- #### addFirst()\n// -- Returns a new array with a prepended item or items.\n// --\n// -- Usage: `addFirst(array: Array, val: Array|T): Array`\n// --\n// -- ```js\n// -- arr = ['a', 'b']\n// -- arr2 = addFirst(arr, 'c')\n// -- // ['c', 'a', 'b']\n// -- arr2 === arr\n// -- // false\n// -- arr3 = addFirst(arr, ['c', 'd'])\n// -- // ['c', 'd', 'a', 'b']\n// -- ```\nfunction addFirst(array, val) {\n if (Array.isArray(val)) return val.concat(array);\n return [val].concat(array);\n}\n\n// -- #### removeLast()\n// -- Returns a new array removing the last item.\n// --\n// -- Usage: `removeLast(array: Array): Array`\n// --\n// -- ```js\n// -- arr = ['a', 'b']\n// -- arr2 = removeLast(arr)\n// -- // ['a']\n// -- arr2 === arr\n// -- // false\n// --\n// -- // The same array is returned if there are no changes:\n// -- arr3 = []\n// -- removeLast(arr3) === arr3\n// -- // true\n// -- ```\nfunction removeLast(array) {\n if (!array.length) return array;\n return array.slice(0, array.length - 1);\n}\n\n// -- #### removeFirst()\n// -- Returns a new array removing the first item.\n// --\n// -- Usage: `removeFirst(array: Array): Array`\n// --\n// -- ```js\n// -- arr = ['a', 'b']\n// -- arr2 = removeFirst(arr)\n// -- // ['b']\n// -- arr2 === arr\n// -- // false\n// --\n// -- // The same array is returned if there are no changes:\n// -- arr3 = []\n// -- removeFirst(arr3) === arr3\n// -- // true\n// -- ```\nfunction removeFirst(array) {\n if (!array.length) return array;\n return array.slice(1);\n}\n\n// -- #### insert()\n// -- Returns a new array obtained by inserting an item or items\n// -- at a specified index.\n// --\n// -- Usage: `insert(array: Array, idx: number, val: Array|T): Array`\n// --\n// -- ```js\n// -- arr = ['a', 'b', 'c']\n// -- arr2 = insert(arr, 1, 'd')\n// -- // ['a', 'd', 'b', 'c']\n// -- arr2 === arr\n// -- // false\n// -- insert(arr, 1, ['d', 'e'])\n// -- // ['a', 'd', 'e', 'b', 'c']\n// -- ```\nfunction insert(array, idx, val) {\n return array.slice(0, idx).concat(Array.isArray(val) ? val : [val]).concat(array.slice(idx));\n}\n\n// -- #### removeAt()\n// -- Returns a new array obtained by removing an item at\n// -- a specified index.\n// --\n// -- Usage: `removeAt(array: Array, idx: number): Array`\n// --\n// -- ```js\n// -- arr = ['a', 'b', 'c']\n// -- arr2 = removeAt(arr, 1)\n// -- // ['a', 'c']\n// -- arr2 === arr\n// -- // false\n// --\n// -- // The same array is returned if there are no changes:\n// -- removeAt(arr, 4) === arr\n// -- // true\n// -- ```\nfunction removeAt(array, idx) {\n if (idx >= array.length || idx < 0) return array;\n return array.slice(0, idx).concat(array.slice(idx + 1));\n}\n\n// -- #### replaceAt()\n// -- Returns a new array obtained by replacing an item at\n// -- a specified index. If the provided item is the same as\n// -- (*referentially equal to*) the previous item at that position,\n// -- the original array is returned.\n// --\n// -- Usage: `replaceAt(array: Array, idx: number, newItem: T): Array`\n// --\n// -- ```js\n// -- arr = ['a', 'b', 'c']\n// -- arr2 = replaceAt(arr, 1, 'd')\n// -- // ['a', 'd', 'c']\n// -- arr2 === arr\n// -- // false\n// --\n// -- // The same object is returned if there are no changes:\n// -- replaceAt(arr, 1, 'b') === arr\n// -- // true\n// -- ```\nfunction replaceAt(array, idx, newItem) {\n if (array[idx] === newItem) return array;\n var len = array.length;\n var result = Array(len);\n for (var i = 0; i < len; i++) {\n result[i] = array[i];\n }\n result[idx] = newItem;\n return result;\n}\n\n// ===============================================\n// -- ### Collections (objects and arrays)\n// ===============================================\n// -- The following types are used throughout this section\n// -- ```js\n// -- type ArrayOrObject = Array|Object;\n// -- type Key = number|string;\n// -- ```\n\n// -- #### getIn()\n// -- Returns a value from an object at a given path. Works with\n// -- nested arrays and objects. If the path does not exist, it returns\n// -- `undefined`.\n// --\n// -- Usage: `getIn(obj: ?ArrayOrObject, path: Array): any`\n// --\n// -- ```js\n// -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: ['a', 'b', 'c'] }\n// -- getIn(obj, ['d', 'd1'])\n// -- // 3\n// -- getIn(obj, ['e', 1])\n// -- // 'b'\n// -- ```\nfunction getIn(obj, path) {\n !Array.isArray(path) && throwStr(process.env.NODE_ENV !== 'production' ? 'A path array should be provided when calling getIn()' : INVALID_ARGS);\n if (obj == null) return undefined;\n var ptr = obj;\n for (var i = 0; i < path.length; i++) {\n var key = path[i];\n ptr = ptr != null ? ptr[key] : undefined;\n if (ptr === undefined) return ptr;\n }\n return ptr;\n}\n\n// -- #### set()\n// -- Returns a new object with a modified attribute.\n// -- If the provided value is the same as (*referentially equal to*)\n// -- the previous value, the original object is returned.\n// --\n// -- Usage: `set(obj: ?T, key: Key, val: any): T`\n// --\n// -- ```js\n// -- obj = { a: 1, b: 2, c: 3 }\n// -- obj2 = set(obj, 'b', 5)\n// -- // { a: 1, b: 5, c: 3 }\n// -- obj2 === obj\n// -- // false\n// --\n// -- // The same object is returned if there are no changes:\n// -- set(obj, 'b', 2) === obj\n// -- // true\n// -- ```\nfunction set(obj, key, val) {\n var fallback = typeof key === 'number' ? [] : {};\n var finalObj = obj == null ? fallback : obj;\n if (finalObj[key] === val) return finalObj;\n var obj2 = clone(finalObj);\n obj2[key] = val;\n return obj2;\n}\n\n// -- #### setIn()\n// -- Returns a new object with a modified **nested** attribute.\n// --\n// -- Notes:\n// --\n// -- * If the provided value is the same as (*referentially equal to*)\n// -- the previous value, the original object is returned.\n// -- * If the path does not exist, it will be created before setting\n// -- the new value.\n// --\n// -- Usage: `setIn(obj: T, path: Array, val: any): T`\n// --\n// -- ```js\n// -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }\n// -- obj2 = setIn(obj, ['d', 'd1'], 4)\n// -- // { a: 1, b: 2, d: { d1: 4, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }\n// -- obj2 === obj\n// -- // false\n// -- obj2.d === obj.d\n// -- // false\n// -- obj2.e === obj.e\n// -- // true\n// --\n// -- // The same object is returned if there are no changes:\n// -- obj3 = setIn(obj, ['d', 'd1'], 3)\n// -- // { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }\n// -- obj3 === obj\n// -- // true\n// -- obj3.d === obj.d\n// -- // true\n// -- obj3.e === obj.e\n// -- // true\n// --\n// -- // ... unknown paths create intermediate keys. Numeric segments are treated as array indices:\n// -- setIn({ a: 3 }, ['unknown', 0, 'path'], 4)\n// -- // { a: 3, unknown: [{ path: 4 }] }\n// -- ```\nfunction doSetIn(obj, path, val, idx) {\n var newValue = void 0;\n var key = path[idx];\n if (idx === path.length - 1) {\n newValue = val;\n } else {\n var nestedObj = isObject(obj) && isObject(obj[key]) ? obj[key] : typeof path[idx + 1] === 'number' ? [] : {};\n newValue = doSetIn(nestedObj, path, val, idx + 1);\n }\n return set(obj, key, newValue);\n}\n\nfunction setIn(obj, path, val) {\n if (!path.length) return val;\n return doSetIn(obj, path, val, 0);\n}\n\n// -- #### update()\n// -- Returns a new object with a modified attribute,\n// -- calculated via a user-provided callback based on the current value.\n// -- If the calculated value is the same as (*referentially equal to*)\n// -- the previous value, the original object is returned.\n// --\n// -- Usage: `update(obj: T, key: Key,\n// -- fnUpdate: (prevValue: any) => any): T`\n// --\n// -- ```js\n// -- obj = { a: 1, b: 2, c: 3 }\n// -- obj2 = update(obj, 'b', (val) => val + 1)\n// -- // { a: 1, b: 3, c: 3 }\n// -- obj2 === obj\n// -- // false\n// --\n// -- // The same object is returned if there are no changes:\n// -- update(obj, 'b', (val) => val) === obj\n// -- // true\n// -- ```\nfunction update(obj, key, fnUpdate) {\n var prevVal = obj == null ? undefined : obj[key];\n var nextVal = fnUpdate(prevVal);\n return set(obj, key, nextVal);\n}\n\n// -- #### updateIn()\n// -- Returns a new object with a modified **nested** attribute,\n// -- calculated via a user-provided callback based on the current value.\n// -- If the calculated value is the same as (*referentially equal to*)\n// -- the previous value, the original object is returned.\n// --\n// -- Usage: `updateIn(obj: T, path: Array,\n// -- fnUpdate: (prevValue: any) => any): T`\n// --\n// -- ```js\n// -- obj = { a: 1, d: { d1: 3, d2: 4 } }\n// -- obj2 = updateIn(obj, ['d', 'd1'], (val) => val + 1)\n// -- // { a: 1, d: { d1: 4, d2: 4 } }\n// -- obj2 === obj\n// -- // false\n// --\n// -- // The same object is returned if there are no changes:\n// -- obj3 = updateIn(obj, ['d', 'd1'], (val) => val)\n// -- // { a: 1, d: { d1: 3, d2: 4 } }\n// -- obj3 === obj\n// -- // true\n// -- ```\nfunction updateIn(obj, path, fnUpdate) {\n var prevVal = getIn(obj, path);\n var nextVal = fnUpdate(prevVal);\n return setIn(obj, path, nextVal);\n}\n\n// -- #### merge()\n// -- Returns a new object built as follows: the overlapping keys from the\n// -- second one overwrite the corresponding entries from the first one.\n// -- Similar to `Object.assign()`, but immutable.\n// --\n// -- Usage:\n// --\n// -- * `merge(obj1: Object, obj2: ?Object): Object`\n// -- * `merge(obj1: Object, ...objects: Array): Object`\n// --\n// -- The unmodified `obj1` is returned if `obj2` does not *provide something\n// -- new to* `obj1`, i.e. if either of the following\n// -- conditions are true:\n// --\n// -- * `obj2` is `null` or `undefined`\n// -- * `obj2` is an object, but it is empty\n// -- * All attributes of `obj2` are `undefined`\n// -- * All attributes of `obj2` are referentially equal to the\n// -- corresponding attributes of `obj1`\n// --\n// -- Note that `undefined` attributes in `obj2` do not modify the\n// -- corresponding attributes in `obj1`.\n// --\n// -- ```js\n// -- obj1 = { a: 1, b: 2, c: 3 }\n// -- obj2 = { c: 4, d: 5 }\n// -- obj3 = merge(obj1, obj2)\n// -- // { a: 1, b: 2, c: 4, d: 5 }\n// -- obj3 === obj1\n// -- // false\n// --\n// -- // The same object is returned if there are no changes:\n// -- merge(obj1, { c: 3 }) === obj1\n// -- // true\n// -- ```\nfunction merge(a, b, c, d, e, f) {\n for (var _len2 = arguments.length, rest = Array(_len2 > 6 ? _len2 - 6 : 0), _key2 = 6; _key2 < _len2; _key2++) {\n rest[_key2 - 6] = arguments[_key2];\n }\n\n return rest.length ? doMerge.call.apply(doMerge, [null, false, false, a, b, c, d, e, f].concat(rest)) : doMerge(false, false, a, b, c, d, e, f);\n}\n\n// -- #### mergeDeep()\n// -- Returns a new object built as follows: the overlapping keys from the\n// -- second one overwrite the corresponding entries from the first one.\n// -- If both the first and second entries are objects they are merged recursively.\n// -- Similar to `Object.assign()`, but immutable, and deeply merging.\n// --\n// -- Usage:\n// --\n// -- * `mergeDeep(obj1: Object, obj2: ?Object): Object`\n// -- * `mergeDeep(obj1: Object, ...objects: Array): Object`\n// --\n// -- The unmodified `obj1` is returned if `obj2` does not *provide something\n// -- new to* `obj1`, i.e. if either of the following\n// -- conditions are true:\n// --\n// -- * `obj2` is `null` or `undefined`\n// -- * `obj2` is an object, but it is empty\n// -- * All attributes of `obj2` are `undefined`\n// -- * All attributes of `obj2` are referentially equal to the\n// -- corresponding attributes of `obj1`\n// --\n// -- Note that `undefined` attributes in `obj2` do not modify the\n// -- corresponding attributes in `obj1`.\n// --\n// -- ```js\n// -- obj1 = { a: 1, b: 2, c: { a: 1 } }\n// -- obj2 = { b: 3, c: { b: 2 } }\n// -- obj3 = mergeDeep(obj1, obj2)\n// -- // { a: 1, b: 3, c: { a: 1, b: 2 } }\n// -- obj3 === obj1\n// -- // false\n// --\n// -- // The same object is returned if there are no changes:\n// -- mergeDeep(obj1, { c: { a: 1 } }) === obj1\n// -- // true\n// -- ```\nfunction mergeDeep(a, b, c, d, e, f) {\n for (var _len3 = arguments.length, rest = Array(_len3 > 6 ? _len3 - 6 : 0), _key3 = 6; _key3 < _len3; _key3++) {\n rest[_key3 - 6] = arguments[_key3];\n }\n\n return rest.length ? doMerge.call.apply(doMerge, [null, false, true, a, b, c, d, e, f].concat(rest)) : doMerge(false, true, a, b, c, d, e, f);\n}\n\n// -- #### mergeIn()\n// -- Similar to `merge()`, but merging the value at a given nested path.\n// -- Note that the returned type is the same as that of the first argument.\n// --\n// -- Usage:\n// --\n// -- * `mergeIn(obj1: T, path: Array, obj2: ?Object): T`\n// -- * `mergeIn(obj1: T, path: Array,\n// -- ...objects: Array): T`\n// --\n// -- ```js\n// -- obj1 = { a: 1, d: { b: { d1: 3, d2: 4 } } }\n// -- obj2 = { d3: 5 }\n// -- obj3 = mergeIn(obj1, ['d', 'b'], obj2)\n// -- // { a: 1, d: { b: { d1: 3, d2: 4, d3: 5 } } }\n// -- obj3 === obj1\n// -- // false\n// --\n// -- // The same object is returned if there are no changes:\n// -- mergeIn(obj1, ['d', 'b'], { d2: 4 }) === obj1\n// -- // true\n// -- ```\nfunction mergeIn(a, path, b, c, d, e, f) {\n var prevVal = getIn(a, path);\n if (prevVal == null) prevVal = {};\n var nextVal = void 0;\n\n for (var _len4 = arguments.length, rest = Array(_len4 > 7 ? _len4 - 7 : 0), _key4 = 7; _key4 < _len4; _key4++) {\n rest[_key4 - 7] = arguments[_key4];\n }\n\n if (rest.length) {\n nextVal = doMerge.call.apply(doMerge, [null, false, false, prevVal, b, c, d, e, f].concat(rest));\n } else {\n nextVal = doMerge(false, false, prevVal, b, c, d, e, f);\n }\n return setIn(a, path, nextVal);\n}\n\n// -- #### omit()\n// -- Returns an object excluding one or several attributes.\n// --\n// -- Usage: `omit(obj: Object, attrs: Array|string): Object`\n//\n// -- ```js\n// -- obj = { a: 1, b: 2, c: 3, d: 4 }\n// -- omit(obj, 'a')\n// -- // { b: 2, c: 3, d: 4 }\n// -- omit(obj, ['b', 'c'])\n// -- // { a: 1, d: 4 }\n// --\n// -- // The same object is returned if there are no changes:\n// -- omit(obj, 'z') === obj1\n// -- // true\n// -- ```\nfunction omit(obj, attrs) {\n var omitList = Array.isArray(attrs) ? attrs : [attrs];\n var fDoSomething = false;\n for (var i = 0; i < omitList.length; i++) {\n if (hasOwnProperty.call(obj, omitList[i])) {\n fDoSomething = true;\n break;\n }\n }\n if (!fDoSomething) return obj;\n var out = {};\n var keys = getKeysAndSymbols(obj);\n for (var _i = 0; _i < keys.length; _i++) {\n var key = keys[_i];\n if (omitList.indexOf(key) >= 0) continue;\n out[key] = obj[key];\n }\n return out;\n}\n\n// -- #### addDefaults()\n// -- Returns a new object built as follows: `undefined` keys in the first one\n// -- are filled in with the corresponding values from the second one\n// -- (even if they are `null`).\n// --\n// -- Usage:\n// --\n// -- * `addDefaults(obj: Object, defaults: Object): Object`\n// -- * `addDefaults(obj: Object, ...defaultObjects: Array): Object`\n// --\n// -- ```js\n// -- obj1 = { a: 1, b: 2, c: 3 }\n// -- obj2 = { c: 4, d: 5, e: null }\n// -- obj3 = addDefaults(obj1, obj2)\n// -- // { a: 1, b: 2, c: 3, d: 5, e: null }\n// -- obj3 === obj1\n// -- // false\n// --\n// -- // The same object is returned if there are no changes:\n// -- addDefaults(obj1, { c: 4 }) === obj1\n// -- // true\n// -- ```\nfunction addDefaults(a, b, c, d, e, f) {\n for (var _len5 = arguments.length, rest = Array(_len5 > 6 ? _len5 - 6 : 0), _key5 = 6; _key5 < _len5; _key5++) {\n rest[_key5 - 6] = arguments[_key5];\n }\n\n return rest.length ? doMerge.call.apply(doMerge, [null, true, false, a, b, c, d, e, f].concat(rest)) : doMerge(true, false, a, b, c, d, e, f);\n}\n\n// ===============================================\n// ### Public API\n// ===============================================\nvar timm = {\n clone: clone,\n addLast: addLast,\n addFirst: addFirst,\n removeLast: removeLast,\n removeFirst: removeFirst,\n insert: insert,\n removeAt: removeAt,\n replaceAt: replaceAt,\n\n getIn: getIn,\n // eslint-disable-next-line object-shorthand\n set: set, // so that flow doesn't complain\n setIn: setIn,\n update: update,\n updateIn: updateIn,\n merge: merge,\n mergeDeep: mergeDeep,\n mergeIn: mergeIn,\n omit: omit,\n addDefaults: addDefaults\n};\n\nexports.default = timm;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AnsiStringType = exports.StringType = exports.BufferType = exports.Uint8ArrayType = exports.IgnoreType = exports.Float80_LE = exports.Float80_BE = exports.Float64_LE = exports.Float64_BE = exports.Float32_LE = exports.Float32_BE = exports.Float16_LE = exports.Float16_BE = exports.INT64_BE = exports.UINT64_BE = exports.INT64_LE = exports.UINT64_LE = exports.INT32_LE = exports.INT32_BE = exports.INT24_BE = exports.INT24_LE = exports.INT16_LE = exports.INT16_BE = exports.INT8 = exports.UINT32_BE = exports.UINT32_LE = exports.UINT24_BE = exports.UINT24_LE = exports.UINT16_BE = exports.UINT16_LE = exports.UINT8 = void 0;\nconst ieee754 = require(\"ieee754\");\n// Primitive types\nfunction dv(array) {\n return new DataView(array.buffer, array.byteOffset);\n}\n/**\n * 8-bit unsigned integer\n */\nexports.UINT8 = {\n len: 1,\n get(array, offset) {\n return dv(array).getUint8(offset);\n },\n put(array, offset, value) {\n dv(array).setUint8(offset, value);\n return offset + 1;\n }\n};\n/**\n * 16-bit unsigned integer, Little Endian byte order\n */\nexports.UINT16_LE = {\n len: 2,\n get(array, offset) {\n return dv(array).getUint16(offset, true);\n },\n put(array, offset, value) {\n dv(array).setUint16(offset, value, true);\n return offset + 2;\n }\n};\n/**\n * 16-bit unsigned integer, Big Endian byte order\n */\nexports.UINT16_BE = {\n len: 2,\n get(array, offset) {\n return dv(array).getUint16(offset);\n },\n put(array, offset, value) {\n dv(array).setUint16(offset, value);\n return offset + 2;\n }\n};\n/**\n * 24-bit unsigned integer, Little Endian byte order\n */\nexports.UINT24_LE = {\n len: 3,\n get(array, offset) {\n const dataView = dv(array);\n return dataView.getUint8(offset) + (dataView.getUint16(offset + 1, true) << 8);\n },\n put(array, offset, value) {\n const dataView = dv(array);\n dataView.setUint8(offset, value & 0xff);\n dataView.setUint16(offset + 1, value >> 8, true);\n return offset + 3;\n }\n};\n/**\n * 24-bit unsigned integer, Big Endian byte order\n */\nexports.UINT24_BE = {\n len: 3,\n get(array, offset) {\n const dataView = dv(array);\n return (dataView.getUint16(offset) << 8) + dataView.getUint8(offset + 2);\n },\n put(array, offset, value) {\n const dataView = dv(array);\n dataView.setUint16(offset, value >> 8);\n dataView.setUint8(offset + 2, value & 0xff);\n return offset + 3;\n }\n};\n/**\n * 32-bit unsigned integer, Little Endian byte order\n */\nexports.UINT32_LE = {\n len: 4,\n get(array, offset) {\n return dv(array).getUint32(offset, true);\n },\n put(array, offset, value) {\n dv(array).setUint32(offset, value, true);\n return offset + 4;\n }\n};\n/**\n * 32-bit unsigned integer, Big Endian byte order\n */\nexports.UINT32_BE = {\n len: 4,\n get(array, offset) {\n return dv(array).getUint32(offset);\n },\n put(array, offset, value) {\n dv(array).setUint32(offset, value);\n return offset + 4;\n }\n};\n/**\n * 8-bit signed integer\n */\nexports.INT8 = {\n len: 1,\n get(array, offset) {\n return dv(array).getInt8(offset);\n },\n put(array, offset, value) {\n dv(array).setInt8(offset, value);\n return offset + 1;\n }\n};\n/**\n * 16-bit signed integer, Big Endian byte order\n */\nexports.INT16_BE = {\n len: 2,\n get(array, offset) {\n return dv(array).getInt16(offset);\n },\n put(array, offset, value) {\n dv(array).setInt16(offset, value);\n return offset + 2;\n }\n};\n/**\n * 16-bit signed integer, Little Endian byte order\n */\nexports.INT16_LE = {\n len: 2,\n get(array, offset) {\n return dv(array).getInt16(offset, true);\n },\n put(array, offset, value) {\n dv(array).setInt16(offset, value, true);\n return offset + 2;\n }\n};\n/**\n * 24-bit signed integer, Little Endian byte order\n */\nexports.INT24_LE = {\n len: 3,\n get(array, offset) {\n const unsigned = exports.UINT24_LE.get(array, offset);\n return unsigned > 0x7fffff ? unsigned - 0x1000000 : unsigned;\n },\n put(array, offset, value) {\n const dataView = dv(array);\n dataView.setUint8(offset, value & 0xff);\n dataView.setUint16(offset + 1, value >> 8, true);\n return offset + 3;\n }\n};\n/**\n * 24-bit signed integer, Big Endian byte order\n */\nexports.INT24_BE = {\n len: 3,\n get(array, offset) {\n const unsigned = exports.UINT24_BE.get(array, offset);\n return unsigned > 0x7fffff ? unsigned - 0x1000000 : unsigned;\n },\n put(array, offset, value) {\n const dataView = dv(array);\n dataView.setUint16(offset, value >> 8);\n dataView.setUint8(offset + 2, value & 0xff);\n return offset + 3;\n }\n};\n/**\n * 32-bit signed integer, Big Endian byte order\n */\nexports.INT32_BE = {\n len: 4,\n get(array, offset) {\n return dv(array).getInt32(offset);\n },\n put(array, offset, value) {\n dv(array).setInt32(offset, value);\n return offset + 4;\n }\n};\n/**\n * 32-bit signed integer, Big Endian byte order\n */\nexports.INT32_LE = {\n len: 4,\n get(array, offset) {\n return dv(array).getInt32(offset, true);\n },\n put(array, offset, value) {\n dv(array).setInt32(offset, value, true);\n return offset + 4;\n }\n};\n/**\n * 64-bit unsigned integer, Little Endian byte order\n */\nexports.UINT64_LE = {\n len: 8,\n get(array, offset) {\n return dv(array).getBigUint64(offset, true);\n },\n put(array, offset, value) {\n dv(array).setBigUint64(offset, value, true);\n return offset + 8;\n }\n};\n/**\n * 64-bit signed integer, Little Endian byte order\n */\nexports.INT64_LE = {\n len: 8,\n get(array, offset) {\n return dv(array).getBigInt64(offset, true);\n },\n put(array, offset, value) {\n dv(array).setBigInt64(offset, value, true);\n return offset + 8;\n }\n};\n/**\n * 64-bit unsigned integer, Big Endian byte order\n */\nexports.UINT64_BE = {\n len: 8,\n get(array, offset) {\n return dv(array).getBigUint64(offset);\n },\n put(array, offset, value) {\n dv(array).setBigUint64(offset, value);\n return offset + 8;\n }\n};\n/**\n * 64-bit signed integer, Big Endian byte order\n */\nexports.INT64_BE = {\n len: 8,\n get(array, offset) {\n return dv(array).getBigInt64(offset);\n },\n put(array, offset, value) {\n dv(array).setBigInt64(offset, value);\n return offset + 8;\n }\n};\n/**\n * IEEE 754 16-bit (half precision) float, big endian\n */\nexports.Float16_BE = {\n len: 2,\n get(dataView, offset) {\n return ieee754.read(dataView, offset, false, 10, this.len);\n },\n put(dataView, offset, value) {\n ieee754.write(dataView, value, offset, false, 10, this.len);\n return offset + this.len;\n }\n};\n/**\n * IEEE 754 16-bit (half precision) float, little endian\n */\nexports.Float16_LE = {\n len: 2,\n get(array, offset) {\n return ieee754.read(array, offset, true, 10, this.len);\n },\n put(array, offset, value) {\n ieee754.write(array, value, offset, true, 10, this.len);\n return offset + this.len;\n }\n};\n/**\n * IEEE 754 32-bit (single precision) float, big endian\n */\nexports.Float32_BE = {\n len: 4,\n get(array, offset) {\n return dv(array).getFloat32(offset);\n },\n put(array, offset, value) {\n dv(array).setFloat32(offset, value);\n return offset + 4;\n }\n};\n/**\n * IEEE 754 32-bit (single precision) float, little endian\n */\nexports.Float32_LE = {\n len: 4,\n get(array, offset) {\n return dv(array).getFloat32(offset, true);\n },\n put(array, offset, value) {\n dv(array).setFloat32(offset, value, true);\n return offset + 4;\n }\n};\n/**\n * IEEE 754 64-bit (double precision) float, big endian\n */\nexports.Float64_BE = {\n len: 8,\n get(array, offset) {\n return dv(array).getFloat64(offset);\n },\n put(array, offset, value) {\n dv(array).setFloat64(offset, value);\n return offset + 8;\n }\n};\n/**\n * IEEE 754 64-bit (double precision) float, little endian\n */\nexports.Float64_LE = {\n len: 8,\n get(array, offset) {\n return dv(array).getFloat64(offset, true);\n },\n put(array, offset, value) {\n dv(array).setFloat64(offset, value, true);\n return offset + 8;\n }\n};\n/**\n * IEEE 754 80-bit (extended precision) float, big endian\n */\nexports.Float80_BE = {\n len: 10,\n get(array, offset) {\n return ieee754.read(array, offset, false, 63, this.len);\n },\n put(array, offset, value) {\n ieee754.write(array, value, offset, false, 63, this.len);\n return offset + this.len;\n }\n};\n/**\n * IEEE 754 80-bit (extended precision) float, little endian\n */\nexports.Float80_LE = {\n len: 10,\n get(array, offset) {\n return ieee754.read(array, offset, true, 63, this.len);\n },\n put(array, offset, value) {\n ieee754.write(array, value, offset, true, 63, this.len);\n return offset + this.len;\n }\n};\n/**\n * Ignore a given number of bytes\n */\nclass IgnoreType {\n /**\n * @param len number of bytes to ignore\n */\n constructor(len) {\n this.len = len;\n }\n // ToDo: don't read, but skip data\n get(array, off) {\n }\n}\nexports.IgnoreType = IgnoreType;\nclass Uint8ArrayType {\n constructor(len) {\n this.len = len;\n }\n get(array, offset) {\n return array.subarray(offset, offset + this.len);\n }\n}\nexports.Uint8ArrayType = Uint8ArrayType;\nclass BufferType {\n constructor(len) {\n this.len = len;\n }\n get(uint8Array, off) {\n return Buffer.from(uint8Array.subarray(off, off + this.len));\n }\n}\nexports.BufferType = BufferType;\n/**\n * Consume a fixed number of bytes from the stream and return a string with a specified encoding.\n */\nclass StringType {\n constructor(len, encoding) {\n this.len = len;\n this.encoding = encoding;\n }\n get(uint8Array, offset) {\n return Buffer.from(uint8Array).toString(this.encoding, offset, offset + this.len);\n }\n}\nexports.StringType = StringType;\n/**\n * ANSI Latin 1 String\n * Using windows-1252 / ISO 8859-1 decoding\n */\nclass AnsiStringType {\n constructor(len) {\n this.len = len;\n }\n static decode(buffer, offset, until) {\n let str = '';\n for (let i = offset; i < until; ++i) {\n str += AnsiStringType.codePointToString(AnsiStringType.singleByteDecoder(buffer[i]));\n }\n return str;\n }\n static inRange(a, min, max) {\n return min <= a && a <= max;\n }\n static codePointToString(cp) {\n if (cp <= 0xFFFF) {\n return String.fromCharCode(cp);\n }\n else {\n cp -= 0x10000;\n return String.fromCharCode((cp >> 10) + 0xD800, (cp & 0x3FF) + 0xDC00);\n }\n }\n static singleByteDecoder(bite) {\n if (AnsiStringType.inRange(bite, 0x00, 0x7F)) {\n return bite;\n }\n const codePoint = AnsiStringType.windows1252[bite - 0x80];\n if (codePoint === null) {\n throw Error('invaliding encoding');\n }\n return codePoint;\n }\n get(buffer, offset = 0) {\n return AnsiStringType.decode(buffer, offset, offset + this.len);\n }\n}\nexports.AnsiStringType = AnsiStringType;\nAnsiStringType.windows1252 = [8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352,\n 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732,\n 8482, 353, 8250, 339, 157, 382, 376, 160, 161, 162, 163, 164, 165, 166, 167, 168,\n 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184,\n 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200,\n 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216,\n 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,\n 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,\n 248, 249, 250, 251, 252, 253, 254, 255];\n","\nexports = module.exports = trim;\n\nfunction trim(str){\n return str.replace(/^\\s*|\\s*$/g, '');\n}\n\nexports.left = function(str){\n return str.replace(/^\\s*/, '');\n};\n\nexports.right = function(str){\n return str.replace(/\\s*$/, '');\n};\n","\r\n\r\n\r\n\r\n;(function(){\r\n\tvar UTIF = {};\r\n\t\r\n\t// Make available for import by `require()`\r\n\tif (typeof module == \"object\") {module.exports = UTIF;}\r\n\telse {self.UTIF = UTIF;}\r\n\t\r\n\tvar pako = (typeof require === \"function\") ? require(\"pako\") : self.pako;\r\n\t\r\n\tfunction log() { if (typeof process==\"undefined\" || process.env.NODE_ENV==\"development\") console.log.apply(console, arguments); }\r\n\t\r\n\t(function(UTIF, pako){\r\n\t\t\r\n\t// Following lines add a JPEG decoder to UTIF.JpegDecoder\r\n\t(function(){\"use strict\";var W=function a1(){function W(p){this.message=\"JPEG error: \"+p}W.prototype=new Error;W.prototype.name=\"JpegError\";W.constructor=W;return W}(),ak=function ag(){var p=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,ac=799,ah=3406,ao=2276,ar=1567,ai=3784,s=5793,ad=2896;function ak(Q){if(Q==null)Q={};if(Q.w==null)Q.w=-1;this.V=Q.n;this.N=Q.w}function a5(Q,h){var f=0,G=[],n,E,a=16,F;while(a>0&&!Q[a-1]){a--}G.push({children:[],index:0});var C=G[0];for(n=0;n0){C=G.pop()}C.index++;G.push(C);while(G.length<=n){G.push(F={children:[],index:0});C.children[C.index]=F.children;C=F}f++}if(n+10){V--;return J>>V&1}J=Q[h++];if(J===255){var I=Q[h++];if(I){if(I===220&&d){h+=2;var l=Z(Q,h);h+=2;if(l>0&&l!==f.s){throw new DNLMarkerError(\"Found DNL marker (0xFFDC) while parsing scan data\",l)}}else if(I===217){if(d){var M=q*8;\r\n\tif(M>0&&M>>7}function u(I){var l=I;while(!0){l=l[Y()];switch(typeof l){case\"number\":return l;case\"object\":continue}throw new W(\"invalid huffman sequence\")}}function m(I){var e=0;while(I>0){e=e<<1|Y();I--}return e}function j(I){if(I===1){return Y()===1?1:-1}var e=m(I);if(e>=1<>4;if(i===0){if(A<15){break}N+=16;continue}N+=A;var o=p[N];X.D[I+o]=j(i);N++}}function $(X,I){var l=u(X.J),M=l===0?0:j(l)<0){r--;return}var N=E,l=a;while(N<=l){var M=u(X.i),S=M&15,i=M>>4;if(S===0){if(i<15){r=m(i)+(1<>4;if(S===0){if(M<15){r=m(M)+(1<0){for(O=0;O0?\"unexpected\":\"excessive\";h=k.offset}if(k.M>=65488&&k.M<=65495){h+=2}else{break}}return h-z}function al(Q,h,f){var G=Q.$,n=Q.D,E,a,C,F,d,T,U,z,J,V,Y,u,m,j,v,$,b;if(!G){throw new W(\"missing required Quantization Table.\")}for(var r=0;r<64;r+=8){J=n[h+r];V=n[h+r+1];Y=n[h+r+2];u=n[h+r+3];m=n[h+r+4];j=n[h+r+5];v=n[h+r+6];$=n[h+r+7];J*=G[r];if((V|Y|u|m|j|v|$)===0){b=s*J+512>>10;f[r]=b;f[r+1]=b;f[r+2]=b;f[r+3]=b;f[r+4]=b;f[r+5]=b;f[r+6]=b;f[r+7]=b;continue}V*=G[r+1];Y*=G[r+2];u*=G[r+3];m*=G[r+4];j*=G[r+5];v*=G[r+6];$*=G[r+7];E=s*J+128>>8;a=s*m+128>>8;C=Y;F=v;d=ad*(V-$)+128>>8;z=ad*(V+$)+128>>8;\r\n\tT=u<<4;U=j<<4;E=E+a+1>>1;a=E-a;b=C*ai+F*ar+128>>8;C=C*ar-F*ai+128>>8;F=b;d=d+U+1>>1;U=d-U;z=z+T+1>>1;T=z-T;E=E+F+1>>1;F=E-F;a=a+C+1>>1;C=a-C;b=d*ao+z*ah+2048>>12;d=d*ah-z*ao+2048>>12;z=b;b=T*ac+U*t+2048>>12;T=T*t-U*ac+2048>>12;U=b;f[r]=E+z;f[r+7]=E-z;f[r+1]=a+U;f[r+6]=a-U;f[r+2]=C+T;f[r+5]=C-T;f[r+3]=F+d;f[r+4]=F-d}for(var P=0;P<8;++P){J=f[P];V=f[P+8];Y=f[P+16];u=f[P+24];m=f[P+32];j=f[P+40];v=f[P+48];$=f[P+56];if((V|Y|u|m|j|v|$)===0){b=s*J+8192>>14;if(b<-2040){b=0}else if(b>=2024){b=255}else{b=b+2056>>4}n[h+P]=b;n[h+P+8]=b;n[h+P+16]=b;n[h+P+24]=b;n[h+P+32]=b;n[h+P+40]=b;n[h+P+48]=b;n[h+P+56]=b;continue}E=s*J+2048>>12;a=s*m+2048>>12;C=Y;F=v;d=ad*(V-$)+2048>>12;z=ad*(V+$)+2048>>12;T=u;U=j;E=(E+a+1>>1)+4112;a=E-a;b=C*ai+F*ar+2048>>12;C=C*ar-F*ai+2048>>12;F=b;d=d+U+1>>1;U=d-U;z=z+T+1>>1;T=z-T;E=E+F+1>>1;F=E-F;a=a+C+1>>1;C=a-C;b=d*ao+z*ah+2048>>12;d=d*ah-z*ao+2048>>12;z=b;\r\n\tb=T*ac+U*t+2048>>12;T=T*t-U*ac+2048>>12;U=b;J=E+z;$=E-z;V=a+U;v=a-U;Y=C+T;j=C-T;u=F+d;m=F-d;if(J<16){J=0}else if(J>=4080){J=255}else{J>>=4}if(V<16){V=0}else if(V>=4080){V=255}else{V>>=4}if(Y<16){Y=0}else if(Y>=4080){Y=255}else{Y>>=4}if(u<16){u=0}else if(u>=4080){u=255}else{u>>=4}if(m<16){m=0}else if(m>=4080){m=255}else{m>>=4}if(j<16){j=0}else if(j>=4080){j=255}else{j>>=4}if(v<16){v=0}else if(v>=4080){v=255}else{v>>=4}if($<16){$=0}else if($>=4080){$=255}else{$>>=4}n[h+P]=J;\r\n\tn[h+P+8]=V;n[h+P+16]=Y;n[h+P+24]=u;n[h+P+32]=m;n[h+P+40]=j;n[h+P+48]=v;n[h+P+56]=$}}function a0(Q,h){var f=h.P,G=h.c,n=new Int16Array(64);for(var E=0;E=G){return null}var E=Z(Q,h);if(E>=65472&&E<=65534){return{u:null,M:E,offset:h}}var a=Z(Q,n);while(!(a>=65472&&a<=65534)){if(++n>=G){return null}a=Z(Q,n)}return{u:E.toString(16),M:a,offset:n}}ak.prototype={parse(Q,h){if(h==null)h={};\r\n\tvar f=h.F,E=0,a=null,C=null,F,d,T=0;function G(){var o=Z(Q,E);E+=2;var B=E+o-2,V=an(Q,B,E);if(V&&V.u){B=V.offset}var ab=Q.subarray(E,B);E+=ab.length;return ab}function n(F){var o=Math.ceil(F.o/8/F.X),B=Math.ceil(F.s/8/F.B);for(var Y=0;Y>4===0){for(u=0;u<64;u++){b=p[u];P[b]=Q[E++]}}else if(r>>4===1){for(u=0;u<64;u++){b=p[u];P[b]=Z(Q,E);E+=2}}else{throw new W(\"DQT - invalid table spec\")}U[r&15]=P}break;case 65472:case 65473:case 65474:if(F){throw new W(\"Only single frame JPEGs supported\")}E+=2;F={};F.G=V===65473;F.Z=V===65474;F.precision=Q[E++];var D=Z(Q,E),a4,q=0,H=0;E+=2;F.s=f||D;F.o=Z(Q,E);E+=2;F.W=[];F._={};var a8=Q[E++];for(Y=0;Y>4,y=Q[E+1]&15;if(q>4===0?J:z)[_&15]=a5(N,K)}break;case 65501:E+=2;d=Z(Q,E);E+=2;break;case 65498:var x=++T===1&&!f,R;E+=2;var k=Q[E++],g=[];for(Y=0;Y>4];R.i=z[a6&15];g.push(R)}var I=Q[E++],l=Q[E++],M=Q[E++];try{var S=a7(Q,E,F,g,d,I,l,M>>4,M&15,x);E+=S}catch(ex){if(ex instanceof DNLMarkerError){return this.parse(Q,{F:ex.s})}else if(ex instanceof EOIMarkerError){break markerLoop}throw ex}break;case 65500:E+=4;break;case 65535:if(Q[E]!==255){E--}break;default:var i=an(Q,E-2,E-3);if(i&&i.u){E=i.offset;break}if(E>=Q.length-1){break markerLoop}throw new W(\"JpegImage.parse - unknown marker: \"+V.toString(16))}V=Z(Q,E);E+=2}this.width=F.o;this.height=F.s;this.g=a;this.b=C;this.W=[];for(Y=0;Y>8)+P[J+1]}}}return v},get f(){if(this.b){return!!this.b.a}if(this.p===3){if(this.N===0){return!1}else if(this.W[0].index===82&&this.W[1].index===71&&this.W[2].index===66){return!1}return!0}if(this.N===1){return!0}return!1},z:function aj(Q){var h,f,G;\r\n\tfor(var n=0,E=Q.length;n4){throw new W(\"Unsupported color mode\")}var E=this.Y(h,f,n);if(this.p===1&&G){var a=E.length,C=new Uint8ClampedArray(a*3),F=0;for(var d=0;d>24}function Z(p,t){return p[t]<<8|p[t+1]}function am(p,t){return(p[t]<<24|p[t+1]<<16|p[t+2]<<8|p[t+3])>>>0}UTIF.JpegDecoder=ak}());\r\n\t\r\n\t//UTIF.JpegDecoder = PDFJS.JpegImage;\r\n\t\r\n\t\r\n\tUTIF.encodeImage = function(rgba, w, h, metadata)\r\n\t{\r\n\t\tvar idf = { \"t256\":[w], \"t257\":[h], \"t258\":[8,8,8,8], \"t259\":[1], \"t262\":[2], \"t273\":[1000], // strips offset\r\n\t\t\t\t\t\"t277\":[4], \"t278\":[h], /* rows per strip */ \"t279\":[w*h*4], // strip byte counts\r\n\t\t\t\t\t\"t282\":[[72,1]], \"t283\":[[72,1]], \"t284\":[1], \"t286\":[[0,1]], \"t287\":[[0,1]], \"t296\":[1], \"t305\": [\"Photopea (UTIF.js)\"], \"t338\":[1]\r\n\t\t\t};\r\n\t\tif (metadata) for (var i in metadata) idf[i] = metadata[i];\r\n\t\t\r\n\t\tvar prfx = new Uint8Array(UTIF.encode([idf]));\r\n\t\tvar img = new Uint8Array(rgba);\r\n\t\tvar data = new Uint8Array(1000+w*h*4);\r\n\t\tfor(var i=0; i probably not an image\r\n\t\timg.isLE = id==\"II\";\r\n\t\timg.width = img[\"t256\"][0]; //delete img[\"t256\"];\r\n\t\timg.height = img[\"t257\"][0]; //delete img[\"t257\"];\r\n\t\r\n\t\tvar cmpr = img[\"t259\"] ? img[\"t259\"][0] : 1; //delete img[\"t259\"];\r\n\t\tvar fo = img[\"t266\"] ? img[\"t266\"][0] : 1; //delete img[\"t266\"];\r\n\t\tif(img[\"t284\"] && img[\"t284\"][0]==2) log(\"PlanarConfiguration 2 should not be used!\");\r\n\t\tif(cmpr==7 && img[\"t258\"] && img[\"t258\"].length>3) img[\"t258\"]=img[\"t258\"].slice(0,3);\r\n\t\r\n\t\tvar bipp; // bits per pixel\r\n\t\tif(img[\"t258\"]) bipp = Math.min(32,img[\"t258\"][0])*img[\"t258\"].length;\r\n\t\telse bipp = (img[\"t277\"]?img[\"t277\"][0]:1); \r\n\t\t// Some .NEF files have t258==14, even though they use 16 bits per pixel\r\n\t\tif(cmpr==1 && img[\"t279\"]!=null && img[\"t278\"] && img[\"t262\"][0]==32803) {\r\n\t\t\tbipp = Math.round((img[\"t279\"][0]*8)/(img.width*img[\"t278\"][0]));\r\n\t\t}\r\n\t\tif(img[\"t50885\"] && img[\"t50885\"][0]==4) bipp = img[\"t258\"][0]*3; // RAW_CANON_40D_SRAW_V103.CR2\r\n\t\tvar bipl = Math.ceil(img.width*bipp/8)*8;\r\n\t\tvar soff = img[\"t273\"]; if(soff==null || img[\"t322\"]) soff = img[\"t324\"];\r\n\t\tvar bcnt = img[\"t279\"]; if(cmpr==1 && soff.length==1) bcnt = [img.height*(bipl>>>3)]; if(bcnt==null || img[\"t322\"]) bcnt = img[\"t325\"];\r\n\t\t//bcnt[0] = Math.min(bcnt[0], data.length); // Hasselblad, \"RAW_HASSELBLAD_H3D39II.3FR\"\r\n\t\tvar bytes = new Uint8Array(img.height*(bipl>>>3)), bilen = 0;\r\n\t\r\n\t\tif(img[\"t322\"]!=null) // tiled\r\n\t\t{\r\n\t\t\tvar tw = img[\"t322\"][0], th = img[\"t323\"][0];\r\n\t\t\tvar tx = Math.floor((img.width + tw - 1) / tw);\r\n\t\t\tvar ty = Math.floor((img.height + th - 1) / th);\r\n\t\t\tvar tbuff = new Uint8Array(Math.ceil(tw*th*bipp/8)|0);\r\n\t\t\tconsole.log(\"====\", tx,ty);\r\n\t\t\tfor(var y=0; y>>3, h = (img[\"t278\"] ? img[\"t278\"][0] : img.height), bpl = Math.ceil(bps*noc*img.width/8);\r\n\t\t\r\n\t\t// convert to Little Endian /*\r\n\t\tif(bps==16 && !img.isLE && img[\"t33422\"]==null) // not DNG\r\n\t\t\tfor(var y=0; y>>8)&255; \r\n\t\t\t\t}\r\n\t\t\t\telse if(noc==3) for(var j= 3; j>>3]>>>7-(P&7)&1;B[1]++;return D}function aj(B,P){if(x==null){x={};\r\n\tfor(var D=0;D>>1}return B}function c(B,P){return B>>P}function N(B,P,D,U,X,y){P[D]=c(c(11*B[X]-4*B[X+y]+B[X+y+y]+4,3)+B[U],1);\r\n\tP[D+y]=c(c(5*B[X]+4*B[X+y]-B[X+y+y]+4,3)-B[U],1)}function g(B,P,D,U,X,y){var n=B[X-y]-B[X+y],S=B[X],O=B[U];\r\n\tP[D]=c(c(n+4,3)+S+O,1);P[D+y]=c(c(-n+4,3)+S-O,1)}function L(B,P,D,U,X,y){P[D]=c(c(5*B[X]+4*B[X-y]-B[X-y-y]+4,3)+B[U],1);\r\n\tP[D+y]=c(c(11*B[X]-4*B[X-y]+B[X-y-y]+4,3)-B[U],1)}function t(B){B=B<0?0:B>4095?4095:B;B=H[B]>>>2;return B}function ab(B,P,D,U,X){U=new Uint16Array(U.buffer);\r\n\tvar y=Date.now(),n=UTIF._binBE,S=P+D,O,q,i,M,m,aA,T,a8,a0,am,au,a3,aw,ao,v,ax,p,k;P+=4;while(P>>1)*(i>>>1));k=new Int16Array((q>>>1)*(i>>>1));u=new Int16Array(1024);\r\n\tfor(var f=0;f<1024;f++){var aF=f-512,j=Math.abs(aF),O=Math.floor(768*j*j*j/(255*255*255))+j;u[f]=Math.sign(aF)*O}H=new Uint16Array(4096);\r\n\tvar al=(1<<16)-1;for(var f=0;f<4096;f++){var ad=f,az=al*(Math.pow(113,ad/4095)-1)/112;H[f]=Math.min(az,al)}}var Z=p[T],V=Q(q,1+d[M]),z=Q(i,1+d[M]);\r\n\tif(M==0){for(var b=0;b>>1)+G]=B[w]<<8|B[w+1]}}else{var aC=[B,P*8],aq=[],a5=0,ae=V*z,I=[0,0],s=0,E=0;\r\n\twhile(a50){aq[a5++]=E;s--}}var $=(M-1)%3,aE=$!=1?V:0,as=$!=0?z:0;\r\n\tfor(var b=0;b>>1)+aE,aa=b*V;for(var G=0;G>>1,an=V*2,at=z*2;\r\n\tfor(var b=0;b>14-r*2&3;var af=a6[aD];if(af!=0)for(var b=0;b>>1)*(q>>>1)+(G>>>1),R=a2[w],ak=ar[w]-2048,aB=ah[w]-2048,av=a1[w]-2048,a4=(ak<<1)+R,a9=(aB<<1)+R,ap=R+av,ag=R-av;\r\n\tU[J]=t(a4);U[J+1]=t(ap);U[J+q]=t(ag);U[J+q+1]=t(a9)}}P+=o*4}else if(C==16388){P+=o*4}else if(F==8192||F==8448||F==9216){}else throw C.toString(16)}}console.log(Date.now()-y)}return ab}()\r\n\t\r\n\tUTIF.decode._decodeLogLuv32 = function(img, data, off, len, tgt, toff) {\r\n\t\tvar w = img.width, qw=w*4;\r\n\t\tvar io = 0, out = new Uint8Array(qw);\r\n\t\t\r\n\t\twhile(io>> (tab[i] >>> 8);\r\n\t\t\t\tfor(var c=0; c>>4); tgt[toff+i+1]=(b0<<4)|(b2>>>4); tgt[toff+i+2]=(b2<<4)|(b1>>>4); }\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tvar pix = new Uint16Array(16);\r\n\t\tvar row, col, val, max, min, imax, imin, sh, bit, i, dp;\r\n\t\t\r\n\t\tvar data = new Uint8Array(raw_width+1);\r\n\t\tfor (row=0; row < height; row++) {\r\n\t\t\t//fread (data, 1, raw_width, ifp);\r\n\t\t\tfor(var j=0; j>> 11);\r\n\t\t\t\timax = 0x0f & (val >>> 22);\r\n\t\t\t\timin = 0x0f & (val >>> 26);\r\n\t\t\t\tfor (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++);\r\n\t\t\t\tfor (bit=30, i=0; i < 16; i++)\r\n\t\t\t\t\tif (i == imax) pix[i] = max;\r\n\t\t\t\t\telse if (i == imin) pix[i] = min;\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tpix[i] = ((bin.readUshort(data, dp+(bit >> 3)) >>> (bit & 7) & 0x7f) << sh) + min;\r\n\t\t\t\t\t\tif (pix[i] > 0x7ff) pix[i] = 0x7ff;\r\n\t\t\t\t\t\tbit += 7;\r\n\t\t\t\t\t}\r\n\t\t\t\tfor (i=0; i < 16; i++, col+=2) {\r\n\t\t\t\t\t//RAW(row,col) = curve[pix[i] << 1] >> 2;\r\n\t\t\t\t\tvar clr = pix[i]<<1; //clr = 0xffff;\r\n\t\t\t\t\tUTIF.decode._putsF(tgt, (row*raw_width+col)*tiff_bps, clr<<(16-tiff_bps));\r\n\t\t\t\t}\r\n\t\t\t\tcol -= col & 1 ? 1:31;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeNikon = function(img,imgs, data, off, src_length, tgt, toff)\r\n\t{\r\n\t\tvar nikon_tree = [\r\n\t [ 0, 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,\t/* 12-bit lossy */\r\n\t\t5,4,3,6,2,7,1,0,8,9,11,10,12 ],\r\n\t [ 0, 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,\t/* 12-bit lossy after split */\r\n\t\t0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 ],\r\n\t [ 0, 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */\r\n\t\t5,4,6,3,7,2,8,1,9,0,10,11,12 ],\r\n\t [ 0, 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0,\t/* 14-bit lossy */\r\n\t\t5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 ],\r\n\t [ 0, 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0,\t/* 14-bit lossy after split */\r\n\t\t8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 ],\r\n\t [ 0, 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0,\t/* 14-bit lossless */\r\n\t\t7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 ] ];\r\n\t\t \r\n\t\tvar raw_width = img[\"t256\"][0], height=img[\"t257\"][0], tiff_bps=img[\"t258\"][0];\r\n\t\t\r\n\t\tvar tree = 0, split = 0;\r\n\t\tvar make_decoder = UTIF.decode._make_decoder;\r\n\t\tvar getbithuff = UTIF.decode._getbithuff;\r\n\t\t\r\n\t\tvar mn = imgs[0].exifIFD.makerNote, md = mn[\"t150\"]?mn[\"t150\"]:mn[\"t140\"], mdo=0; //console.log(mn,md);\r\n\t\t//console.log(md[0].toString(16), md[1].toString(16), tiff_bps);\r\n\t\tvar ver0 = md[mdo++], ver1 = md[mdo++];\r\n\t\tif (ver0 == 0x49 || ver1 == 0x58) mdo+=2110;\r\n\t\tif (ver0 == 0x46) tree = 2;\r\n\t\tif (tiff_bps == 14) tree += 3;\r\n\t\t\r\n\t\tvar vpred = [[0,0],[0,0]], bin=(img.isLE ? UTIF._binLE : UTIF._binBE);\r\n\t\tfor(var i=0; i<2; i++) for(var j=0; j<2; j++) { vpred[i][j] = bin.readShort(md,mdo); mdo+=2; } // not sure here ... [i][j] or [j][i]\r\n\t\t//console.log(vpred);\r\n\t\t\r\n\t\t\r\n\t\tvar max = 1 << tiff_bps & 0x7fff, step=0;\r\n\t\tvar csize = bin.readShort(md,mdo); mdo+=2;\r\n\t\tif (csize > 1) step = Math.floor(max / (csize-1));\r\n\t\tif (ver0 == 0x44 && ver1 == 0x20 && step > 0) split = bin.readShort(md,562);\r\n\t\t\r\n\t\t\r\n\t\tvar i;\r\n\t\tvar row, col;\r\n\t\tvar len, shl, diff;\r\n\t\tvar min_v = 0;\r\n\t\tvar hpred = [0,0];\r\n\t\tvar huff = make_decoder(nikon_tree[tree]);\r\n\t\t\r\n\t\t//var g_input_offset=0, bitbuf=0, vbits=0, reset=0;\r\n\t\tvar prm = [off,0,0,0];\r\n\t\t//console.log(split); split = 170;\r\n\t\t\r\n\t\tfor (min_v=row=0; row < height; row++) {\r\n\t\t\tif (split && row == split) {\r\n\t\t\t\t//free (huff);\r\n\t\t\t\thuff = make_decoder (nikon_tree[tree+1]);\r\n\t\t\t\t//max_v += (min_v = 16) << 1;\r\n\t\t\t}\r\n\t\t\tfor (col=0; col < raw_width; col++) {\r\n\t\t\t\ti = getbithuff(data,prm,huff[0],huff);\r\n\t\t\t\tlen = i & 15;\r\n\t\t\t\tshl = i >>> 4;\r\n\t\t\t\tdiff = (((getbithuff(data,prm,len-shl,0) << 1) + 1) << shl) >>> 1;\r\n\t\t\t\tif ((diff & (1 << (len-1))) == 0)\r\n\t\t\t\t\tdiff -= (1 << len) - (shl==0?1:0);\r\n\t\t\t\tif (col < 2) hpred[col] = vpred[row & 1][col] += diff;\r\n\t\t\t\telse hpred[col & 1] += diff;\r\n\t\t\t\t\r\n\t\t\t\tvar clr = Math.min(Math.max(hpred[col & 1],0),(1<>>3); dt[o]|=val>>>16; dt[o+1]|=val>>>8; dt[o+2]|=val; }\r\n\t\r\n\t\r\n\tUTIF.decode._getbithuff = function(data,prm,nbits, huff) {\r\n\t\tvar zero_after_ff = 0;\r\n\t\tvar get_byte = UTIF.decode._get_byte;\r\n\t\tvar c;\r\n\t \r\n\t\tvar off=prm[0], bitbuf=prm[1], vbits=prm[2], reset=prm[3];\r\n\t\r\n\t\t//if (nbits > 25) return 0;\r\n\t\t//if (nbits < 0) return bitbuf = vbits = reset = 0;\r\n\t\tif (nbits == 0 || vbits < 0) return 0; \r\n\t\twhile (!reset && vbits < nbits && (c = data[off++]) != -1 &&\r\n\t\t\t!(reset = zero_after_ff && c == 0xff && data[off++])) {\r\n\t\t\t//console.log(\"byte read into c\");\r\n\t\t\tbitbuf = (bitbuf << 8) + c;\r\n\t\t\tvbits += 8;\r\n\t\t} \r\n\t\tc = (bitbuf << (32-vbits)) >>> (32-nbits);\r\n\t\tif (huff) {\r\n\t\t\tvbits -= huff[c+1] >>> 8; //console.log(c, huff[c]>>8);\r\n\t\t\tc = huff[c+1]&255;\r\n\t\t} else\r\n\t\t\tvbits -= nbits;\r\n\t\tif (vbits < 0) throw \"e\";\r\n\t \r\n\t\tprm[0]=off; prm[1]=bitbuf; prm[2]=vbits; prm[3]=reset;\r\n\t \r\n\t\treturn c;\r\n\t}\r\n\t\r\n\tUTIF.decode._make_decoder = function(source) {\r\n\t\tvar max, len, h, i, j;\r\n\t\tvar huff = [];\r\n\t\r\n\t\tfor (max=16; max!=0 && !source[max]; max--);\r\n\t\tvar si=17;\r\n\t\t\r\n\t\thuff[0] = max;\r\n\t\tfor (h=len=1; len <= max; len++)\r\n\t\t\tfor (i=0; i < source[len]; i++, ++si)\r\n\t\t\t\tfor (j=0; j < 1 << (max-len); j++)\r\n\t\t\t\t\tif (h <= 1 << max)\r\n\t\t\t\t\t\thuff[h++] = (len << 8) | source[si];\r\n\t\treturn huff;\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff)\r\n\t{\r\n\t\tlen = Math.min(len, data.length-off);\r\n\t\tvar tables = img[\"t347\"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len);\r\n\t\t\r\n\t\tif (tables) {\r\n\t\t\tvar SOI = 216, EOI = 217, boff = 0;\r\n\t\t\tfor (var i=0; i<(tlen-1); i++)\r\n\t\t\t{\r\n\t\t\t\t// Skip EOI marker from JPEGTables\r\n\t\t\t\tif (tables[i]==255 && tables[i+1]==EOI) break;\r\n\t\t\t\tbuff[boff++] = tables[i];\r\n\t\t\t}\r\n\t\r\n\t\t\t// Skip SOI marker from data\r\n\t\t\tvar byte1 = data[off], byte2 = data[off + 1];\r\n\t\t\tif (byte1!=255 || byte2!=SOI)\r\n\t\t\t{\r\n\t\t\t\tbuff[boff++] = byte1;\r\n\t\t\t\tbuff[boff++] = byte2;\r\n\t\t\t}\r\n\t\t\tfor (var i=2; i>>8); }\r\n\t\t\t\telse for(var i=0; i>>8); tgt[toff+(i<<1)+1] = (out[i]&255); }\r\n\t\t\t}\r\n\t\t\telse if(bps==14 || bps==12) { // 4 * 14 == 56 == 7 * 8\r\n\t\t\t\tvar rst = 16-bps;\r\n\t\t\t\tfor(var i=0; i 1);\r\n\t\t}\r\n\t\r\n\t\tif(!isTiled)\r\n\t\t{\r\n\t\t\tif(data[off]==255 && data[off+1]==SOI) return { jpegOffset: off };\r\n\t\t\tif(jpgIchgFmt!=null)\r\n\t\t\t{\r\n\t\t\t\tif(data[off+jifoff]==255 && data[off+jifoff+1]==SOI) joff = off+jifoff;\r\n\t\t\t\telse log(\"JPEGInterchangeFormat does not point to SOI\");\r\n\t\r\n\t\t\t\tif(jpgIchgFmtLen==null) log(\"JPEGInterchangeFormatLength field is missing\");\r\n\t\t\t\telse if(jifoff >= soff || (jifoff+jiflen) <= soff) log(\"JPEGInterchangeFormatLength field value is invalid\");\r\n\t\r\n\t\t\t\tif(joff != null) return { jpegOffset: joff };\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t\tif(ycbcrss!=null) { ssx = ycbcrss[0]; ssy = ycbcrss[1]; }\r\n\t\r\n\t\tif(jpgIchgFmt!=null)\r\n\t\t\tif(jpgIchgFmtLen!=null)\r\n\t\t\t\tif(jiflen >= 2 && (jifoff+jiflen) <= soff)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(data[off+jifoff+jiflen-2]==255 && data[off+jifoff+jiflen-1]==SOI) tables = new Uint8Array(jiflen-2);\r\n\t\t\t\t\telse tables = new Uint8Array(jiflen);\r\n\t\r\n\t\t\t\t\tfor(i=0; i offset to first strip or tile\");\r\n\t\r\n\t\tif(tables == null)\r\n\t\t{\r\n\t\t\tvar ooff = 0, out = [];\r\n\t\t\tout[ooff++] = 255; out[ooff++] = SOI;\r\n\t\r\n\t\t\tvar qtables = img[\"t519\"];\r\n\t\t\tif(qtables==null) throw new Error(\"JPEGQTables tag is missing\");\r\n\t\t\tfor(i=0; i>> 8); out[ooff++] = nc & 255;\r\n\t\t\t\t\tout[ooff++] = (i | (k << 4));\r\n\t\t\t\t\tfor(j=0; j<16; j++) out[ooff++] = data[off+htables[i]+j];\r\n\t\t\t\t\tfor(j=0; j>> 8) & 255; out[ooff++] = img.height & 255;\r\n\t\t\tout[ooff++] = (img.width >>> 8) & 255; out[ooff++] = img.width & 255;\r\n\t\t\tout[ooff++] = spp;\r\n\t\t\tif(spp==1) { out[ooff++] = 1; out[ooff++] = 17; out[ooff++] = 0; }\r\n\t\t\telse for(i=0; i<3; i++)\r\n\t\t\t{\r\n\t\t\t\tout[ooff++] = i + 1;\r\n\t\t\t\tout[ooff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));\r\n\t\t\t\tout[ooff++] = i;\r\n\t\t\t}\r\n\t\r\n\t\t\tif(jpgresint!=null && jpgresint[0]!=0)\r\n\t\t\t{\r\n\t\t\t\tout[ooff++] = 255; out[ooff++] = DRI; out[ooff++] = 0; out[ooff++] = 4;\r\n\t\t\t\tout[ooff++] = (jpgresint[0] >>> 8) & 255;\r\n\t\t\t\tout[ooff++] = jpgresint[0] & 255;\r\n\t\t\t}\r\n\t\r\n\t\t\ttables = new Uint8Array(out);\r\n\t\t}\r\n\t\r\n\t\tvar sofpos = -1;\r\n\t\ti = 0;\r\n\t\twhile(i < (tables.length - 1)) {\r\n\t\t\tif(tables[i]==255 && tables[i+1]==SOF0) { sofpos = i; break; }\r\n\t\t\ti++;\r\n\t\t}\r\n\t\r\n\t\tif(sofpos == -1)\r\n\t\t{\r\n\t\t\tvar tmptab = new Uint8Array(tables.length + 10 + 3*spp);\r\n\t\t\ttmptab.set(tables);\r\n\t\t\tvar tmpoff = tables.length;\r\n\t\t\tsofpos = tables.length;\r\n\t\t\ttables = tmptab;\r\n\t\r\n\t\t\ttables[tmpoff++] = 255; tables[tmpoff++] = SOF0;\r\n\t\t\ttables[tmpoff++] = 0; tables[tmpoff++] = 8 + 3*spp; tables[tmpoff++] = 8;\r\n\t\t\ttables[tmpoff++] = (img.height >>> 8) & 255; tables[tmpoff++] = img.height & 255;\r\n\t\t\ttables[tmpoff++] = (img.width >>> 8) & 255; tables[tmpoff++] = img.width & 255;\r\n\t\t\ttables[tmpoff++] = spp;\r\n\t\t\tif(spp==1) { tables[tmpoff++] = 1; tables[tmpoff++] = 17; tables[tmpoff++] = 0; }\r\n\t\t\telse for(i=0; i<3; i++)\r\n\t\t\t{\r\n\t\t\t\ttables[tmpoff++] = i + 1;\r\n\t\t\t\ttables[tmpoff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));\r\n\t\t\t\ttables[tmpoff++] = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t\tif(data[soff]==255 && data[soff+1]==SOS)\r\n\t\t{\r\n\t\t\tvar soslen = (data[soff+2]<<8) | data[soff+3];\r\n\t\t\tsosMarker = new Uint8Array(soslen+2);\r\n\t\t\tsosMarker[0] = data[soff]; sosMarker[1] = data[soff+1]; sosMarker[2] = data[soff+2]; sosMarker[3] = data[soff+3];\r\n\t\t\tfor(i=0; i<(soslen-2); i++) sosMarker[i+4] = data[soff+i+4];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsosMarker = new Uint8Array(2 + 6 + 2*spp);\r\n\t\t\tvar sosoff = 0;\r\n\t\t\tsosMarker[sosoff++] = 255; sosMarker[sosoff++] = SOS;\r\n\t\t\tsosMarker[sosoff++] = 0; sosMarker[sosoff++] = 6 + 2*spp; sosMarker[sosoff++] = spp;\r\n\t\t\tif(spp==1) { sosMarker[sosoff++] = 1; sosMarker[sosoff++] = 0; }\r\n\t\t\telse for(i=0; i<3; i++)\r\n\t\t\t{\r\n\t\t\t\tsosMarker[sosoff++] = i+1; sosMarker[sosoff++] = (i << 4) | i;\r\n\t\t\t}\r\n\t\t\tsosMarker[sosoff++] = 0; sosMarker[sosoff++] = 63; sosMarker[sosoff++] = 0;\r\n\t\t}\r\n\t\r\n\t\treturn { jpegOffset: off, tables: tables, sosMarker: sosMarker, sofPosition: sofpos };\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff)\r\n\t{\r\n\t\tvar i, dlen, tlen, buff, buffoff;\r\n\t\tvar jpegData = UTIF.decode._decodeOldJPEGInit(img, data, off, len);\r\n\t\r\n\t\tif(jpegData.jpegOffset!=null)\r\n\t\t{\r\n\t\t\tdlen = off+len-jpegData.jpegOffset;\r\n\t\t\tbuff = new Uint8Array(dlen);\r\n\t\t\tfor(i=0; i>> 8) & 255; buff[jpegData.sofPosition+6] = img.height & 255;\r\n\t\t\tbuff[jpegData.sofPosition+7] = (img.width >>> 8) & 255; buff[jpegData.sofPosition+8] = img.width & 255;\r\n\t\r\n\t\t\tif(data[off]!=255 || data[off+1]!=SOS)\r\n\t\t\t{\r\n\t\t\t\tbuff.set(jpegData.sosMarker, buffoff);\r\n\t\t\t\tbuffoff += sosMarker.length;\r\n\t\t\t}\r\n\t\t\tfor(i=0; i=0 && n<128) for(var i=0; i< n+1; i++) { ta[toff]=sa[off]; toff++; off++; }\r\n\t\t\tif(n>=-127 && n<0) { for(var i=0; i<-n+1; i++) { ta[toff]=sa[off]; toff++; } off++; }\r\n\t\t}\r\n\t\treturn toff;\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeThunder = function(data, off, len, tgt, toff)\r\n\t{\r\n\t\tvar d2 = [ 0, 1, 0, -1 ], d3 = [ 0, 1, 2, 3, 0, -3, -2, -1 ];\r\n\t\tvar lim = off+len, qoff = toff*2, px = 0;\r\n\t\twhile(off>>6), n = (b&63); off++;\r\n\t\t\tif(msk==3) { px=(n&15); tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; }\r\n\t\t\tif(msk==0) for(var i=0; i>>1] |= (px<<(4*(1-qoff&1))); qoff++; }\r\n\t\t\tif(msk==2) for(var i=0; i<2; i++) { var d=(n>>>(3*(1-i)))&7; if(d!=4) { px+=d3[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }\r\n\t\t\tif(msk==1) for(var i=0; i<3; i++) { var d=(n>>>(2*(2-i)))&3; if(d!=2) { px+=d2[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }\r\n\t\t}\r\n\t}\r\n\t\r\n\tUTIF.decode._dmap = { \"1\":0,\"011\":1,\"000011\":2,\"0000011\":3, \"010\":-1,\"000010\":-2,\"0000010\":-3 };\r\n\tUTIF.decode._lens = ( function()\r\n\t{\r\n\t\tvar addKeys = function(lens, arr, i0, inc) { for(var i=0; i>>3)>>3]>>>(7-(boff&7)))&1;\r\n\t\t\tif(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;\r\n\t\t\tboff++; wrd+=bit;\r\n\t\t\tif(mode==\"H\")\r\n\t\t\t{\r\n\t\t\t\tif(U._lens[clr][wrd]!=null)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar dl=U._lens[clr][wrd]; wrd=\"\"; len+=dl;\r\n\t\t\t\t\tif(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=\"\"; }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(wrd==\"0001\") { wrd=\"\"; U._addNtimes(line,b2-a0,clr); a0=b2; }\r\n\t\t\t\tif(wrd==\"001\" ) { wrd=\"\"; mode=\"H\"; toRead=2; }\r\n\t\t\t\tif(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=\"\"; clr=1-clr; }\r\n\t\t\t}\r\n\t\t\tif(line.length==w && mode==\"\")\r\n\t\t\t{\r\n\t\t\t\tU._writeBits(line, tgt, toff*8+y*bipl);\r\n\t\t\t\tclr=0; y++; a0=0;\r\n\t\t\t\tpline=U._makeDiff(line); line=[];\r\n\t\t\t}\r\n\t\t\t//if(wrd.length>150) { log(wrd); break; throw \"e\"; }\r\n\t\t}\r\n\t}\r\n\t\r\n\tUTIF.decode._findDiff = function(line, x, clr) { for(var i=0; i=x && line[i+1]==clr) return line[i]; }\r\n\t\r\n\tUTIF.decode._makeDiff = function(line)\r\n\t{\r\n\t\tvar out = []; if(line[0]==1) out.push(0,1);\r\n\t\tfor(var i=1; i>>3)>>3]>>>(7-(boff&7)))&1;\r\n\t\t\tif(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;\r\n\t\t\tboff++; wrd+=bit;\r\n\t\t\t\r\n\t\t\tlen = U._lens[clr][wrd];\r\n\t\t\tif(len!=null) {\r\n\t\t\t\tU._addNtimes(line,len,clr); wrd=\"\";\r\n\t\t\t\tif(len<64) clr = 1-clr; \r\n\t\t\t\tif(line.length==w) { U._writeBits(line, tgt, toff*8+y*bipl); line=[]; y++; clr=0; if((boff&7)!=0) boff+=8-(boff&7); if(len>=64) boff+=8; }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeG3 = function(data, off, slen, tgt, toff, w, fo, twoDim)\r\n\t{\r\n\t\tvar U = UTIF.decode, boff=off<<3, len=0, wrd=\"\";\r\n\t\tvar line=[], pline=[]; for(var i=0; i>>3)>>3]>>>(7-(boff&7)))&1;\r\n\t\t\tif(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;\r\n\t\t\tboff++; wrd+=bit;\r\n\t\r\n\t\t\tif(is1D)\r\n\t\t\t{\r\n\t\t\t\tif(U._lens[clr][wrd]!=null)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar dl=U._lens[clr][wrd]; wrd=\"\"; len+=dl;\r\n\t\t\t\t\tif(dl<64) { U._addNtimes(line,len,clr); clr=1-clr; len=0; }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(mode==\"H\")\r\n\t\t\t\t{\r\n\t\t\t\t\tif(U._lens[clr][wrd]!=null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar dl=U._lens[clr][wrd]; wrd=\"\"; len+=dl;\r\n\t\t\t\t\t\tif(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=\"\"; }\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif(wrd==\"0001\") { wrd=\"\"; U._addNtimes(line,b2-a0,clr); a0=b2; }\r\n\t\t\t\t\tif(wrd==\"001\" ) { wrd=\"\"; mode=\"H\"; toRead=2; }\r\n\t\t\t\t\tif(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=\"\"; clr=1-clr; }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(wrd.endsWith(\"000000000001\")) // needed for some files\r\n\t\t\t{\r\n\t\t\t\tif(y>=0) U._writeBits(line, tgt, toff*8+y*bipl);\r\n\t\t\t\tif(twoDim) {\r\n\t\t\t\t\tif(fo==1) is1D = ((data[boff>>>3]>>>(7-(boff&7)))&1)==1;\r\n\t\t\t\t\tif(fo==2) is1D = ((data[boff>>>3]>>>( (boff&7)))&1)==1;\r\n\t\t\t\t\tboff++;\r\n\t\t\t\t}\r\n\t\t\t\t//log(\"EOL\",y, \"next 1D:\", is1D);\r\n\t\t\t\twrd=\"\"; clr=0; y++; a0=0;\r\n\t\t\t\tpline=U._makeDiff(line); line=[];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(line.length==w) U._writeBits(line, tgt, toff*8+y*bipl);\r\n\t}\r\n\t\r\n\tUTIF.decode._addNtimes = function(arr, n, val) { for(var i=0; i>>3] |= (bits[i]<<(7-((boff+i)&7)));\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeLZW=UTIF.decode._decodeLZW=function(){var e,U,Z,u,K=0,V=0,g=0,N=0,O=function(){var S=e>>>3,A=U[S]<<16|U[S+1]<<8|U[S+2],j=A>>>24-(e&7)-V&(1<>>----------------\");\r\n\t\tfor(var i=0; i4) { bin.writeUint(data, offset, eoff); toff=eoff; }\r\n\t\r\n\t\t\tif (type== 1 || type==7) { for(var i=0; i4) { dlen += (dlen&1); eoff += dlen; }\r\n\t\t\toffset += 4;\r\n\t\t}\r\n\t\treturn [offset, eoff];\r\n\t}\r\n\t\r\n\tUTIF.toRGBA8 = function(out, scl)\r\n\t{\r\n\t\tvar w = out.width, h = out.height, area = w*h, qarea = area*4, data = out.data;\r\n\t\tvar img = new Uint8Array(area*4);\r\n\t\t//console.log(out);\r\n\t\t// 0: WhiteIsZero, 1: BlackIsZero, 2: RGB, 3: Palette color, 4: Transparency mask, 5: CMYK\r\n\t\tvar intp = (out[\"t262\"] ? out[\"t262\"][0]: 2), bps = (out[\"t258\"]?Math.min(32,out[\"t258\"][0]):1);\r\n\t\tif(out[\"t262\"]==null && bps==1) intp=0;\r\n\t\t//log(\"interpretation: \", intp, \"bps\", bps, out);\r\n\t\t\r\n\t\tif(false) {}\r\n\t\telse if(intp==0)\r\n\t\t{\r\n\t\t\tvar bpl = Math.ceil(bps*w/8);\r\n\t\t\tfor(var y=0; y>3)])>>(7- (i&7)))& 1; img[qi]=img[qi+1]=img[qi+2]=( 1-px)*255; img[qi+3]=255; }\r\n\t\t\t\tif(bps== 4) for(var i=0; i>1)])>>(4-4*(i&1)))&15; img[qi]=img[qi+1]=img[qi+2]=(15-px)* 17; img[qi+3]=255; }\r\n\t\t\t\tif(bps== 8) for(var i=0; i>3)])>>(7- (i&7)))&1; img[qi]=img[qi+1]=img[qi+2]=(px)*255; img[qi+3]=255; }\r\n\t\t\t\tif(bps== 2) for(var i=0; i>2)])>>(6-2*(i&3)))&3; img[qi]=img[qi+1]=img[qi+2]=(px)* 85; img[qi+3]=255; }\r\n\t\t\t\tif(bps== 8) for(var i=0; i>>3)]>>>(7-(x&7)))&1;\r\n\t\t\t\t\telse if(bps==2) mi=(data[dof+(x>>>2)]>>>(6-2*(x&3)))&3;\r\n\t\t\t\t\telse if(bps==4) mi=(data[dof+(x>>>1)]>>>(4-4*(x&1)))&15;\r\n\t\t\t\t\telse if(bps==8) mi= data[dof+x*smpls]; \r\n\t\t\t\t\telse throw bps;\r\n\t\t\t\t\timg[qi]=(map[mi]>>8); img[qi+1]=(map[cn+mi]>>8); img[qi+2]=(map[cn+cn+mi]>>8); img[qi+3]=255; \r\n\t\t\t\t}\r\n\t\t}\r\n\t\telse if(intp==5) \r\n\t\t{\r\n\t\t\tvar smpls = out[\"t258\"]?out[\"t258\"].length : 4;\r\n\t\t\tvar gotAlpha = smpls>4 ? 1 : 0;\r\n\t\t\tfor(var i=0; i>>1);\r\n\t\t\t\t\tvar Y = data[si+(j&1)], Cb=data[si+2]-128, Cr=data[si+3]-128;\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar r = Y + ( (Cr >> 2) + (Cr >> 3) + (Cr >> 5) ) ;\r\n\t\t\t\t\tvar g = Y - ( (Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ( (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5)) ;\r\n\t\t\t\t\tvar b = Y + ( Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)) ;\r\n\t\t\t\t\t\r\n\t\t\t\t\timg[qi ]=Math.max(0,Math.min(255,r));\r\n\t\t\t\t\timg[qi+1]=Math.max(0,Math.min(255,g));\r\n\t\t\t\t\timg[qi+2]=Math.max(0,Math.min(255,b));\r\n\t\t\t\t\timg[qi+3]=255;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(intp==32845) {\r\n\t\t\t\r\n\t\t\tfunction gamma(x) { return x < 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1.0 / 2.4) - 0.055; }\r\n\t\t\t\r\n\t\t\tfor(var y=0; yma) { ma=ar; page=img; }\r\n\t\t}\r\n\t\tUTIF.decodeImage(buff, page, ifds);\r\n\t\tvar rgba = UTIF.toRGBA8(page), w=page.width, h=page.height;\r\n\t\t\r\n\t\tvar cnv = document.createElement(\"canvas\"); cnv.width=w; cnv.height=h;\r\n\t\tvar ctx = cnv.getContext(\"2d\");\r\n\t\tvar imgd = new ImageData(new Uint8ClampedArray(rgba.buffer),w,h);\r\n\t\tctx.putImageData(imgd,0,0);\r\n\t\treturn cnv.toDataURL();\r\n\t}\r\n\t\r\n\t\r\n\tUTIF._binBE =\r\n\t{\r\n\t\tnextZero : function(data, o) { while(data[o]!=0) o++; return o; },\r\n\t\treadUshort : function(buff, p) { return (buff[p]<< 8) | buff[p+1]; },\r\n\t\treadShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+1]; a[1]=buff[p+0]; return UTIF._binBE. i16[0]; },\r\n\t\treadInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE. i32[0]; },\r\n\t\treadUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE.ui32[0]; },\r\n\t\treadASCII : function(buff, p, l) { var s = \"\"; for(var i=0; i> 8)&255; buff[p+1] = n&255; },\r\n\t\twriteInt : function(buff, p, n) { var a=UTIF._binBE.ui8; UTIF._binBE.i32[0]=n; buff[p+3]=a[0]; buff[p+2]=a[1]; buff[p+1]=a[2]; buff[p+0]=a[3]; },\r\n\t\twriteUint : function(buff, p, n) { buff[p] = (n>>24)&255; buff[p+1] = (n>>16)&255; buff[p+2] = (n>>8)&255; buff[p+3] = (n>>0)&255; },\r\n\t\twriteASCII : function(buff, p, s) { for(var i = 0; i < s.length; i++) buff[p+i] = s.charCodeAt(i); },\r\n\t\twriteDouble: function(buff, p, n)\r\n\t\t{\r\n\t\t\tUTIF._binBE.fl64[0] = n;\r\n\t\t\tfor (var i = 0; i < 8; i++) buff[p + i] = UTIF._binBE.ui8[7 - i];\r\n\t\t}\r\n\t}\r\n\tUTIF._binBE.ui8 = new Uint8Array (8);\r\n\tUTIF._binBE.i16 = new Int16Array (UTIF._binBE.ui8.buffer);\r\n\tUTIF._binBE.i32 = new Int32Array (UTIF._binBE.ui8.buffer);\r\n\tUTIF._binBE.ui32 = new Uint32Array (UTIF._binBE.ui8.buffer);\r\n\tUTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer);\r\n\tUTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer);\r\n\t\r\n\tUTIF._binLE =\r\n\t{\r\n\t\tnextZero : UTIF._binBE.nextZero,\r\n\t\treadUshort : function(buff, p) { return (buff[p+1]<< 8) | buff[p]; },\r\n\t\treadShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; return UTIF._binBE. i16[0]; },\r\n\t\treadInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE. i32[0]; },\r\n\t\treadUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE.ui32[0]; },\r\n\t\treadASCII : UTIF._binBE.readASCII,\r\n\t\treadFloat : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<4;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl32[0]; },\r\n\t\treadDouble : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<8;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl64[0]; },\r\n\t\t\r\n\t\twriteUshort: function(buff, p, n) { buff[p] = (n)&255; buff[p+1] = (n>>8)&255; },\r\n\t\twriteInt : function(buff, p, n) { var a=UTIF._binBE.ui8; UTIF._binBE.i32[0]=n; buff[p+0]=a[0]; buff[p+1]=a[1]; buff[p+2]=a[2]; buff[p+3]=a[3]; },\r\n\t\twriteUint : function(buff, p, n) { buff[p] = (n>>>0)&255; buff[p+1] = (n>>>8)&255; buff[p+2] = (n>>>16)&255; buff[p+3] = (n>>>24)&255; },\r\n\t\twriteASCII : UTIF._binBE.writeASCII\r\n\t}\r\n\tUTIF._copyTile = function(tb, tw, th, b, w, h, xoff, yoff)\r\n\t{\r\n\t\t//log(\"copyTile\", tw, th, w, h, xoff, yoff);\r\n\t\tvar xlim = Math.min(tw, w-xoff);\r\n\t\tvar ylim = Math.min(th, h-yoff);\r\n\t\tfor(var y=0; y>--r&1;\r\n\tX=g[X+y]}w[t]=X}}function P(l,A,g,K){if(l[A+3]!=255)return 0;if(g==0)return A;for(var t=0;t<2;t++){if(l[A+t]==0){l[A+t]=l.length;\r\n\tl.push(0,0,K,255)}var F=P(l,l[A+t],g-1,K+1);if(F!=0)return F}return 0}function f(l){var A=l.b,g=l.a;\r\n\twhile(A<25&&l.e>>8;g=g<<8|K;A+=8}if(A<0)throw\"e\";l.b=A;l.a=g}function O(l,A){if(A.b>(A.b-=l)&65535>>16-l}function B(l,A){var g=l[0],K=0,t=255,F=0;if(A.b<16)f(A);var $=A.a>>A.b-8&255;\r\n\tK=l[1][$];t=g[K+3];A.b-=g[K+2];while(t==255){F=A.a>>--A.b&1;K=g[K+F];t=g[K+3]}return t}function D(l,A){if(l<32768>>16-A)l+=-(1<>4,q&15]}}else if(M==65476){var m=_+X-2;while(_>>4];t[i[0]]=i.slice(1)}g=u();_+=2;break}else{_+=X-2}}var T=K>8?Uint16Array:Uint8Array,Y=new T(w*r*L),d={b:0,a:0,c:g==8,e:_,data:o,d:o.length};\r\n\tif(d.c)b(Y,r*L,d,$[0],w);else{var v=[],Q=0,C=0;for(var y=0;yQ)Q=s;\r\n\tif(H>C)C=H;v.push(s*H)}if(Q!=1||C!=1){var E=[],c=0;for(var y=0;y>>1);else if(A==6)S=l[n]+(m-l[n-L]>>>1);else if(A==7)S=m+l[n]>>>1;else throw A;\r\n\tl[q]+=S}}}}return x}();\r\n\t\r\n\t\r\n\t(function(){var G=0,F=1,i=2,b=3,J=4,N=5,E=6,s=7,c=8,T=9,a3=10,f=11,q=12,M=13,m=14,x=15,L=16,$=17,p=18;\r\n\tfunction a5(t){var Z=UTIF._binBE.readUshort,u={b:Z(t,0),i:t[2],C:t[3],u:t[4],q:Z(t,5),k:Z(t,7),e:Z(t,9),l:Z(t,11),s:t[13],d:Z(t,14)};\r\n\tif(u.b!=18771||u.i>1||u.q<6||u.q%6||u.e<768||u.e%24||u.l!=768||u.k=u.l||u.s>16||u.s!=u.k/u.l||u.s!=Math.ceil(u.e/u.l)||u.d!=u.q/6||u.u!=12&&u.u!=14&&u.u!=16||u.C!=16&&u.C!=0){throw\"Invalid data\"}if(u.i==0){throw\"Not implemented. We need this file!\"}u.h=u.C==16;\r\n\tu.m=(u.h?u.l*2/3:u.l>>>1)|0;u.A=u.m+2;u.f=64;u.g=(1<>>6);for(var e=0;e<3;e++){for(var Q=0;\r\n\tQ<41;Q++){Z[e][Q]=[u,1]}}return Z}function a4(t){for(var Z=-1,u=0;!u;Z++){u=t[t.j]>>>7-t.a&1;t.a++;t.a&=7;\r\n\tif(!t.a)t.j++}return Z}function K(t,Z){var u=0,e=8-t.a,Q=t.j,V=t.a;if(Z){if(Z>=e){do{u<<=e;Z-=e;u|=t[t.j]&(1<=8)}if(Z){u<<=Z;e-=Z;u|=t[t.j]>>>e&(1<n&&C>>2;if(o){w[X]=h;return}l=Z.t*Z.c[t.g+Y-H]+Z.c[t.g+g-Y]}else{h=Y>g&&Y>P||Y>>2:A+v>>>1;\r\n\tl=Z.t*Z.c[t.g+Y-g]+Z.c[t.g+g-A]}R=y(l);var W=a4(u);if(W>>1):a>>>1;\r\n\tO[R][0]+=y(a);if(O[R][1]==t.f){O[R][0]>>>=1;O[R][1]>>>=1}O[R][1]++;h=l<0?h-a:h+a;if(t.i){if(h<0)h+=Z.w;\r\n\telse if(h>t.g)h-=Z.w}w[X]=h>=0?Math.min(h,t.g):0}function U(t,Z,u){var e=t[0].length;for(var Q=Z;Q<=u;\r\n\tQ++){t[Q][0]=t[Q-1][1];t[Q][e-1]=t[Q-1][e-2]}}function B(t){U(t,s,q);U(t,i,J);U(t,x,$)}function _(t,Z,u,e,Q,V,O,o,X,k,j,I,a){var l=0,R=1,w=QJ;\r\n\twhile(R8){r(t,Z,u,e,Q,R,o[X]);r(t,Z,u,e,V,R,o[X]);R+=2}}B(e)}function a8(t,Z,u,e,Q,V){_(t,Z,u,e,i,s,Q,V,0,0,1,0,8);\r\n\t_(t,Z,u,e,c,x,Q,V,1,0,1,0,8);_(t,Z,u,e,b,T,Q,V,2,1,0,3,0);_(t,Z,u,e,a3,L,Q,V,0,0,0,3,2);_(t,Z,u,e,J,f,Q,V,1,0,0,3,2);\r\n\t_(t,Z,u,e,q,$,Q,V,2,1,0,3,0)}function a9(t,Z,u,e,Q,V){var O=V.length,o=t.l;if(Q+1==t.s)o=t.e-Q*t.l;var X=6*t.e*e+Q*t.l;\r\n\tfor(var k=0;k<6;k++){for(var j=0;j>>1)}else if(I==2){a=x+(k>>>1)}else{a=s+k}var l=t.h?(j*2/3&2147483646|j%3&1)+(j%3>>>1):j>>>1;\r\n\tZ[X+j]=u[a][l+1]}X+=t.e}}UTIF._decompressRAF=function(t,Z){var u=a5(t),e=a7(t,u),Q=a2(u),V=new Int16Array(u.e*u.q);\r\n\tif(Z==null){Z=u.h?[[1,1,0,1,1,2],[1,1,2,1,1,0],[2,0,1,0,2,1],[1,1,2,1,1,0],[1,1,0,1,1,2],[0,2,1,2,0,1]]:[[0,1],[3,2]]}var O=[[G,b],[F,J],[N,f],[E,q],[M,L],[m,$]],o=[];\r\n\tfor(var X=0;X -1\n }\n}\n\nfunction normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {\n throw new TypeError('Invalid character in header field name: \"' + name + '\"')\n }\n return name.toLowerCase()\n}\n\nfunction normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n}\n\n// Build a destructive iterator for the value list\nfunction iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n\n return iterator\n}\n\nexport function Headers(headers) {\n this.map = {}\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1])\n }, this)\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n}\n\nHeaders.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue + ', ' + value : value\n}\n\nHeaders.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n}\n\nHeaders.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n}\n\nHeaders.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n}\n\nHeaders.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n}\n\nHeaders.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n}\n\nHeaders.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push(name)\n })\n return iteratorFor(items)\n}\n\nHeaders.prototype.values = function() {\n var items = []\n this.forEach(function(value) {\n items.push(value)\n })\n return iteratorFor(items)\n}\n\nHeaders.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push([name, value])\n })\n return iteratorFor(items)\n}\n\nif (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n}\n\nfunction consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n}\n\nfunction fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n}\n\nfunction readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n}\n\nfunction readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsText(blob)\n return promise\n}\n\nfunction readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n}\n\nfunction bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n}\n\nfunction Body() {\n this.bodyUsed = false\n\n this._initBody = function(body) {\n /*\n fetch-mock wraps the Response object in an ES6 Proxy to\n provide useful test harness features such as flush. However, on\n ES5 browsers without fetch or Proxy support pollyfills must be used;\n the proxy-pollyfill is unable to proxy an attribute unless it exists\n on the object before the Proxy is created. This change ensures\n Response.bodyUsed exists on the instance, while maintaining the\n semantic of setting Request.bodyUsed in the constructor before\n _initBody is called.\n */\n this.bodyUsed = this.bodyUsed\n this._bodyInit = body\n if (!body) {\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n this._bodyText = body = Object.prototype.toString.call(body)\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n var isConsumed = consumed(this)\n if (isConsumed) {\n return isConsumed\n }\n if (ArrayBuffer.isView(this._bodyArrayBuffer)) {\n return Promise.resolve(\n this._bodyArrayBuffer.buffer.slice(\n this._bodyArrayBuffer.byteOffset,\n this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength\n )\n )\n } else {\n return Promise.resolve(this._bodyArrayBuffer)\n }\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n }\n }\n\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n\n return this\n}\n\n// HTTP methods whose capitalization should be normalized\nvar methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']\n\nfunction normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return methods.indexOf(upcased) > -1 ? upcased : method\n}\n\nexport function Request(input, options) {\n if (!(this instanceof Request)) {\n throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n }\n\n options = options || {}\n var body = options.body\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n this.signal = input.signal\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n } else {\n this.url = String(input)\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.signal = options.signal || this.signal\n this.referrer = null\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n\n if (this.method === 'GET' || this.method === 'HEAD') {\n if (options.cache === 'no-store' || options.cache === 'no-cache') {\n // Search for a '_' parameter in the query string\n var reParamSearch = /([?&])_=[^&]*/\n if (reParamSearch.test(this.url)) {\n // If it already exists then set the value with the current time\n this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime())\n } else {\n // Otherwise add a new '_' parameter to the end with the current time\n var reQueryString = /\\?/\n this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime()\n }\n }\n }\n}\n\nRequest.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n}\n\nfunction decode(body) {\n var form = new FormData()\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n}\n\nfunction parseHeaders(rawHeaders) {\n var headers = new Headers()\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ')\n // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill\n // https://github.com/github/fetch/issues/748\n // https://github.com/zloirock/core-js/issues/751\n preProcessedHeaders\n .split('\\r')\n .map(function(header) {\n return header.indexOf('\\n') === 0 ? header.substr(1, header.length) : header\n })\n .forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n headers.append(key, value)\n }\n })\n return headers\n}\n\nBody.call(Request.prototype)\n\nexport function Response(bodyInit, options) {\n if (!(this instanceof Response)) {\n throw new TypeError('Please use the \"new\" operator, this DOM object constructor cannot be called as a function.')\n }\n if (!options) {\n options = {}\n }\n\n this.type = 'default'\n this.status = options.status === undefined ? 200 : options.status\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = options.statusText === undefined ? '' : '' + options.statusText\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n}\n\nBody.call(Response.prototype)\n\nResponse.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n}\n\nResponse.error = function() {\n var response = new Response(null, {status: 0, statusText: ''})\n response.type = 'error'\n return response\n}\n\nvar redirectStatuses = [301, 302, 303, 307, 308]\n\nResponse.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n}\n\nexport var DOMException = global.DOMException\ntry {\n new DOMException()\n} catch (err) {\n DOMException = function(message, name) {\n this.message = message\n this.name = name\n var error = Error(message)\n this.stack = error.stack\n }\n DOMException.prototype = Object.create(Error.prototype)\n DOMException.prototype.constructor = DOMException\n}\n\nexport function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n\n if (request.signal && request.signal.aborted) {\n return reject(new DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest()\n\n function abortXhr() {\n xhr.abort()\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n setTimeout(function() {\n resolve(new Response(body, options))\n }, 0)\n }\n\n xhr.onerror = function() {\n setTimeout(function() {\n reject(new TypeError('Network request failed'))\n }, 0)\n }\n\n xhr.ontimeout = function() {\n setTimeout(function() {\n reject(new TypeError('Network request failed'))\n }, 0)\n }\n\n xhr.onabort = function() {\n setTimeout(function() {\n reject(new DOMException('Aborted', 'AbortError'))\n }, 0)\n }\n\n function fixUrl(url) {\n try {\n return url === '' && global.location.href ? global.location.href : url\n } catch (e) {\n return url\n }\n }\n\n xhr.open(request.method, fixUrl(request.url), true)\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false\n }\n\n if ('responseType' in xhr) {\n if (support.blob) {\n xhr.responseType = 'blob'\n } else if (\n support.arrayBuffer &&\n request.headers.get('Content-Type') &&\n request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1\n ) {\n xhr.responseType = 'arraybuffer'\n }\n }\n\n if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) {\n Object.getOwnPropertyNames(init.headers).forEach(function(name) {\n xhr.setRequestHeader(name, normalizeValue(init.headers[name]))\n })\n } else {\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n }\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr)\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr)\n }\n }\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n}\n\nfetch.polyfill = true\n\nif (!global.fetch) {\n global.fetch = fetch\n global.Headers = Headers\n global.Request = Request\n global.Response = Response\n}\n","\"use strict\";\nvar window = require(\"global/window\")\nvar isFunction = require(\"is-function\")\nvar parseHeaders = require(\"parse-headers\")\nvar xtend = require(\"xtend\")\n\nmodule.exports = createXHR\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = createXHR;\ncreateXHR.XMLHttpRequest = window.XMLHttpRequest || noop\ncreateXHR.XDomainRequest = \"withCredentials\" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest\n\nforEachArray([\"get\", \"put\", \"post\", \"patch\", \"head\", \"delete\"], function(method) {\n createXHR[method === \"delete\" ? \"del\" : method] = function(uri, options, callback) {\n options = initParams(uri, options, callback)\n options.method = method.toUpperCase()\n return _createXHR(options)\n }\n})\n\nfunction forEachArray(array, iterator) {\n for (var i = 0; i < array.length; i++) {\n iterator(array[i])\n }\n}\n\nfunction isEmpty(obj){\n for(var i in obj){\n if(obj.hasOwnProperty(i)) return false\n }\n return true\n}\n\nfunction initParams(uri, options, callback) {\n var params = uri\n\n if (isFunction(options)) {\n callback = options\n if (typeof uri === \"string\") {\n params = {uri:uri}\n }\n } else {\n params = xtend(options, {uri: uri})\n }\n\n params.callback = callback\n return params\n}\n\nfunction createXHR(uri, options, callback) {\n options = initParams(uri, options, callback)\n return _createXHR(options)\n}\n\nfunction _createXHR(options) {\n if(typeof options.callback === \"undefined\"){\n throw new Error(\"callback argument missing\")\n }\n\n var called = false\n var callback = function cbOnce(err, response, body){\n if(!called){\n called = true\n options.callback(err, response, body)\n }\n }\n\n function readystatechange() {\n if (xhr.readyState === 4) {\n setTimeout(loadFunc, 0)\n }\n }\n\n function getBody() {\n // Chrome with requestType=blob throws errors arround when even testing access to responseText\n var body = undefined\n\n if (xhr.response) {\n body = xhr.response\n } else {\n body = xhr.responseText || getXml(xhr)\n }\n\n if (isJson) {\n try {\n body = JSON.parse(body)\n } catch (e) {}\n }\n\n return body\n }\n\n function errorFunc(evt) {\n clearTimeout(timeoutTimer)\n if(!(evt instanceof Error)){\n evt = new Error(\"\" + (evt || \"Unknown XMLHttpRequest Error\") )\n }\n evt.statusCode = 0\n return callback(evt, failureResponse)\n }\n\n // will load the data & process the response in a special response object\n function loadFunc() {\n if (aborted) return\n var status\n clearTimeout(timeoutTimer)\n if(options.useXDR && xhr.status===undefined) {\n //IE8 CORS GET successful response doesn't have a status field, but body is fine\n status = 200\n } else {\n status = (xhr.status === 1223 ? 204 : xhr.status)\n }\n var response = failureResponse\n var err = null\n\n if (status !== 0){\n response = {\n body: getBody(),\n statusCode: status,\n method: method,\n headers: {},\n url: uri,\n rawRequest: xhr\n }\n if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE\n response.headers = parseHeaders(xhr.getAllResponseHeaders())\n }\n } else {\n err = new Error(\"Internal XMLHttpRequest Error\")\n }\n return callback(err, response, response.body)\n }\n\n var xhr = options.xhr || null\n\n if (!xhr) {\n if (options.cors || options.useXDR) {\n xhr = new createXHR.XDomainRequest()\n }else{\n xhr = new createXHR.XMLHttpRequest()\n }\n }\n\n var key\n var aborted\n var uri = xhr.url = options.uri || options.url\n var method = xhr.method = options.method || \"GET\"\n var body = options.body || options.data\n var headers = xhr.headers = options.headers || {}\n var sync = !!options.sync\n var isJson = false\n var timeoutTimer\n var failureResponse = {\n body: undefined,\n headers: {},\n statusCode: 0,\n method: method,\n url: uri,\n rawRequest: xhr\n }\n\n if (\"json\" in options && options.json !== false) {\n isJson = true\n headers[\"accept\"] || headers[\"Accept\"] || (headers[\"Accept\"] = \"application/json\") //Don't override existing accept header declared by user\n if (method !== \"GET\" && method !== \"HEAD\") {\n headers[\"content-type\"] || headers[\"Content-Type\"] || (headers[\"Content-Type\"] = \"application/json\") //Don't override existing accept header declared by user\n body = JSON.stringify(options.json === true ? body : options.json)\n }\n }\n\n xhr.onreadystatechange = readystatechange\n xhr.onload = loadFunc\n xhr.onerror = errorFunc\n // IE9 must have onprogress be set to a unique function.\n xhr.onprogress = function () {\n // IE must die\n }\n xhr.onabort = function(){\n aborted = true;\n }\n xhr.ontimeout = errorFunc\n xhr.open(method, uri, !sync, options.username, options.password)\n //has to be after open\n if(!sync) {\n xhr.withCredentials = !!options.withCredentials\n }\n // Cannot set timeout with sync request\n // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly\n // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent\n if (!sync && options.timeout > 0 ) {\n timeoutTimer = setTimeout(function(){\n if (aborted) return\n aborted = true//IE9 may still call readystatechange\n xhr.abort(\"timeout\")\n var e = new Error(\"XMLHttpRequest timeout\")\n e.code = \"ETIMEDOUT\"\n errorFunc(e)\n }, options.timeout )\n }\n\n if (xhr.setRequestHeader) {\n for(key in headers){\n if(headers.hasOwnProperty(key)){\n xhr.setRequestHeader(key, headers[key])\n }\n }\n } else if (options.headers && !isEmpty(options.headers)) {\n throw new Error(\"Headers cannot be set on an XDomainRequest object\")\n }\n\n if (\"responseType\" in options) {\n xhr.responseType = options.responseType\n }\n\n if (\"beforeSend\" in options &&\n typeof options.beforeSend === \"function\"\n ) {\n options.beforeSend(xhr)\n }\n\n // Microsoft Edge browser sends \"undefined\" when send is called with undefined value.\n // XMLHttpRequest spec says to pass null as body to indicate no body\n // See https://github.com/naugtur/xhr/issues/100.\n xhr.send(body || null)\n\n return xhr\n\n\n}\n\nfunction getXml(xhr) {\n // xhr.responseXML will throw Exception \"InvalidStateError\" or \"DOMException\"\n // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.\n try {\n if (xhr.responseType === \"document\") {\n return xhr.responseXML\n }\n var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === \"parsererror\"\n if (xhr.responseType === \"\" && !firefoxBugTakenEffect) {\n return xhr.responseXML\n }\n } catch (e) {}\n\n return null\n}\n\nfunction noop() {}\n","module.exports = (function xmlparser() {\n //common browsers\n if (typeof self.DOMParser !== 'undefined') {\n return function(str) {\n var parser = new self.DOMParser()\n return parser.parseFromString(str, 'application/xml')\n }\n } \n\n //IE8 fallback\n if (typeof self.ActiveXObject !== 'undefined'\n && new self.ActiveXObject('Microsoft.XMLDOM')) {\n return function(str) {\n var xmlDoc = new self.ActiveXObject(\"Microsoft.XMLDOM\")\n xmlDoc.async = \"false\"\n xmlDoc.loadXML(str)\n return xmlDoc\n }\n }\n\n //last resort fallback\n return function(str) {\n var div = document.createElement('div')\n div.innerHTML = str\n return div\n }\n})()\n","module.exports = extend\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction extend() {\n var target = {}\n\n for (var i = 0; i < arguments.length; i++) {\n var source = arguments[i]\n\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n target[key] = source[key]\n }\n }\n }\n\n return target\n}\n","var __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __markAsModule = (target) => __defProp(target, \"__esModule\", { value: true });\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __reExport = (target, module2, copyDefault, desc) => {\n if (module2 && typeof module2 === \"object\" || typeof module2 === \"function\") {\n for (let key of __getOwnPropNames(module2))\n if (!__hasOwnProp.call(target, key) && (copyDefault || key !== \"default\"))\n __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });\n }\n return target;\n};\nvar __toCommonJS = /* @__PURE__ */ ((cache) => {\n return (module2, temp) => {\n return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);\n };\n})(typeof WeakMap !== \"undefined\" ? /* @__PURE__ */ new WeakMap() : 0);\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\n\n// src/index.ts\nvar src_exports = {};\n__export(src_exports, {\n applyPalette: () => applyPalette,\n applyPaletteSync: () => applyPaletteSync,\n buildPalette: () => buildPalette,\n buildPaletteSync: () => buildPaletteSync,\n constants: () => constants_exports,\n conversion: () => conversion_exports,\n distance: () => distance_exports,\n image: () => image_exports,\n palette: () => palette_exports,\n quality: () => quality_exports,\n utils: () => utils_exports\n});\n\n// src/constants/index.ts\nvar constants_exports = {};\n__export(constants_exports, {\n bt709: () => bt709_exports\n});\n\n// src/constants/bt709.ts\nvar bt709_exports = {};\n__export(bt709_exports, {\n Y: () => Y,\n x: () => x,\n y: () => y\n});\nvar Y = /* @__PURE__ */ ((Y2) => {\n Y2[Y2[\"RED\"] = 0.2126] = \"RED\";\n Y2[Y2[\"GREEN\"] = 0.7152] = \"GREEN\";\n Y2[Y2[\"BLUE\"] = 0.0722] = \"BLUE\";\n Y2[Y2[\"WHITE\"] = 1] = \"WHITE\";\n return Y2;\n})(Y || {});\nvar x = /* @__PURE__ */ ((x2) => {\n x2[x2[\"RED\"] = 0.64] = \"RED\";\n x2[x2[\"GREEN\"] = 0.3] = \"GREEN\";\n x2[x2[\"BLUE\"] = 0.15] = \"BLUE\";\n x2[x2[\"WHITE\"] = 0.3127] = \"WHITE\";\n return x2;\n})(x || {});\nvar y = /* @__PURE__ */ ((y2) => {\n y2[y2[\"RED\"] = 0.33] = \"RED\";\n y2[y2[\"GREEN\"] = 0.6] = \"GREEN\";\n y2[y2[\"BLUE\"] = 0.06] = \"BLUE\";\n y2[y2[\"WHITE\"] = 0.329] = \"WHITE\";\n return y2;\n})(y || {});\n\n// src/conversion/index.ts\nvar conversion_exports = {};\n__export(conversion_exports, {\n lab2rgb: () => lab2rgb,\n lab2xyz: () => lab2xyz,\n rgb2hsl: () => rgb2hsl,\n rgb2lab: () => rgb2lab,\n rgb2xyz: () => rgb2xyz,\n xyz2lab: () => xyz2lab,\n xyz2rgb: () => xyz2rgb\n});\n\n// src/conversion/rgb2xyz.ts\nfunction correctGamma(n) {\n return n > 0.04045 ? ((n + 0.055) / 1.055) ** 2.4 : n / 12.92;\n}\nfunction rgb2xyz(r, g, b) {\n r = correctGamma(r / 255);\n g = correctGamma(g / 255);\n b = correctGamma(b / 255);\n return {\n x: r * 0.4124 + g * 0.3576 + b * 0.1805,\n y: r * 0.2126 + g * 0.7152 + b * 0.0722,\n z: r * 0.0193 + g * 0.1192 + b * 0.9505\n };\n}\n\n// src/utils/arithmetic.ts\nvar arithmetic_exports = {};\n__export(arithmetic_exports, {\n degrees2radians: () => degrees2radians,\n inRange0to255: () => inRange0to255,\n inRange0to255Rounded: () => inRange0to255Rounded,\n intInRange: () => intInRange,\n max3: () => max3,\n min3: () => min3,\n stableSort: () => stableSort\n});\nfunction degrees2radians(n) {\n return n * (Math.PI / 180);\n}\nfunction max3(a, b, c) {\n let m = a;\n if (m < b)\n m = b;\n if (m < c)\n m = c;\n return m;\n}\nfunction min3(a, b, c) {\n let m = a;\n if (m > b)\n m = b;\n if (m > c)\n m = c;\n return m;\n}\nfunction intInRange(value, low, high) {\n if (value > high)\n value = high;\n if (value < low)\n value = low;\n return value | 0;\n}\nfunction inRange0to255Rounded(n) {\n n = Math.round(n);\n if (n > 255)\n n = 255;\n else if (n < 0)\n n = 0;\n return n;\n}\nfunction inRange0to255(n) {\n if (n > 255)\n n = 255;\n else if (n < 0)\n n = 0;\n return n;\n}\nfunction stableSort(arrayToSort, callback) {\n const type = typeof arrayToSort[0];\n let sorted;\n if (type === \"number\" || type === \"string\") {\n const ord = /* @__PURE__ */ Object.create(null);\n for (let i = 0, l = arrayToSort.length; i < l; i++) {\n const val = arrayToSort[i];\n if (ord[val] || ord[val] === 0)\n continue;\n ord[val] = i;\n }\n sorted = arrayToSort.sort((a, b) => callback(a, b) || ord[a] - ord[b]);\n } else {\n const ord2 = arrayToSort.slice(0);\n sorted = arrayToSort.sort((a, b) => callback(a, b) || ord2.indexOf(a) - ord2.indexOf(b));\n }\n return sorted;\n}\n\n// src/conversion/rgb2hsl.ts\nfunction rgb2hsl(r, g, b) {\n const min = min3(r, g, b);\n const max = max3(r, g, b);\n const delta = max - min;\n const l = (min + max) / 510;\n let s = 0;\n if (l > 0 && l < 1)\n s = delta / (l < 0.5 ? max + min : 510 - max - min);\n let h = 0;\n if (delta > 0) {\n if (max === r) {\n h = (g - b) / delta;\n } else if (max === g) {\n h = 2 + (b - r) / delta;\n } else {\n h = 4 + (r - g) / delta;\n }\n h *= 60;\n if (h < 0)\n h += 360;\n }\n return { h, s, l };\n}\n\n// src/conversion/xyz2lab.ts\nvar refX = 0.95047;\nvar refY = 1;\nvar refZ = 1.08883;\nfunction pivot(n) {\n return n > 8856e-6 ? n ** (1 / 3) : 7.787 * n + 16 / 116;\n}\nfunction xyz2lab(x2, y2, z) {\n x2 = pivot(x2 / refX);\n y2 = pivot(y2 / refY);\n z = pivot(z / refZ);\n if (116 * y2 - 16 < 0)\n throw new Error(\"xxx\");\n return {\n L: Math.max(0, 116 * y2 - 16),\n a: 500 * (x2 - y2),\n b: 200 * (y2 - z)\n };\n}\n\n// src/conversion/rgb2lab.ts\nfunction rgb2lab(r, g, b) {\n const xyz = rgb2xyz(r, g, b);\n return xyz2lab(xyz.x, xyz.y, xyz.z);\n}\n\n// src/conversion/lab2xyz.ts\nvar refX2 = 0.95047;\nvar refY2 = 1;\nvar refZ2 = 1.08883;\nfunction pivot2(n) {\n return n > 0.206893034 ? n ** 3 : (n - 16 / 116) / 7.787;\n}\nfunction lab2xyz(L, a, b) {\n const y2 = (L + 16) / 116;\n const x2 = a / 500 + y2;\n const z = y2 - b / 200;\n return {\n x: refX2 * pivot2(x2),\n y: refY2 * pivot2(y2),\n z: refZ2 * pivot2(z)\n };\n}\n\n// src/conversion/xyz2rgb.ts\nfunction correctGamma2(n) {\n return n > 31308e-7 ? 1.055 * n ** (1 / 2.4) - 0.055 : 12.92 * n;\n}\nfunction xyz2rgb(x2, y2, z) {\n const r = correctGamma2(x2 * 3.2406 + y2 * -1.5372 + z * -0.4986);\n const g = correctGamma2(x2 * -0.9689 + y2 * 1.8758 + z * 0.0415);\n const b = correctGamma2(x2 * 0.0557 + y2 * -0.204 + z * 1.057);\n return {\n r: inRange0to255Rounded(r * 255),\n g: inRange0to255Rounded(g * 255),\n b: inRange0to255Rounded(b * 255)\n };\n}\n\n// src/conversion/lab2rgb.ts\nfunction lab2rgb(L, a, b) {\n const xyz = lab2xyz(L, a, b);\n return xyz2rgb(xyz.x, xyz.y, xyz.z);\n}\n\n// src/distance/index.ts\nvar distance_exports = {};\n__export(distance_exports, {\n AbstractDistanceCalculator: () => AbstractDistanceCalculator,\n AbstractEuclidean: () => AbstractEuclidean,\n AbstractManhattan: () => AbstractManhattan,\n CIE94GraphicArts: () => CIE94GraphicArts,\n CIE94Textiles: () => CIE94Textiles,\n CIEDE2000: () => CIEDE2000,\n CMetric: () => CMetric,\n Euclidean: () => Euclidean,\n EuclideanBT709: () => EuclideanBT709,\n EuclideanBT709NoAlpha: () => EuclideanBT709NoAlpha,\n Manhattan: () => Manhattan,\n ManhattanBT709: () => ManhattanBT709,\n ManhattanNommyde: () => ManhattanNommyde,\n PNGQuant: () => PNGQuant\n});\n\n// src/distance/distanceCalculator.ts\nvar AbstractDistanceCalculator = class {\n constructor() {\n __publicField(this, \"_maxDistance\");\n __publicField(this, \"_whitePoint\");\n this._setDefaults();\n this.setWhitePoint(255, 255, 255, 255);\n }\n setWhitePoint(r, g, b, a) {\n this._whitePoint = {\n r: r > 0 ? 255 / r : 0,\n g: g > 0 ? 255 / g : 0,\n b: b > 0 ? 255 / b : 0,\n a: a > 0 ? 255 / a : 0\n };\n this._maxDistance = this.calculateRaw(r, g, b, a, 0, 0, 0, 0);\n }\n calculateNormalized(colorA, colorB) {\n return this.calculateRaw(colorA.r, colorA.g, colorA.b, colorA.a, colorB.r, colorB.g, colorB.b, colorB.a) / this._maxDistance;\n }\n};\n\n// src/distance/cie94.ts\nvar AbstractCIE94 = class extends AbstractDistanceCalculator {\n calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {\n const lab1 = rgb2lab(inRange0to255(r1 * this._whitePoint.r), inRange0to255(g1 * this._whitePoint.g), inRange0to255(b1 * this._whitePoint.b));\n const lab2 = rgb2lab(inRange0to255(r2 * this._whitePoint.r), inRange0to255(g2 * this._whitePoint.g), inRange0to255(b2 * this._whitePoint.b));\n const dL = lab1.L - lab2.L;\n const dA = lab1.a - lab2.a;\n const dB = lab1.b - lab2.b;\n const c1 = Math.sqrt(lab1.a * lab1.a + lab1.b * lab1.b);\n const c2 = Math.sqrt(lab2.a * lab2.a + lab2.b * lab2.b);\n const dC = c1 - c2;\n let deltaH = dA * dA + dB * dB - dC * dC;\n deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH);\n const dAlpha = (a2 - a1) * this._whitePoint.a * this._kA;\n return Math.sqrt((dL / this._Kl) ** 2 + (dC / (1 + this._K1 * c1)) ** 2 + (deltaH / (1 + this._K2 * c1)) ** 2 + dAlpha ** 2);\n }\n};\nvar CIE94Textiles = class extends AbstractCIE94 {\n _setDefaults() {\n this._Kl = 2;\n this._K1 = 0.048;\n this._K2 = 0.014;\n this._kA = 0.25 * 50 / 255;\n }\n};\nvar CIE94GraphicArts = class extends AbstractCIE94 {\n _setDefaults() {\n this._Kl = 1;\n this._K1 = 0.045;\n this._K2 = 0.015;\n this._kA = 0.25 * 100 / 255;\n }\n};\n\n// src/distance/ciede2000.ts\nvar _CIEDE2000 = class extends AbstractDistanceCalculator {\n _setDefaults() {\n }\n static _calculatehp(b, ap) {\n const hp = Math.atan2(b, ap);\n if (hp >= 0)\n return hp;\n return hp + _CIEDE2000._deg360InRad;\n }\n static _calculateRT(ahp, aCp) {\n const aCp_to_7 = aCp ** 7;\n const R_C = 2 * Math.sqrt(aCp_to_7 / (aCp_to_7 + _CIEDE2000._pow25to7));\n const delta_theta = _CIEDE2000._deg30InRad * Math.exp(-(((ahp - _CIEDE2000._deg275InRad) / _CIEDE2000._deg25InRad) ** 2));\n return -Math.sin(2 * delta_theta) * R_C;\n }\n static _calculateT(ahp) {\n return 1 - 0.17 * Math.cos(ahp - _CIEDE2000._deg30InRad) + 0.24 * Math.cos(ahp * 2) + 0.32 * Math.cos(ahp * 3 + _CIEDE2000._deg6InRad) - 0.2 * Math.cos(ahp * 4 - _CIEDE2000._deg63InRad);\n }\n static _calculate_ahp(C1pC2p, h_bar, h1p, h2p) {\n const hpSum = h1p + h2p;\n if (C1pC2p === 0)\n return hpSum;\n if (h_bar <= _CIEDE2000._deg180InRad)\n return hpSum / 2;\n if (hpSum < _CIEDE2000._deg360InRad) {\n return (hpSum + _CIEDE2000._deg360InRad) / 2;\n }\n return (hpSum - _CIEDE2000._deg360InRad) / 2;\n }\n static _calculate_dHp(C1pC2p, h_bar, h2p, h1p) {\n let dhp;\n if (C1pC2p === 0) {\n dhp = 0;\n } else if (h_bar <= _CIEDE2000._deg180InRad) {\n dhp = h2p - h1p;\n } else if (h2p <= h1p) {\n dhp = h2p - h1p + _CIEDE2000._deg360InRad;\n } else {\n dhp = h2p - h1p - _CIEDE2000._deg360InRad;\n }\n return 2 * Math.sqrt(C1pC2p) * Math.sin(dhp / 2);\n }\n calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {\n const lab1 = rgb2lab(inRange0to255(r1 * this._whitePoint.r), inRange0to255(g1 * this._whitePoint.g), inRange0to255(b1 * this._whitePoint.b));\n const lab2 = rgb2lab(inRange0to255(r2 * this._whitePoint.r), inRange0to255(g2 * this._whitePoint.g), inRange0to255(b2 * this._whitePoint.b));\n const dA = (a2 - a1) * this._whitePoint.a * _CIEDE2000._kA;\n const dE2 = this.calculateRawInLab(lab1, lab2);\n return Math.sqrt(dE2 + dA * dA);\n }\n calculateRawInLab(Lab1, Lab2) {\n const L1 = Lab1.L;\n const a1 = Lab1.a;\n const b1 = Lab1.b;\n const L2 = Lab2.L;\n const a2 = Lab2.a;\n const b2 = Lab2.b;\n const C1 = Math.sqrt(a1 * a1 + b1 * b1);\n const C2 = Math.sqrt(a2 * a2 + b2 * b2);\n const pow_a_C1_C2_to_7 = ((C1 + C2) / 2) ** 7;\n const G = 0.5 * (1 - Math.sqrt(pow_a_C1_C2_to_7 / (pow_a_C1_C2_to_7 + _CIEDE2000._pow25to7)));\n const a1p = (1 + G) * a1;\n const a2p = (1 + G) * a2;\n const C1p = Math.sqrt(a1p * a1p + b1 * b1);\n const C2p = Math.sqrt(a2p * a2p + b2 * b2);\n const C1pC2p = C1p * C2p;\n const h1p = _CIEDE2000._calculatehp(b1, a1p);\n const h2p = _CIEDE2000._calculatehp(b2, a2p);\n const h_bar = Math.abs(h1p - h2p);\n const dLp = L2 - L1;\n const dCp = C2p - C1p;\n const dHp = _CIEDE2000._calculate_dHp(C1pC2p, h_bar, h2p, h1p);\n const ahp = _CIEDE2000._calculate_ahp(C1pC2p, h_bar, h1p, h2p);\n const T = _CIEDE2000._calculateT(ahp);\n const aCp = (C1p + C2p) / 2;\n const aLp_minus_50_square = ((L1 + L2) / 2 - 50) ** 2;\n const S_L = 1 + 0.015 * aLp_minus_50_square / Math.sqrt(20 + aLp_minus_50_square);\n const S_C = 1 + 0.045 * aCp;\n const S_H = 1 + 0.015 * T * aCp;\n const R_T = _CIEDE2000._calculateRT(ahp, aCp);\n const dLpSL = dLp / S_L;\n const dCpSC = dCp / S_C;\n const dHpSH = dHp / S_H;\n return dLpSL ** 2 + dCpSC ** 2 + dHpSH ** 2 + R_T * dCpSC * dHpSH;\n }\n};\nvar CIEDE2000 = _CIEDE2000;\n__publicField(CIEDE2000, \"_kA\", 0.25 * 100 / 255);\n__publicField(CIEDE2000, \"_pow25to7\", 25 ** 7);\n__publicField(CIEDE2000, \"_deg360InRad\", degrees2radians(360));\n__publicField(CIEDE2000, \"_deg180InRad\", degrees2radians(180));\n__publicField(CIEDE2000, \"_deg30InRad\", degrees2radians(30));\n__publicField(CIEDE2000, \"_deg6InRad\", degrees2radians(6));\n__publicField(CIEDE2000, \"_deg63InRad\", degrees2radians(63));\n__publicField(CIEDE2000, \"_deg275InRad\", degrees2radians(275));\n__publicField(CIEDE2000, \"_deg25InRad\", degrees2radians(25));\n\n// src/distance/cmetric.ts\nvar CMetric = class extends AbstractDistanceCalculator {\n calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {\n const rmean = (r1 + r2) / 2 * this._whitePoint.r;\n const r = (r1 - r2) * this._whitePoint.r;\n const g = (g1 - g2) * this._whitePoint.g;\n const b = (b1 - b2) * this._whitePoint.b;\n const dE = ((512 + rmean) * r * r >> 8) + 4 * g * g + ((767 - rmean) * b * b >> 8);\n const dA = (a2 - a1) * this._whitePoint.a;\n return Math.sqrt(dE + dA * dA);\n }\n _setDefaults() {\n }\n};\n\n// src/distance/euclidean.ts\nvar AbstractEuclidean = class extends AbstractDistanceCalculator {\n calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {\n const dR = r2 - r1;\n const dG = g2 - g1;\n const dB = b2 - b1;\n const dA = a2 - a1;\n return Math.sqrt(this._kR * dR * dR + this._kG * dG * dG + this._kB * dB * dB + this._kA * dA * dA);\n }\n};\nvar Euclidean = class extends AbstractEuclidean {\n _setDefaults() {\n this._kR = 1;\n this._kG = 1;\n this._kB = 1;\n this._kA = 1;\n }\n};\nvar EuclideanBT709 = class extends AbstractEuclidean {\n _setDefaults() {\n this._kR = 0.2126 /* RED */;\n this._kG = 0.7152 /* GREEN */;\n this._kB = 0.0722 /* BLUE */;\n this._kA = 1;\n }\n};\nvar EuclideanBT709NoAlpha = class extends AbstractEuclidean {\n _setDefaults() {\n this._kR = 0.2126 /* RED */;\n this._kG = 0.7152 /* GREEN */;\n this._kB = 0.0722 /* BLUE */;\n this._kA = 0;\n }\n};\n\n// src/distance/manhattan.ts\nvar AbstractManhattan = class extends AbstractDistanceCalculator {\n calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {\n let dR = r2 - r1;\n let dG = g2 - g1;\n let dB = b2 - b1;\n let dA = a2 - a1;\n if (dR < 0)\n dR = 0 - dR;\n if (dG < 0)\n dG = 0 - dG;\n if (dB < 0)\n dB = 0 - dB;\n if (dA < 0)\n dA = 0 - dA;\n return this._kR * dR + this._kG * dG + this._kB * dB + this._kA * dA;\n }\n};\nvar Manhattan = class extends AbstractManhattan {\n _setDefaults() {\n this._kR = 1;\n this._kG = 1;\n this._kB = 1;\n this._kA = 1;\n }\n};\nvar ManhattanNommyde = class extends AbstractManhattan {\n _setDefaults() {\n this._kR = 0.4984;\n this._kG = 0.8625;\n this._kB = 0.2979;\n this._kA = 1;\n }\n};\nvar ManhattanBT709 = class extends AbstractManhattan {\n _setDefaults() {\n this._kR = 0.2126 /* RED */;\n this._kG = 0.7152 /* GREEN */;\n this._kB = 0.0722 /* BLUE */;\n this._kA = 1;\n }\n};\n\n// src/distance/pngQuant.ts\nvar PNGQuant = class extends AbstractDistanceCalculator {\n calculateRaw(r1, g1, b1, a1, r2, g2, b2, a2) {\n const alphas = (a2 - a1) * this._whitePoint.a;\n return this._colordifferenceCh(r1 * this._whitePoint.r, r2 * this._whitePoint.r, alphas) + this._colordifferenceCh(g1 * this._whitePoint.g, g2 * this._whitePoint.g, alphas) + this._colordifferenceCh(b1 * this._whitePoint.b, b2 * this._whitePoint.b, alphas);\n }\n _colordifferenceCh(x2, y2, alphas) {\n const black = x2 - y2;\n const white = black + alphas;\n return black * black + white * white;\n }\n _setDefaults() {\n }\n};\n\n// src/palette/index.ts\nvar palette_exports = {};\n__export(palette_exports, {\n AbstractPaletteQuantizer: () => AbstractPaletteQuantizer,\n ColorHistogram: () => ColorHistogram,\n NeuQuant: () => NeuQuant,\n NeuQuantFloat: () => NeuQuantFloat,\n RGBQuant: () => RGBQuant,\n WuColorCube: () => WuColorCube,\n WuQuant: () => WuQuant\n});\n\n// src/palette/paletteQuantizer.ts\nvar AbstractPaletteQuantizer = class {\n quantizeSync() {\n for (const value of this.quantize()) {\n if (value.palette) {\n return value.palette;\n }\n }\n throw new Error(\"unreachable\");\n }\n};\n\n// src/utils/point.ts\nvar Point = class {\n constructor() {\n __publicField(this, \"r\");\n __publicField(this, \"g\");\n __publicField(this, \"b\");\n __publicField(this, \"a\");\n __publicField(this, \"uint32\");\n __publicField(this, \"rgba\");\n this.uint32 = -1 >>> 0;\n this.r = this.g = this.b = this.a = 0;\n this.rgba = new Array(4);\n this.rgba[0] = 0;\n this.rgba[1] = 0;\n this.rgba[2] = 0;\n this.rgba[3] = 0;\n }\n static createByQuadruplet(quadruplet) {\n const point = new Point();\n point.r = quadruplet[0] | 0;\n point.g = quadruplet[1] | 0;\n point.b = quadruplet[2] | 0;\n point.a = quadruplet[3] | 0;\n point._loadUINT32();\n point._loadQuadruplet();\n return point;\n }\n static createByRGBA(red, green, blue, alpha) {\n const point = new Point();\n point.r = red | 0;\n point.g = green | 0;\n point.b = blue | 0;\n point.a = alpha | 0;\n point._loadUINT32();\n point._loadQuadruplet();\n return point;\n }\n static createByUint32(uint32) {\n const point = new Point();\n point.uint32 = uint32 >>> 0;\n point._loadRGBA();\n point._loadQuadruplet();\n return point;\n }\n from(point) {\n this.r = point.r;\n this.g = point.g;\n this.b = point.b;\n this.a = point.a;\n this.uint32 = point.uint32;\n this.rgba[0] = point.r;\n this.rgba[1] = point.g;\n this.rgba[2] = point.b;\n this.rgba[3] = point.a;\n }\n getLuminosity(useAlphaChannel) {\n let r = this.r;\n let g = this.g;\n let b = this.b;\n if (useAlphaChannel) {\n r = Math.min(255, 255 - this.a + this.a * r / 255);\n g = Math.min(255, 255 - this.a + this.a * g / 255);\n b = Math.min(255, 255 - this.a + this.a * b / 255);\n }\n return r * 0.2126 /* RED */ + g * 0.7152 /* GREEN */ + b * 0.0722 /* BLUE */;\n }\n _loadUINT32() {\n this.uint32 = (this.a << 24 | this.b << 16 | this.g << 8 | this.r) >>> 0;\n }\n _loadRGBA() {\n this.r = this.uint32 & 255;\n this.g = this.uint32 >>> 8 & 255;\n this.b = this.uint32 >>> 16 & 255;\n this.a = this.uint32 >>> 24 & 255;\n }\n _loadQuadruplet() {\n this.rgba[0] = this.r;\n this.rgba[1] = this.g;\n this.rgba[2] = this.b;\n this.rgba[3] = this.a;\n }\n};\n\n// src/utils/pointContainer.ts\nvar PointContainer = class {\n constructor() {\n __publicField(this, \"_pointArray\");\n __publicField(this, \"_width\");\n __publicField(this, \"_height\");\n this._width = 0;\n this._height = 0;\n this._pointArray = [];\n }\n getWidth() {\n return this._width;\n }\n getHeight() {\n return this._height;\n }\n setWidth(width) {\n this._width = width;\n }\n setHeight(height) {\n this._height = height;\n }\n getPointArray() {\n return this._pointArray;\n }\n clone() {\n const clone = new PointContainer();\n clone._width = this._width;\n clone._height = this._height;\n for (let i = 0, l = this._pointArray.length; i < l; i++) {\n clone._pointArray[i] = Point.createByUint32(this._pointArray[i].uint32 | 0);\n }\n return clone;\n }\n toUint32Array() {\n const l = this._pointArray.length;\n const uint32Array = new Uint32Array(l);\n for (let i = 0; i < l; i++) {\n uint32Array[i] = this._pointArray[i].uint32;\n }\n return uint32Array;\n }\n toUint8Array() {\n return new Uint8Array(this.toUint32Array().buffer);\n }\n static fromHTMLImageElement(img) {\n const width = img.naturalWidth;\n const height = img.naturalHeight;\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(img, 0, 0, width, height, 0, 0, width, height);\n return PointContainer.fromHTMLCanvasElement(canvas);\n }\n static fromHTMLCanvasElement(canvas) {\n const width = canvas.width;\n const height = canvas.height;\n const ctx = canvas.getContext(\"2d\");\n const imgData = ctx.getImageData(0, 0, width, height);\n return PointContainer.fromImageData(imgData);\n }\n static fromImageData(imageData) {\n const width = imageData.width;\n const height = imageData.height;\n return PointContainer.fromUint8Array(imageData.data, width, height);\n }\n static fromUint8Array(uint8Array, width, height) {\n switch (Object.prototype.toString.call(uint8Array)) {\n case \"[object Uint8ClampedArray]\":\n case \"[object Uint8Array]\":\n break;\n default:\n uint8Array = new Uint8Array(uint8Array);\n }\n const uint32Array = new Uint32Array(uint8Array.buffer);\n return PointContainer.fromUint32Array(uint32Array, width, height);\n }\n static fromUint32Array(uint32Array, width, height) {\n const container = new PointContainer();\n container._width = width;\n container._height = height;\n for (let i = 0, l = uint32Array.length; i < l; i++) {\n container._pointArray[i] = Point.createByUint32(uint32Array[i] | 0);\n }\n return container;\n }\n static fromBuffer(buffer, width, height) {\n const uint32Array = new Uint32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Uint32Array.BYTES_PER_ELEMENT);\n return PointContainer.fromUint32Array(uint32Array, width, height);\n }\n};\n\n// src/utils/palette.ts\nvar hueGroups = 10;\nfunction hueGroup(hue, segmentsNumber) {\n const maxHue = 360;\n const seg = maxHue / segmentsNumber;\n const half = seg / 2;\n for (let i = 1, mid = seg - half; i < segmentsNumber; i++, mid += seg) {\n if (hue >= mid && hue < mid + seg)\n return i;\n }\n return 0;\n}\nvar Palette = class {\n constructor() {\n __publicField(this, \"_pointContainer\");\n __publicField(this, \"_pointArray\", []);\n __publicField(this, \"_i32idx\", {});\n this._pointContainer = new PointContainer();\n this._pointContainer.setHeight(1);\n this._pointArray = this._pointContainer.getPointArray();\n }\n add(color) {\n this._pointArray.push(color);\n this._pointContainer.setWidth(this._pointArray.length);\n }\n has(color) {\n for (let i = this._pointArray.length - 1; i >= 0; i--) {\n if (color.uint32 === this._pointArray[i].uint32)\n return true;\n }\n return false;\n }\n getNearestColor(colorDistanceCalculator, color) {\n return this._pointArray[this._getNearestIndex(colorDistanceCalculator, color) | 0];\n }\n getPointContainer() {\n return this._pointContainer;\n }\n _nearestPointFromCache(key) {\n return typeof this._i32idx[key] === \"number\" ? this._i32idx[key] : -1;\n }\n _getNearestIndex(colorDistanceCalculator, point) {\n let idx = this._nearestPointFromCache(\"\" + point.uint32);\n if (idx >= 0)\n return idx;\n let minimalDistance = Number.MAX_VALUE;\n idx = 0;\n for (let i = 0, l = this._pointArray.length; i < l; i++) {\n const p = this._pointArray[i];\n const distance = colorDistanceCalculator.calculateRaw(point.r, point.g, point.b, point.a, p.r, p.g, p.b, p.a);\n if (distance < minimalDistance) {\n minimalDistance = distance;\n idx = i;\n }\n }\n this._i32idx[point.uint32] = idx;\n return idx;\n }\n sort() {\n this._i32idx = {};\n this._pointArray.sort((a, b) => {\n const hslA = rgb2hsl(a.r, a.g, a.b);\n const hslB = rgb2hsl(b.r, b.g, b.b);\n const hueA = a.r === a.g && a.g === a.b ? 0 : 1 + hueGroup(hslA.h, hueGroups);\n const hueB = b.r === b.g && b.g === b.b ? 0 : 1 + hueGroup(hslB.h, hueGroups);\n const hueDiff = hueB - hueA;\n if (hueDiff)\n return -hueDiff;\n const lA = a.getLuminosity(true);\n const lB = b.getLuminosity(true);\n if (lB - lA !== 0)\n return lB - lA;\n const satDiff = (hslB.s * 100 | 0) - (hslA.s * 100 | 0);\n if (satDiff)\n return -satDiff;\n return 0;\n });\n }\n};\n\n// src/utils/index.ts\nvar utils_exports = {};\n__export(utils_exports, {\n HueStatistics: () => HueStatistics,\n Palette: () => Palette,\n Point: () => Point,\n PointContainer: () => PointContainer,\n ProgressTracker: () => ProgressTracker,\n arithmetic: () => arithmetic_exports\n});\n\n// src/utils/hueStatistics.ts\nvar HueGroup = class {\n constructor() {\n __publicField(this, \"num\", 0);\n __publicField(this, \"cols\", []);\n }\n};\nvar HueStatistics = class {\n constructor(numGroups, minCols) {\n __publicField(this, \"_numGroups\");\n __publicField(this, \"_minCols\");\n __publicField(this, \"_stats\");\n __publicField(this, \"_groupsFull\");\n this._numGroups = numGroups;\n this._minCols = minCols;\n this._stats = [];\n for (let i = 0; i <= numGroups; i++) {\n this._stats[i] = new HueGroup();\n }\n this._groupsFull = 0;\n }\n check(i32) {\n if (this._groupsFull === this._numGroups + 1) {\n this.check = () => {\n };\n }\n const r = i32 & 255;\n const g = i32 >>> 8 & 255;\n const b = i32 >>> 16 & 255;\n const hg = r === g && g === b ? 0 : 1 + hueGroup(rgb2hsl(r, g, b).h, this._numGroups);\n const gr = this._stats[hg];\n const min = this._minCols;\n gr.num++;\n if (gr.num > min) {\n return;\n }\n if (gr.num === min) {\n this._groupsFull++;\n }\n if (gr.num <= min) {\n this._stats[hg].cols.push(i32);\n }\n }\n injectIntoDictionary(histG) {\n for (let i = 0; i <= this._numGroups; i++) {\n if (this._stats[i].num <= this._minCols) {\n this._stats[i].cols.forEach((col) => {\n if (!histG[col]) {\n histG[col] = 1;\n } else {\n histG[col]++;\n }\n });\n }\n }\n }\n injectIntoArray(histG) {\n for (let i = 0; i <= this._numGroups; i++) {\n if (this._stats[i].num <= this._minCols) {\n this._stats[i].cols.forEach((col) => {\n if (histG.indexOf(col) === -1) {\n histG.push(col);\n }\n });\n }\n }\n }\n};\n\n// src/utils/progressTracker.ts\nvar _ProgressTracker = class {\n constructor(valueRange, progressRange) {\n __publicField(this, \"progress\");\n __publicField(this, \"_step\");\n __publicField(this, \"_range\");\n __publicField(this, \"_last\");\n __publicField(this, \"_progressRange\");\n this._range = valueRange;\n this._progressRange = progressRange;\n this._step = Math.max(1, this._range / (_ProgressTracker.steps + 1) | 0);\n this._last = -this._step;\n this.progress = 0;\n }\n shouldNotify(current) {\n if (current - this._last >= this._step) {\n this._last = current;\n this.progress = Math.min(this._progressRange * this._last / this._range, this._progressRange);\n return true;\n }\n return false;\n }\n};\nvar ProgressTracker = _ProgressTracker;\n__publicField(ProgressTracker, \"steps\", 100);\n\n// src/palette/neuquant/neuquant.ts\nvar networkBiasShift = 3;\nvar Neuron = class {\n constructor(defaultValue) {\n __publicField(this, \"r\");\n __publicField(this, \"g\");\n __publicField(this, \"b\");\n __publicField(this, \"a\");\n this.r = this.g = this.b = this.a = defaultValue;\n }\n toPoint() {\n return Point.createByRGBA(this.r >> networkBiasShift, this.g >> networkBiasShift, this.b >> networkBiasShift, this.a >> networkBiasShift);\n }\n subtract(r, g, b, a) {\n this.r -= r | 0;\n this.g -= g | 0;\n this.b -= b | 0;\n this.a -= a | 0;\n }\n};\nvar _NeuQuant = class extends AbstractPaletteQuantizer {\n constructor(colorDistanceCalculator, colors = 256) {\n super();\n __publicField(this, \"_pointArray\");\n __publicField(this, \"_networkSize\");\n __publicField(this, \"_network\");\n __publicField(this, \"_sampleFactor\");\n __publicField(this, \"_radPower\");\n __publicField(this, \"_freq\");\n __publicField(this, \"_bias\");\n __publicField(this, \"_distance\");\n this._distance = colorDistanceCalculator;\n this._pointArray = [];\n this._sampleFactor = 1;\n this._networkSize = colors;\n this._distance.setWhitePoint(255 << networkBiasShift, 255 << networkBiasShift, 255 << networkBiasShift, 255 << networkBiasShift);\n }\n sample(pointContainer) {\n this._pointArray = this._pointArray.concat(pointContainer.getPointArray());\n }\n *quantize() {\n this._init();\n yield* this._learn();\n yield {\n palette: this._buildPalette(),\n progress: 100\n };\n }\n _init() {\n this._freq = [];\n this._bias = [];\n this._radPower = [];\n this._network = [];\n for (let i = 0; i < this._networkSize; i++) {\n this._network[i] = new Neuron((i << networkBiasShift + 8) / this._networkSize | 0);\n this._freq[i] = _NeuQuant._initialBias / this._networkSize | 0;\n this._bias[i] = 0;\n }\n }\n *_learn() {\n let sampleFactor = this._sampleFactor;\n const pointsNumber = this._pointArray.length;\n if (pointsNumber < _NeuQuant._minpicturebytes)\n sampleFactor = 1;\n const alphadec = 30 + (sampleFactor - 1) / 3 | 0;\n const pointsToSample = pointsNumber / sampleFactor | 0;\n let delta = pointsToSample / _NeuQuant._nCycles | 0;\n let alpha = _NeuQuant._initAlpha;\n let radius = (this._networkSize >> 3) * _NeuQuant._radiusBias;\n let rad = radius >> _NeuQuant._radiusBiasShift;\n if (rad <= 1)\n rad = 0;\n for (let i = 0; i < rad; i++) {\n this._radPower[i] = alpha * ((rad * rad - i * i) * _NeuQuant._radBias / (rad * rad)) >>> 0;\n }\n let step;\n if (pointsNumber < _NeuQuant._minpicturebytes) {\n step = 1;\n } else if (pointsNumber % _NeuQuant._prime1 !== 0) {\n step = _NeuQuant._prime1;\n } else if (pointsNumber % _NeuQuant._prime2 !== 0) {\n step = _NeuQuant._prime2;\n } else if (pointsNumber % _NeuQuant._prime3 !== 0) {\n step = _NeuQuant._prime3;\n } else {\n step = _NeuQuant._prime4;\n }\n const tracker = new ProgressTracker(pointsToSample, 99);\n for (let i = 0, pointIndex = 0; i < pointsToSample; ) {\n if (tracker.shouldNotify(i)) {\n yield {\n progress: tracker.progress\n };\n }\n const point = this._pointArray[pointIndex];\n const b = point.b << networkBiasShift;\n const g = point.g << networkBiasShift;\n const r = point.r << networkBiasShift;\n const a = point.a << networkBiasShift;\n const neuronIndex = this._contest(b, g, r, a);\n this._alterSingle(alpha, neuronIndex, b, g, r, a);\n if (rad !== 0)\n this._alterNeighbour(rad, neuronIndex, b, g, r, a);\n pointIndex += step;\n if (pointIndex >= pointsNumber)\n pointIndex -= pointsNumber;\n i++;\n if (delta === 0)\n delta = 1;\n if (i % delta === 0) {\n alpha -= alpha / alphadec | 0;\n radius -= radius / _NeuQuant._radiusDecrease | 0;\n rad = radius >> _NeuQuant._radiusBiasShift;\n if (rad <= 1)\n rad = 0;\n for (let j = 0; j < rad; j++) {\n this._radPower[j] = alpha * ((rad * rad - j * j) * _NeuQuant._radBias / (rad * rad)) >>> 0;\n }\n }\n }\n }\n _buildPalette() {\n const palette = new Palette();\n this._network.forEach((neuron) => {\n palette.add(neuron.toPoint());\n });\n palette.sort();\n return palette;\n }\n _alterNeighbour(rad, i, b, g, r, al) {\n let lo = i - rad;\n if (lo < -1)\n lo = -1;\n let hi = i + rad;\n if (hi > this._networkSize)\n hi = this._networkSize;\n let j = i + 1;\n let k = i - 1;\n let m = 1;\n while (j < hi || k > lo) {\n const a = this._radPower[m++] / _NeuQuant._alphaRadBias;\n if (j < hi) {\n const p = this._network[j++];\n p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));\n }\n if (k > lo) {\n const p = this._network[k--];\n p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));\n }\n }\n }\n _alterSingle(alpha, i, b, g, r, a) {\n alpha /= _NeuQuant._initAlpha;\n const n = this._network[i];\n n.subtract(alpha * (n.r - r), alpha * (n.g - g), alpha * (n.b - b), alpha * (n.a - a));\n }\n _contest(b, g, r, a) {\n const multiplier = 255 * 4 << networkBiasShift;\n let bestd = ~(1 << 31);\n let bestbiasd = bestd;\n let bestpos = -1;\n let bestbiaspos = bestpos;\n for (let i = 0; i < this._networkSize; i++) {\n const n = this._network[i];\n const dist = this._distance.calculateNormalized(n, { r, g, b, a }) * multiplier | 0;\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n const biasdist = dist - (this._bias[i] >> _NeuQuant._initialBiasShift - networkBiasShift);\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n const betafreq = this._freq[i] >> _NeuQuant._betaShift;\n this._freq[i] -= betafreq;\n this._bias[i] += betafreq << _NeuQuant._gammaShift;\n }\n this._freq[bestpos] += _NeuQuant._beta;\n this._bias[bestpos] -= _NeuQuant._betaGamma;\n return bestbiaspos;\n }\n};\nvar NeuQuant = _NeuQuant;\n__publicField(NeuQuant, \"_prime1\", 499);\n__publicField(NeuQuant, \"_prime2\", 491);\n__publicField(NeuQuant, \"_prime3\", 487);\n__publicField(NeuQuant, \"_prime4\", 503);\n__publicField(NeuQuant, \"_minpicturebytes\", _NeuQuant._prime4);\n__publicField(NeuQuant, \"_nCycles\", 100);\n__publicField(NeuQuant, \"_initialBiasShift\", 16);\n__publicField(NeuQuant, \"_initialBias\", 1 << _NeuQuant._initialBiasShift);\n__publicField(NeuQuant, \"_gammaShift\", 10);\n__publicField(NeuQuant, \"_betaShift\", 10);\n__publicField(NeuQuant, \"_beta\", _NeuQuant._initialBias >> _NeuQuant._betaShift);\n__publicField(NeuQuant, \"_betaGamma\", _NeuQuant._initialBias << _NeuQuant._gammaShift - _NeuQuant._betaShift);\n__publicField(NeuQuant, \"_radiusBiasShift\", 6);\n__publicField(NeuQuant, \"_radiusBias\", 1 << _NeuQuant._radiusBiasShift);\n__publicField(NeuQuant, \"_radiusDecrease\", 30);\n__publicField(NeuQuant, \"_alphaBiasShift\", 10);\n__publicField(NeuQuant, \"_initAlpha\", 1 << _NeuQuant._alphaBiasShift);\n__publicField(NeuQuant, \"_radBiasShift\", 8);\n__publicField(NeuQuant, \"_radBias\", 1 << _NeuQuant._radBiasShift);\n__publicField(NeuQuant, \"_alphaRadBiasShift\", _NeuQuant._alphaBiasShift + _NeuQuant._radBiasShift);\n__publicField(NeuQuant, \"_alphaRadBias\", 1 << _NeuQuant._alphaRadBiasShift);\n\n// src/palette/neuquant/neuquantFloat.ts\nvar networkBiasShift2 = 3;\nvar NeuronFloat = class {\n constructor(defaultValue) {\n __publicField(this, \"r\");\n __publicField(this, \"g\");\n __publicField(this, \"b\");\n __publicField(this, \"a\");\n this.r = this.g = this.b = this.a = defaultValue;\n }\n toPoint() {\n return Point.createByRGBA(this.r >> networkBiasShift2, this.g >> networkBiasShift2, this.b >> networkBiasShift2, this.a >> networkBiasShift2);\n }\n subtract(r, g, b, a) {\n this.r -= r;\n this.g -= g;\n this.b -= b;\n this.a -= a;\n }\n};\nvar _NeuQuantFloat = class extends AbstractPaletteQuantizer {\n constructor(colorDistanceCalculator, colors = 256) {\n super();\n __publicField(this, \"_pointArray\");\n __publicField(this, \"_networkSize\");\n __publicField(this, \"_network\");\n __publicField(this, \"_sampleFactor\");\n __publicField(this, \"_radPower\");\n __publicField(this, \"_freq\");\n __publicField(this, \"_bias\");\n __publicField(this, \"_distance\");\n this._distance = colorDistanceCalculator;\n this._pointArray = [];\n this._sampleFactor = 1;\n this._networkSize = colors;\n this._distance.setWhitePoint(255 << networkBiasShift2, 255 << networkBiasShift2, 255 << networkBiasShift2, 255 << networkBiasShift2);\n }\n sample(pointContainer) {\n this._pointArray = this._pointArray.concat(pointContainer.getPointArray());\n }\n *quantize() {\n this._init();\n yield* this._learn();\n yield {\n palette: this._buildPalette(),\n progress: 100\n };\n }\n _init() {\n this._freq = [];\n this._bias = [];\n this._radPower = [];\n this._network = [];\n for (let i = 0; i < this._networkSize; i++) {\n this._network[i] = new NeuronFloat((i << networkBiasShift2 + 8) / this._networkSize);\n this._freq[i] = _NeuQuantFloat._initialBias / this._networkSize;\n this._bias[i] = 0;\n }\n }\n *_learn() {\n let sampleFactor = this._sampleFactor;\n const pointsNumber = this._pointArray.length;\n if (pointsNumber < _NeuQuantFloat._minpicturebytes)\n sampleFactor = 1;\n const alphadec = 30 + (sampleFactor - 1) / 3;\n const pointsToSample = pointsNumber / sampleFactor;\n let delta = pointsToSample / _NeuQuantFloat._nCycles | 0;\n let alpha = _NeuQuantFloat._initAlpha;\n let radius = (this._networkSize >> 3) * _NeuQuantFloat._radiusBias;\n let rad = radius >> _NeuQuantFloat._radiusBiasShift;\n if (rad <= 1)\n rad = 0;\n for (let i = 0; i < rad; i++) {\n this._radPower[i] = alpha * ((rad * rad - i * i) * _NeuQuantFloat._radBias / (rad * rad));\n }\n let step;\n if (pointsNumber < _NeuQuantFloat._minpicturebytes) {\n step = 1;\n } else if (pointsNumber % _NeuQuantFloat._prime1 !== 0) {\n step = _NeuQuantFloat._prime1;\n } else if (pointsNumber % _NeuQuantFloat._prime2 !== 0) {\n step = _NeuQuantFloat._prime2;\n } else if (pointsNumber % _NeuQuantFloat._prime3 !== 0) {\n step = _NeuQuantFloat._prime3;\n } else {\n step = _NeuQuantFloat._prime4;\n }\n const tracker = new ProgressTracker(pointsToSample, 99);\n for (let i = 0, pointIndex = 0; i < pointsToSample; ) {\n if (tracker.shouldNotify(i)) {\n yield {\n progress: tracker.progress\n };\n }\n const point = this._pointArray[pointIndex];\n const b = point.b << networkBiasShift2;\n const g = point.g << networkBiasShift2;\n const r = point.r << networkBiasShift2;\n const a = point.a << networkBiasShift2;\n const neuronIndex = this._contest(b, g, r, a);\n this._alterSingle(alpha, neuronIndex, b, g, r, a);\n if (rad !== 0)\n this._alterNeighbour(rad, neuronIndex, b, g, r, a);\n pointIndex += step;\n if (pointIndex >= pointsNumber)\n pointIndex -= pointsNumber;\n i++;\n if (delta === 0)\n delta = 1;\n if (i % delta === 0) {\n alpha -= alpha / alphadec;\n radius -= radius / _NeuQuantFloat._radiusDecrease;\n rad = radius >> _NeuQuantFloat._radiusBiasShift;\n if (rad <= 1)\n rad = 0;\n for (let j = 0; j < rad; j++) {\n this._radPower[j] = alpha * ((rad * rad - j * j) * _NeuQuantFloat._radBias / (rad * rad));\n }\n }\n }\n }\n _buildPalette() {\n const palette = new Palette();\n this._network.forEach((neuron) => {\n palette.add(neuron.toPoint());\n });\n palette.sort();\n return palette;\n }\n _alterNeighbour(rad, i, b, g, r, al) {\n let lo = i - rad;\n if (lo < -1)\n lo = -1;\n let hi = i + rad;\n if (hi > this._networkSize)\n hi = this._networkSize;\n let j = i + 1;\n let k = i - 1;\n let m = 1;\n while (j < hi || k > lo) {\n const a = this._radPower[m++] / _NeuQuantFloat._alphaRadBias;\n if (j < hi) {\n const p = this._network[j++];\n p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));\n }\n if (k > lo) {\n const p = this._network[k--];\n p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));\n }\n }\n }\n _alterSingle(alpha, i, b, g, r, a) {\n alpha /= _NeuQuantFloat._initAlpha;\n const n = this._network[i];\n n.subtract(alpha * (n.r - r), alpha * (n.g - g), alpha * (n.b - b), alpha * (n.a - a));\n }\n _contest(b, g, r, al) {\n const multiplier = 255 * 4 << networkBiasShift2;\n let bestd = ~(1 << 31);\n let bestbiasd = bestd;\n let bestpos = -1;\n let bestbiaspos = bestpos;\n for (let i = 0; i < this._networkSize; i++) {\n const n = this._network[i];\n const dist = this._distance.calculateNormalized(n, { r, g, b, a: al }) * multiplier;\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n const biasdist = dist - (this._bias[i] >> _NeuQuantFloat._initialBiasShift - networkBiasShift2);\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n const betafreq = this._freq[i] >> _NeuQuantFloat._betaShift;\n this._freq[i] -= betafreq;\n this._bias[i] += betafreq << _NeuQuantFloat._gammaShift;\n }\n this._freq[bestpos] += _NeuQuantFloat._beta;\n this._bias[bestpos] -= _NeuQuantFloat._betaGamma;\n return bestbiaspos;\n }\n};\nvar NeuQuantFloat = _NeuQuantFloat;\n__publicField(NeuQuantFloat, \"_prime1\", 499);\n__publicField(NeuQuantFloat, \"_prime2\", 491);\n__publicField(NeuQuantFloat, \"_prime3\", 487);\n__publicField(NeuQuantFloat, \"_prime4\", 503);\n__publicField(NeuQuantFloat, \"_minpicturebytes\", _NeuQuantFloat._prime4);\n__publicField(NeuQuantFloat, \"_nCycles\", 100);\n__publicField(NeuQuantFloat, \"_initialBiasShift\", 16);\n__publicField(NeuQuantFloat, \"_initialBias\", 1 << _NeuQuantFloat._initialBiasShift);\n__publicField(NeuQuantFloat, \"_gammaShift\", 10);\n__publicField(NeuQuantFloat, \"_betaShift\", 10);\n__publicField(NeuQuantFloat, \"_beta\", _NeuQuantFloat._initialBias >> _NeuQuantFloat._betaShift);\n__publicField(NeuQuantFloat, \"_betaGamma\", _NeuQuantFloat._initialBias << _NeuQuantFloat._gammaShift - _NeuQuantFloat._betaShift);\n__publicField(NeuQuantFloat, \"_radiusBiasShift\", 6);\n__publicField(NeuQuantFloat, \"_radiusBias\", 1 << _NeuQuantFloat._radiusBiasShift);\n__publicField(NeuQuantFloat, \"_radiusDecrease\", 30);\n__publicField(NeuQuantFloat, \"_alphaBiasShift\", 10);\n__publicField(NeuQuantFloat, \"_initAlpha\", 1 << _NeuQuantFloat._alphaBiasShift);\n__publicField(NeuQuantFloat, \"_radBiasShift\", 8);\n__publicField(NeuQuantFloat, \"_radBias\", 1 << _NeuQuantFloat._radBiasShift);\n__publicField(NeuQuantFloat, \"_alphaRadBiasShift\", _NeuQuantFloat._alphaBiasShift + _NeuQuantFloat._radBiasShift);\n__publicField(NeuQuantFloat, \"_alphaRadBias\", 1 << _NeuQuantFloat._alphaRadBiasShift);\n\n// src/palette/rgbquant/colorHistogram.ts\nvar _ColorHistogram = class {\n constructor(method, colors) {\n __publicField(this, \"_method\");\n __publicField(this, \"_hueStats\");\n __publicField(this, \"_histogram\");\n __publicField(this, \"_initColors\");\n __publicField(this, \"_minHueCols\");\n this._method = method;\n this._minHueCols = colors << 2;\n this._initColors = colors << 2;\n this._hueStats = new HueStatistics(_ColorHistogram._hueGroups, this._minHueCols);\n this._histogram = /* @__PURE__ */ Object.create(null);\n }\n sample(pointContainer) {\n switch (this._method) {\n case 1:\n this._colorStats1D(pointContainer);\n break;\n case 2:\n this._colorStats2D(pointContainer);\n break;\n }\n }\n getImportanceSortedColorsIDXI32() {\n const sorted = stableSort(Object.keys(this._histogram), (a, b) => this._histogram[b] - this._histogram[a]);\n if (sorted.length === 0) {\n return [];\n }\n let idxi32;\n switch (this._method) {\n case 1:\n const initialColorsLimit = Math.min(sorted.length, this._initColors);\n const last = sorted[initialColorsLimit - 1];\n const freq = this._histogram[last];\n idxi32 = sorted.slice(0, initialColorsLimit);\n let pos = initialColorsLimit;\n const len = sorted.length;\n while (pos < len && this._histogram[sorted[pos]] === freq) {\n idxi32.push(sorted[pos++]);\n }\n this._hueStats.injectIntoArray(idxi32);\n break;\n case 2:\n idxi32 = sorted;\n break;\n default:\n throw new Error(\"Incorrect method\");\n }\n return idxi32.map((v) => +v);\n }\n _colorStats1D(pointContainer) {\n const histG = this._histogram;\n const pointArray = pointContainer.getPointArray();\n const len = pointArray.length;\n for (let i = 0; i < len; i++) {\n const col = pointArray[i].uint32;\n this._hueStats.check(col);\n if (col in histG) {\n histG[col]++;\n } else {\n histG[col] = 1;\n }\n }\n }\n _colorStats2D(pointContainer) {\n const width = pointContainer.getWidth();\n const height = pointContainer.getHeight();\n const pointArray = pointContainer.getPointArray();\n const boxW = _ColorHistogram._boxSize[0];\n const boxH = _ColorHistogram._boxSize[1];\n const area = boxW * boxH;\n const boxes = this._makeBoxes(width, height, boxW, boxH);\n const histG = this._histogram;\n boxes.forEach((box) => {\n let effc = Math.round(box.w * box.h / area) * _ColorHistogram._boxPixels;\n if (effc < 2)\n effc = 2;\n const histL = {};\n this._iterateBox(box, width, (i) => {\n const col = pointArray[i].uint32;\n this._hueStats.check(col);\n if (col in histG) {\n histG[col]++;\n } else if (col in histL) {\n if (++histL[col] >= effc) {\n histG[col] = histL[col];\n }\n } else {\n histL[col] = 1;\n }\n });\n });\n this._hueStats.injectIntoDictionary(histG);\n }\n _iterateBox(bbox, wid, fn) {\n const b = bbox;\n const i0 = b.y * wid + b.x;\n const i1 = (b.y + b.h - 1) * wid + (b.x + b.w - 1);\n const incr = wid - b.w + 1;\n let cnt = 0;\n let i = i0;\n do {\n fn.call(this, i);\n i += ++cnt % b.w === 0 ? incr : 1;\n } while (i <= i1);\n }\n _makeBoxes(width, height, stepX, stepY) {\n const wrem = width % stepX;\n const hrem = height % stepY;\n const xend = width - wrem;\n const yend = height - hrem;\n const boxesArray = [];\n for (let y2 = 0; y2 < height; y2 += stepY) {\n for (let x2 = 0; x2 < width; x2 += stepX) {\n boxesArray.push({\n x: x2,\n y: y2,\n w: x2 === xend ? wrem : stepX,\n h: y2 === yend ? hrem : stepY\n });\n }\n }\n return boxesArray;\n }\n};\nvar ColorHistogram = _ColorHistogram;\n__publicField(ColorHistogram, \"_boxSize\", [64, 64]);\n__publicField(ColorHistogram, \"_boxPixels\", 2);\n__publicField(ColorHistogram, \"_hueGroups\", 10);\n\n// src/palette/rgbquant/rgbquant.ts\nvar RemovedColor = class {\n constructor(index, color, distance) {\n __publicField(this, \"index\");\n __publicField(this, \"color\");\n __publicField(this, \"distance\");\n this.index = index;\n this.color = color;\n this.distance = distance;\n }\n};\nvar RGBQuant = class extends AbstractPaletteQuantizer {\n constructor(colorDistanceCalculator, colors = 256, method = 2) {\n super();\n __publicField(this, \"_colors\");\n __publicField(this, \"_initialDistance\");\n __publicField(this, \"_distanceIncrement\");\n __publicField(this, \"_histogram\");\n __publicField(this, \"_distance\");\n this._distance = colorDistanceCalculator;\n this._colors = colors;\n this._histogram = new ColorHistogram(method, colors);\n this._initialDistance = 0.01;\n this._distanceIncrement = 5e-3;\n }\n sample(image) {\n this._histogram.sample(image);\n }\n *quantize() {\n const idxi32 = this._histogram.getImportanceSortedColorsIDXI32();\n if (idxi32.length === 0) {\n throw new Error(\"No colors in image\");\n }\n yield* this._buildPalette(idxi32);\n }\n *_buildPalette(idxi32) {\n const palette = new Palette();\n const colorArray = palette.getPointContainer().getPointArray();\n const usageArray = new Array(idxi32.length);\n for (let i = 0; i < idxi32.length; i++) {\n colorArray.push(Point.createByUint32(idxi32[i]));\n usageArray[i] = 1;\n }\n const len = colorArray.length;\n const memDist = [];\n let palLen = len;\n let thold = this._initialDistance;\n const tracker = new ProgressTracker(palLen - this._colors, 99);\n while (palLen > this._colors) {\n memDist.length = 0;\n for (let i = 0; i < len; i++) {\n if (tracker.shouldNotify(len - palLen)) {\n yield {\n progress: tracker.progress\n };\n }\n if (usageArray[i] === 0)\n continue;\n const pxi = colorArray[i];\n for (let j = i + 1; j < len; j++) {\n if (usageArray[j] === 0)\n continue;\n const pxj = colorArray[j];\n const dist = this._distance.calculateNormalized(pxi, pxj);\n if (dist < thold) {\n memDist.push(new RemovedColor(j, pxj, dist));\n usageArray[j] = 0;\n palLen--;\n }\n }\n }\n thold += palLen > this._colors * 3 ? this._initialDistance : this._distanceIncrement;\n }\n if (palLen < this._colors) {\n stableSort(memDist, (a, b) => b.distance - a.distance);\n let k = 0;\n while (palLen < this._colors && k < memDist.length) {\n const removedColor = memDist[k];\n usageArray[removedColor.index] = 1;\n palLen++;\n k++;\n }\n }\n let colors = colorArray.length;\n for (let colorIndex = colors - 1; colorIndex >= 0; colorIndex--) {\n if (usageArray[colorIndex] === 0) {\n if (colorIndex !== colors - 1) {\n colorArray[colorIndex] = colorArray[colors - 1];\n }\n --colors;\n }\n }\n colorArray.length = colors;\n palette.sort();\n yield {\n palette,\n progress: 100\n };\n }\n};\n\n// src/palette/wu/wuQuant.ts\nfunction createArray1D(dimension1) {\n const a = [];\n for (let k = 0; k < dimension1; k++) {\n a[k] = 0;\n }\n return a;\n}\nfunction createArray4D(dimension1, dimension2, dimension3, dimension4) {\n const a = new Array(dimension1);\n for (let i = 0; i < dimension1; i++) {\n a[i] = new Array(dimension2);\n for (let j = 0; j < dimension2; j++) {\n a[i][j] = new Array(dimension3);\n for (let k = 0; k < dimension3; k++) {\n a[i][j][k] = new Array(dimension4);\n for (let l = 0; l < dimension4; l++) {\n a[i][j][k][l] = 0;\n }\n }\n }\n }\n return a;\n}\nfunction createArray3D(dimension1, dimension2, dimension3) {\n const a = new Array(dimension1);\n for (let i = 0; i < dimension1; i++) {\n a[i] = new Array(dimension2);\n for (let j = 0; j < dimension2; j++) {\n a[i][j] = new Array(dimension3);\n for (let k = 0; k < dimension3; k++) {\n a[i][j][k] = 0;\n }\n }\n }\n return a;\n}\nfunction fillArray3D(a, dimension1, dimension2, dimension3, value) {\n for (let i = 0; i < dimension1; i++) {\n a[i] = [];\n for (let j = 0; j < dimension2; j++) {\n a[i][j] = [];\n for (let k = 0; k < dimension3; k++) {\n a[i][j][k] = value;\n }\n }\n }\n}\nfunction fillArray1D(a, dimension1, value) {\n for (let i = 0; i < dimension1; i++) {\n a[i] = value;\n }\n}\nvar WuColorCube = class {\n constructor() {\n __publicField(this, \"redMinimum\");\n __publicField(this, \"redMaximum\");\n __publicField(this, \"greenMinimum\");\n __publicField(this, \"greenMaximum\");\n __publicField(this, \"blueMinimum\");\n __publicField(this, \"blueMaximum\");\n __publicField(this, \"volume\");\n __publicField(this, \"alphaMinimum\");\n __publicField(this, \"alphaMaximum\");\n }\n};\nvar _WuQuant = class extends AbstractPaletteQuantizer {\n constructor(colorDistanceCalculator, colors = 256, significantBitsPerChannel = 5) {\n super();\n __publicField(this, \"_reds\");\n __publicField(this, \"_greens\");\n __publicField(this, \"_blues\");\n __publicField(this, \"_alphas\");\n __publicField(this, \"_sums\");\n __publicField(this, \"_weights\");\n __publicField(this, \"_momentsRed\");\n __publicField(this, \"_momentsGreen\");\n __publicField(this, \"_momentsBlue\");\n __publicField(this, \"_momentsAlpha\");\n __publicField(this, \"_moments\");\n __publicField(this, \"_table\");\n __publicField(this, \"_pixels\");\n __publicField(this, \"_cubes\");\n __publicField(this, \"_colors\");\n __publicField(this, \"_significantBitsPerChannel\");\n __publicField(this, \"_maxSideIndex\");\n __publicField(this, \"_alphaMaxSideIndex\");\n __publicField(this, \"_sideSize\");\n __publicField(this, \"_alphaSideSize\");\n __publicField(this, \"_distance\");\n this._distance = colorDistanceCalculator;\n this._setQuality(significantBitsPerChannel);\n this._initialize(colors);\n }\n sample(image) {\n const pointArray = image.getPointArray();\n for (let i = 0, l = pointArray.length; i < l; i++) {\n this._addColor(pointArray[i]);\n }\n this._pixels = this._pixels.concat(pointArray);\n }\n *quantize() {\n yield* this._preparePalette();\n const palette = new Palette();\n for (let paletteIndex = 0; paletteIndex < this._colors; paletteIndex++) {\n if (this._sums[paletteIndex] > 0) {\n const sum = this._sums[paletteIndex];\n const r = this._reds[paletteIndex] / sum;\n const g = this._greens[paletteIndex] / sum;\n const b = this._blues[paletteIndex] / sum;\n const a = this._alphas[paletteIndex] / sum;\n const color = Point.createByRGBA(r | 0, g | 0, b | 0, a | 0);\n palette.add(color);\n }\n }\n palette.sort();\n yield {\n palette,\n progress: 100\n };\n }\n *_preparePalette() {\n yield* this._calculateMoments();\n let next = 0;\n const volumeVariance = createArray1D(this._colors);\n for (let cubeIndex = 1; cubeIndex < this._colors; ++cubeIndex) {\n if (this._cut(this._cubes[next], this._cubes[cubeIndex])) {\n volumeVariance[next] = this._cubes[next].volume > 1 ? this._calculateVariance(this._cubes[next]) : 0;\n volumeVariance[cubeIndex] = this._cubes[cubeIndex].volume > 1 ? this._calculateVariance(this._cubes[cubeIndex]) : 0;\n } else {\n volumeVariance[next] = 0;\n cubeIndex--;\n }\n next = 0;\n let temp = volumeVariance[0];\n for (let index = 1; index <= cubeIndex; ++index) {\n if (volumeVariance[index] > temp) {\n temp = volumeVariance[index];\n next = index;\n }\n }\n if (temp <= 0) {\n this._colors = cubeIndex + 1;\n break;\n }\n }\n const lookupRed = [];\n const lookupGreen = [];\n const lookupBlue = [];\n const lookupAlpha = [];\n for (let k = 0; k < this._colors; ++k) {\n const weight = _WuQuant._volume(this._cubes[k], this._weights);\n if (weight > 0) {\n lookupRed[k] = _WuQuant._volume(this._cubes[k], this._momentsRed) / weight | 0;\n lookupGreen[k] = _WuQuant._volume(this._cubes[k], this._momentsGreen) / weight | 0;\n lookupBlue[k] = _WuQuant._volume(this._cubes[k], this._momentsBlue) / weight | 0;\n lookupAlpha[k] = _WuQuant._volume(this._cubes[k], this._momentsAlpha) / weight | 0;\n } else {\n lookupRed[k] = 0;\n lookupGreen[k] = 0;\n lookupBlue[k] = 0;\n lookupAlpha[k] = 0;\n }\n }\n this._reds = createArray1D(this._colors + 1);\n this._greens = createArray1D(this._colors + 1);\n this._blues = createArray1D(this._colors + 1);\n this._alphas = createArray1D(this._colors + 1);\n this._sums = createArray1D(this._colors + 1);\n for (let index = 0, l = this._pixels.length; index < l; index++) {\n const color = this._pixels[index];\n const match = -1;\n let bestMatch = match;\n let bestDistance = Number.MAX_VALUE;\n for (let lookup = 0; lookup < this._colors; lookup++) {\n const foundRed = lookupRed[lookup];\n const foundGreen = lookupGreen[lookup];\n const foundBlue = lookupBlue[lookup];\n const foundAlpha = lookupAlpha[lookup];\n const distance = this._distance.calculateRaw(foundRed, foundGreen, foundBlue, foundAlpha, color.r, color.g, color.b, color.a);\n if (distance < bestDistance) {\n bestDistance = distance;\n bestMatch = lookup;\n }\n }\n this._reds[bestMatch] += color.r;\n this._greens[bestMatch] += color.g;\n this._blues[bestMatch] += color.b;\n this._alphas[bestMatch] += color.a;\n this._sums[bestMatch]++;\n }\n }\n _addColor(color) {\n const bitsToRemove = 8 - this._significantBitsPerChannel;\n const indexRed = (color.r >> bitsToRemove) + 1;\n const indexGreen = (color.g >> bitsToRemove) + 1;\n const indexBlue = (color.b >> bitsToRemove) + 1;\n const indexAlpha = (color.a >> bitsToRemove) + 1;\n this._weights[indexAlpha][indexRed][indexGreen][indexBlue]++;\n this._momentsRed[indexAlpha][indexRed][indexGreen][indexBlue] += color.r;\n this._momentsGreen[indexAlpha][indexRed][indexGreen][indexBlue] += color.g;\n this._momentsBlue[indexAlpha][indexRed][indexGreen][indexBlue] += color.b;\n this._momentsAlpha[indexAlpha][indexRed][indexGreen][indexBlue] += color.a;\n this._moments[indexAlpha][indexRed][indexGreen][indexBlue] += this._table[color.r] + this._table[color.g] + this._table[color.b] + this._table[color.a];\n }\n *_calculateMoments() {\n const area = [];\n const areaRed = [];\n const areaGreen = [];\n const areaBlue = [];\n const areaAlpha = [];\n const area2 = [];\n const xarea = createArray3D(this._sideSize, this._sideSize, this._sideSize);\n const xareaRed = createArray3D(this._sideSize, this._sideSize, this._sideSize);\n const xareaGreen = createArray3D(this._sideSize, this._sideSize, this._sideSize);\n const xareaBlue = createArray3D(this._sideSize, this._sideSize, this._sideSize);\n const xareaAlpha = createArray3D(this._sideSize, this._sideSize, this._sideSize);\n const xarea2 = createArray3D(this._sideSize, this._sideSize, this._sideSize);\n let trackerProgress = 0;\n const tracker = new ProgressTracker(this._alphaMaxSideIndex * this._maxSideIndex, 99);\n for (let alphaIndex = 1; alphaIndex <= this._alphaMaxSideIndex; ++alphaIndex) {\n fillArray3D(xarea, this._sideSize, this._sideSize, this._sideSize, 0);\n fillArray3D(xareaRed, this._sideSize, this._sideSize, this._sideSize, 0);\n fillArray3D(xareaGreen, this._sideSize, this._sideSize, this._sideSize, 0);\n fillArray3D(xareaBlue, this._sideSize, this._sideSize, this._sideSize, 0);\n fillArray3D(xareaAlpha, this._sideSize, this._sideSize, this._sideSize, 0);\n fillArray3D(xarea2, this._sideSize, this._sideSize, this._sideSize, 0);\n for (let redIndex = 1; redIndex <= this._maxSideIndex; ++redIndex, ++trackerProgress) {\n if (tracker.shouldNotify(trackerProgress)) {\n yield {\n progress: tracker.progress\n };\n }\n fillArray1D(area, this._sideSize, 0);\n fillArray1D(areaRed, this._sideSize, 0);\n fillArray1D(areaGreen, this._sideSize, 0);\n fillArray1D(areaBlue, this._sideSize, 0);\n fillArray1D(areaAlpha, this._sideSize, 0);\n fillArray1D(area2, this._sideSize, 0);\n for (let greenIndex = 1; greenIndex <= this._maxSideIndex; ++greenIndex) {\n let line = 0;\n let lineRed = 0;\n let lineGreen = 0;\n let lineBlue = 0;\n let lineAlpha = 0;\n let line2 = 0;\n for (let blueIndex = 1; blueIndex <= this._maxSideIndex; ++blueIndex) {\n line += this._weights[alphaIndex][redIndex][greenIndex][blueIndex];\n lineRed += this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex];\n lineGreen += this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex];\n lineBlue += this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex];\n lineAlpha += this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex];\n line2 += this._moments[alphaIndex][redIndex][greenIndex][blueIndex];\n area[blueIndex] += line;\n areaRed[blueIndex] += lineRed;\n areaGreen[blueIndex] += lineGreen;\n areaBlue[blueIndex] += lineBlue;\n areaAlpha[blueIndex] += lineAlpha;\n area2[blueIndex] += line2;\n xarea[redIndex][greenIndex][blueIndex] = xarea[redIndex - 1][greenIndex][blueIndex] + area[blueIndex];\n xareaRed[redIndex][greenIndex][blueIndex] = xareaRed[redIndex - 1][greenIndex][blueIndex] + areaRed[blueIndex];\n xareaGreen[redIndex][greenIndex][blueIndex] = xareaGreen[redIndex - 1][greenIndex][blueIndex] + areaGreen[blueIndex];\n xareaBlue[redIndex][greenIndex][blueIndex] = xareaBlue[redIndex - 1][greenIndex][blueIndex] + areaBlue[blueIndex];\n xareaAlpha[redIndex][greenIndex][blueIndex] = xareaAlpha[redIndex - 1][greenIndex][blueIndex] + areaAlpha[blueIndex];\n xarea2[redIndex][greenIndex][blueIndex] = xarea2[redIndex - 1][greenIndex][blueIndex] + area2[blueIndex];\n this._weights[alphaIndex][redIndex][greenIndex][blueIndex] = this._weights[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xarea[redIndex][greenIndex][blueIndex];\n this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsRed[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaRed[redIndex][greenIndex][blueIndex];\n this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsGreen[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaGreen[redIndex][greenIndex][blueIndex];\n this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsBlue[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaBlue[redIndex][greenIndex][blueIndex];\n this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex] = this._momentsAlpha[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xareaAlpha[redIndex][greenIndex][blueIndex];\n this._moments[alphaIndex][redIndex][greenIndex][blueIndex] = this._moments[alphaIndex - 1][redIndex][greenIndex][blueIndex] + xarea2[redIndex][greenIndex][blueIndex];\n }\n }\n }\n }\n }\n static _volumeFloat(cube, moment) {\n return moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);\n }\n static _volume(cube, moment) {\n return _WuQuant._volumeFloat(cube, moment) | 0;\n }\n static _top(cube, direction, position, moment) {\n let result;\n switch (direction) {\n case _WuQuant._alpha:\n result = moment[position][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] - moment[position][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[position][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[position][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (moment[position][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] - moment[position][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[position][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[position][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);\n break;\n case _WuQuant._red:\n result = moment[cube.alphaMaximum][position][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMaximum][position][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][position][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][position][cube.greenMinimum][cube.blueMaximum] - (moment[cube.alphaMaximum][position][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][position][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][position][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][position][cube.greenMinimum][cube.blueMinimum]);\n break;\n case _WuQuant._green:\n result = moment[cube.alphaMaximum][cube.redMaximum][position][cube.blueMaximum] - moment[cube.alphaMaximum][cube.redMinimum][position][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMaximum][position][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][position][cube.blueMaximum] - (moment[cube.alphaMaximum][cube.redMaximum][position][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][position][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMaximum][position][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][position][cube.blueMinimum]);\n break;\n case _WuQuant._blue:\n result = moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][position] - moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][position] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][position] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][position] - (moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][position] - moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][position] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][position] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][position]);\n break;\n default:\n throw new Error(\"impossible\");\n }\n return result | 0;\n }\n static _bottom(cube, direction, moment) {\n switch (direction) {\n case _WuQuant._alpha:\n return -moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);\n case _WuQuant._red:\n return -moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);\n case _WuQuant._green:\n return -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMaximum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMaximum] - (-moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);\n case _WuQuant._blue:\n return -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum] - (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][cube.blueMinimum] + moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][cube.blueMinimum] - moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][cube.blueMinimum]);\n default:\n return 0;\n }\n }\n _calculateVariance(cube) {\n const volumeRed = _WuQuant._volume(cube, this._momentsRed);\n const volumeGreen = _WuQuant._volume(cube, this._momentsGreen);\n const volumeBlue = _WuQuant._volume(cube, this._momentsBlue);\n const volumeAlpha = _WuQuant._volume(cube, this._momentsAlpha);\n const volumeMoment = _WuQuant._volumeFloat(cube, this._moments);\n const volumeWeight = _WuQuant._volume(cube, this._weights);\n const distance = volumeRed * volumeRed + volumeGreen * volumeGreen + volumeBlue * volumeBlue + volumeAlpha * volumeAlpha;\n return volumeMoment - distance / volumeWeight;\n }\n _maximize(cube, direction, first, last, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight) {\n const bottomRed = _WuQuant._bottom(cube, direction, this._momentsRed) | 0;\n const bottomGreen = _WuQuant._bottom(cube, direction, this._momentsGreen) | 0;\n const bottomBlue = _WuQuant._bottom(cube, direction, this._momentsBlue) | 0;\n const bottomAlpha = _WuQuant._bottom(cube, direction, this._momentsAlpha) | 0;\n const bottomWeight = _WuQuant._bottom(cube, direction, this._weights) | 0;\n let result = 0;\n let cutPosition = -1;\n for (let position = first; position < last; ++position) {\n let halfRed = bottomRed + _WuQuant._top(cube, direction, position, this._momentsRed);\n let halfGreen = bottomGreen + _WuQuant._top(cube, direction, position, this._momentsGreen);\n let halfBlue = bottomBlue + _WuQuant._top(cube, direction, position, this._momentsBlue);\n let halfAlpha = bottomAlpha + _WuQuant._top(cube, direction, position, this._momentsAlpha);\n let halfWeight = bottomWeight + _WuQuant._top(cube, direction, position, this._weights);\n if (halfWeight !== 0) {\n let halfDistance = halfRed * halfRed + halfGreen * halfGreen + halfBlue * halfBlue + halfAlpha * halfAlpha;\n let temp = halfDistance / halfWeight;\n halfRed = wholeRed - halfRed;\n halfGreen = wholeGreen - halfGreen;\n halfBlue = wholeBlue - halfBlue;\n halfAlpha = wholeAlpha - halfAlpha;\n halfWeight = wholeWeight - halfWeight;\n if (halfWeight !== 0) {\n halfDistance = halfRed * halfRed + halfGreen * halfGreen + halfBlue * halfBlue + halfAlpha * halfAlpha;\n temp += halfDistance / halfWeight;\n if (temp > result) {\n result = temp;\n cutPosition = position;\n }\n }\n }\n }\n return { max: result, position: cutPosition };\n }\n _cut(first, second) {\n let direction;\n const wholeRed = _WuQuant._volume(first, this._momentsRed);\n const wholeGreen = _WuQuant._volume(first, this._momentsGreen);\n const wholeBlue = _WuQuant._volume(first, this._momentsBlue);\n const wholeAlpha = _WuQuant._volume(first, this._momentsAlpha);\n const wholeWeight = _WuQuant._volume(first, this._weights);\n const red = this._maximize(first, _WuQuant._red, first.redMinimum + 1, first.redMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);\n const green = this._maximize(first, _WuQuant._green, first.greenMinimum + 1, first.greenMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);\n const blue = this._maximize(first, _WuQuant._blue, first.blueMinimum + 1, first.blueMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);\n const alpha = this._maximize(first, _WuQuant._alpha, first.alphaMinimum + 1, first.alphaMaximum, wholeRed, wholeGreen, wholeBlue, wholeAlpha, wholeWeight);\n if (alpha.max >= red.max && alpha.max >= green.max && alpha.max >= blue.max) {\n direction = _WuQuant._alpha;\n if (alpha.position < 0)\n return false;\n } else if (red.max >= alpha.max && red.max >= green.max && red.max >= blue.max) {\n direction = _WuQuant._red;\n } else if (green.max >= alpha.max && green.max >= red.max && green.max >= blue.max) {\n direction = _WuQuant._green;\n } else {\n direction = _WuQuant._blue;\n }\n second.redMaximum = first.redMaximum;\n second.greenMaximum = first.greenMaximum;\n second.blueMaximum = first.blueMaximum;\n second.alphaMaximum = first.alphaMaximum;\n switch (direction) {\n case _WuQuant._red:\n second.redMinimum = first.redMaximum = red.position;\n second.greenMinimum = first.greenMinimum;\n second.blueMinimum = first.blueMinimum;\n second.alphaMinimum = first.alphaMinimum;\n break;\n case _WuQuant._green:\n second.greenMinimum = first.greenMaximum = green.position;\n second.redMinimum = first.redMinimum;\n second.blueMinimum = first.blueMinimum;\n second.alphaMinimum = first.alphaMinimum;\n break;\n case _WuQuant._blue:\n second.blueMinimum = first.blueMaximum = blue.position;\n second.redMinimum = first.redMinimum;\n second.greenMinimum = first.greenMinimum;\n second.alphaMinimum = first.alphaMinimum;\n break;\n case _WuQuant._alpha:\n second.alphaMinimum = first.alphaMaximum = alpha.position;\n second.blueMinimum = first.blueMinimum;\n second.redMinimum = first.redMinimum;\n second.greenMinimum = first.greenMinimum;\n break;\n }\n first.volume = (first.redMaximum - first.redMinimum) * (first.greenMaximum - first.greenMinimum) * (first.blueMaximum - first.blueMinimum) * (first.alphaMaximum - first.alphaMinimum);\n second.volume = (second.redMaximum - second.redMinimum) * (second.greenMaximum - second.greenMinimum) * (second.blueMaximum - second.blueMinimum) * (second.alphaMaximum - second.alphaMinimum);\n return true;\n }\n _initialize(colors) {\n this._colors = colors;\n this._cubes = [];\n for (let cubeIndex = 0; cubeIndex < colors; cubeIndex++) {\n this._cubes[cubeIndex] = new WuColorCube();\n }\n this._cubes[0].redMinimum = 0;\n this._cubes[0].greenMinimum = 0;\n this._cubes[0].blueMinimum = 0;\n this._cubes[0].alphaMinimum = 0;\n this._cubes[0].redMaximum = this._maxSideIndex;\n this._cubes[0].greenMaximum = this._maxSideIndex;\n this._cubes[0].blueMaximum = this._maxSideIndex;\n this._cubes[0].alphaMaximum = this._alphaMaxSideIndex;\n this._weights = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);\n this._momentsRed = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);\n this._momentsGreen = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);\n this._momentsBlue = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);\n this._momentsAlpha = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);\n this._moments = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize);\n this._table = [];\n for (let tableIndex = 0; tableIndex < 256; ++tableIndex) {\n this._table[tableIndex] = tableIndex * tableIndex;\n }\n this._pixels = [];\n }\n _setQuality(significantBitsPerChannel = 5) {\n this._significantBitsPerChannel = significantBitsPerChannel;\n this._maxSideIndex = 1 << this._significantBitsPerChannel;\n this._alphaMaxSideIndex = this._maxSideIndex;\n this._sideSize = this._maxSideIndex + 1;\n this._alphaSideSize = this._alphaMaxSideIndex + 1;\n }\n};\nvar WuQuant = _WuQuant;\n__publicField(WuQuant, \"_alpha\", 3);\n__publicField(WuQuant, \"_red\", 2);\n__publicField(WuQuant, \"_green\", 1);\n__publicField(WuQuant, \"_blue\", 0);\n\n// src/image/index.ts\nvar image_exports = {};\n__export(image_exports, {\n AbstractImageQuantizer: () => AbstractImageQuantizer,\n ErrorDiffusionArray: () => ErrorDiffusionArray,\n ErrorDiffusionArrayKernel: () => ErrorDiffusionArrayKernel,\n ErrorDiffusionRiemersma: () => ErrorDiffusionRiemersma,\n NearestColor: () => NearestColor\n});\n\n// src/image/imageQuantizer.ts\nvar AbstractImageQuantizer = class {\n quantizeSync(pointContainer, palette) {\n for (const value of this.quantize(pointContainer, palette)) {\n if (value.pointContainer) {\n return value.pointContainer;\n }\n }\n throw new Error(\"unreachable\");\n }\n};\n\n// src/image/nearestColor.ts\nvar NearestColor = class extends AbstractImageQuantizer {\n constructor(colorDistanceCalculator) {\n super();\n __publicField(this, \"_distance\");\n this._distance = colorDistanceCalculator;\n }\n *quantize(pointContainer, palette) {\n const pointArray = pointContainer.getPointArray();\n const width = pointContainer.getWidth();\n const height = pointContainer.getHeight();\n const tracker = new ProgressTracker(height, 99);\n for (let y2 = 0; y2 < height; y2++) {\n if (tracker.shouldNotify(y2)) {\n yield {\n progress: tracker.progress\n };\n }\n for (let x2 = 0, idx = y2 * width; x2 < width; x2++, idx++) {\n const point = pointArray[idx];\n point.from(palette.getNearestColor(this._distance, point));\n }\n }\n yield {\n pointContainer,\n progress: 100\n };\n }\n};\n\n// src/image/array.ts\nvar ErrorDiffusionArrayKernel = /* @__PURE__ */ ((ErrorDiffusionArrayKernel2) => {\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"FloydSteinberg\"] = 0] = \"FloydSteinberg\";\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"FalseFloydSteinberg\"] = 1] = \"FalseFloydSteinberg\";\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"Stucki\"] = 2] = \"Stucki\";\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"Atkinson\"] = 3] = \"Atkinson\";\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"Jarvis\"] = 4] = \"Jarvis\";\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"Burkes\"] = 5] = \"Burkes\";\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"Sierra\"] = 6] = \"Sierra\";\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"TwoSierra\"] = 7] = \"TwoSierra\";\n ErrorDiffusionArrayKernel2[ErrorDiffusionArrayKernel2[\"SierraLite\"] = 8] = \"SierraLite\";\n return ErrorDiffusionArrayKernel2;\n})(ErrorDiffusionArrayKernel || {});\nvar ErrorDiffusionArray = class extends AbstractImageQuantizer {\n constructor(colorDistanceCalculator, kernel, serpentine = true, minimumColorDistanceToDither = 0, calculateErrorLikeGIMP = false) {\n super();\n __publicField(this, \"_minColorDistance\");\n __publicField(this, \"_serpentine\");\n __publicField(this, \"_kernel\");\n __publicField(this, \"_calculateErrorLikeGIMP\");\n __publicField(this, \"_distance\");\n this._setKernel(kernel);\n this._distance = colorDistanceCalculator;\n this._minColorDistance = minimumColorDistanceToDither;\n this._serpentine = serpentine;\n this._calculateErrorLikeGIMP = calculateErrorLikeGIMP;\n }\n *quantize(pointContainer, palette) {\n const pointArray = pointContainer.getPointArray();\n const originalPoint = new Point();\n const width = pointContainer.getWidth();\n const height = pointContainer.getHeight();\n const errorLines = [];\n let dir = 1;\n let maxErrorLines = 1;\n for (const kernel of this._kernel) {\n const kernelErrorLines = kernel[2] + 1;\n if (maxErrorLines < kernelErrorLines)\n maxErrorLines = kernelErrorLines;\n }\n for (let i = 0; i < maxErrorLines; i++) {\n this._fillErrorLine(errorLines[i] = [], width);\n }\n const tracker = new ProgressTracker(height, 99);\n for (let y2 = 0; y2 < height; y2++) {\n if (tracker.shouldNotify(y2)) {\n yield {\n progress: tracker.progress\n };\n }\n if (this._serpentine)\n dir *= -1;\n const lni = y2 * width;\n const xStart = dir === 1 ? 0 : width - 1;\n const xEnd = dir === 1 ? width : -1;\n this._fillErrorLine(errorLines[0], width);\n errorLines.push(errorLines.shift());\n const errorLine = errorLines[0];\n for (let x2 = xStart, idx = lni + xStart; x2 !== xEnd; x2 += dir, idx += dir) {\n const point = pointArray[idx];\n const error = errorLine[x2];\n originalPoint.from(point);\n const correctedPoint = Point.createByRGBA(inRange0to255Rounded(point.r + error[0]), inRange0to255Rounded(point.g + error[1]), inRange0to255Rounded(point.b + error[2]), inRange0to255Rounded(point.a + error[3]));\n const palettePoint = palette.getNearestColor(this._distance, correctedPoint);\n point.from(palettePoint);\n if (this._minColorDistance) {\n const dist = this._distance.calculateNormalized(originalPoint, palettePoint);\n if (dist < this._minColorDistance)\n continue;\n }\n let er;\n let eg;\n let eb;\n let ea;\n if (this._calculateErrorLikeGIMP) {\n er = correctedPoint.r - palettePoint.r;\n eg = correctedPoint.g - palettePoint.g;\n eb = correctedPoint.b - palettePoint.b;\n ea = correctedPoint.a - palettePoint.a;\n } else {\n er = originalPoint.r - palettePoint.r;\n eg = originalPoint.g - palettePoint.g;\n eb = originalPoint.b - palettePoint.b;\n ea = originalPoint.a - palettePoint.a;\n }\n const dStart = dir === 1 ? 0 : this._kernel.length - 1;\n const dEnd = dir === 1 ? this._kernel.length : -1;\n for (let i = dStart; i !== dEnd; i += dir) {\n const x1 = this._kernel[i][1] * dir;\n const y1 = this._kernel[i][2];\n if (x1 + x2 >= 0 && x1 + x2 < width && y1 + y2 >= 0 && y1 + y2 < height) {\n const d = this._kernel[i][0];\n const e = errorLines[y1][x1 + x2];\n e[0] += er * d;\n e[1] += eg * d;\n e[2] += eb * d;\n e[3] += ea * d;\n }\n }\n }\n }\n yield {\n pointContainer,\n progress: 100\n };\n }\n _fillErrorLine(errorLine, width) {\n if (errorLine.length > width) {\n errorLine.length = width;\n }\n const l = errorLine.length;\n for (let i = 0; i < l; i++) {\n const error = errorLine[i];\n error[0] = error[1] = error[2] = error[3] = 0;\n }\n for (let i = l; i < width; i++) {\n errorLine[i] = [0, 0, 0, 0];\n }\n }\n _setKernel(kernel) {\n switch (kernel) {\n case 0 /* FloydSteinberg */:\n this._kernel = [\n [7 / 16, 1, 0],\n [3 / 16, -1, 1],\n [5 / 16, 0, 1],\n [1 / 16, 1, 1]\n ];\n break;\n case 1 /* FalseFloydSteinberg */:\n this._kernel = [\n [3 / 8, 1, 0],\n [3 / 8, 0, 1],\n [2 / 8, 1, 1]\n ];\n break;\n case 2 /* Stucki */:\n this._kernel = [\n [8 / 42, 1, 0],\n [4 / 42, 2, 0],\n [2 / 42, -2, 1],\n [4 / 42, -1, 1],\n [8 / 42, 0, 1],\n [4 / 42, 1, 1],\n [2 / 42, 2, 1],\n [1 / 42, -2, 2],\n [2 / 42, -1, 2],\n [4 / 42, 0, 2],\n [2 / 42, 1, 2],\n [1 / 42, 2, 2]\n ];\n break;\n case 3 /* Atkinson */:\n this._kernel = [\n [1 / 8, 1, 0],\n [1 / 8, 2, 0],\n [1 / 8, -1, 1],\n [1 / 8, 0, 1],\n [1 / 8, 1, 1],\n [1 / 8, 0, 2]\n ];\n break;\n case 4 /* Jarvis */:\n this._kernel = [\n [7 / 48, 1, 0],\n [5 / 48, 2, 0],\n [3 / 48, -2, 1],\n [5 / 48, -1, 1],\n [7 / 48, 0, 1],\n [5 / 48, 1, 1],\n [3 / 48, 2, 1],\n [1 / 48, -2, 2],\n [3 / 48, -1, 2],\n [5 / 48, 0, 2],\n [3 / 48, 1, 2],\n [1 / 48, 2, 2]\n ];\n break;\n case 5 /* Burkes */:\n this._kernel = [\n [8 / 32, 1, 0],\n [4 / 32, 2, 0],\n [2 / 32, -2, 1],\n [4 / 32, -1, 1],\n [8 / 32, 0, 1],\n [4 / 32, 1, 1],\n [2 / 32, 2, 1]\n ];\n break;\n case 6 /* Sierra */:\n this._kernel = [\n [5 / 32, 1, 0],\n [3 / 32, 2, 0],\n [2 / 32, -2, 1],\n [4 / 32, -1, 1],\n [5 / 32, 0, 1],\n [4 / 32, 1, 1],\n [2 / 32, 2, 1],\n [2 / 32, -1, 2],\n [3 / 32, 0, 2],\n [2 / 32, 1, 2]\n ];\n break;\n case 7 /* TwoSierra */:\n this._kernel = [\n [4 / 16, 1, 0],\n [3 / 16, 2, 0],\n [1 / 16, -2, 1],\n [2 / 16, -1, 1],\n [3 / 16, 0, 1],\n [2 / 16, 1, 1],\n [1 / 16, 2, 1]\n ];\n break;\n case 8 /* SierraLite */:\n this._kernel = [\n [2 / 4, 1, 0],\n [1 / 4, -1, 1],\n [1 / 4, 0, 1]\n ];\n break;\n default:\n throw new Error(`ErrorDiffusionArray: unknown kernel = ${kernel}`);\n }\n }\n};\n\n// src/image/spaceFillingCurves/hilbertCurve.ts\nfunction* hilbertCurve(width, height, callback) {\n const maxBound = Math.max(width, height);\n const level = Math.floor(Math.log(maxBound) / Math.log(2) + 1);\n const tracker = new ProgressTracker(width * height, 99);\n const data = {\n width,\n height,\n level,\n callback,\n tracker,\n index: 0,\n x: 0,\n y: 0\n };\n yield* walkHilbert(data, 1 /* UP */);\n visit(data, 0 /* NONE */);\n}\nfunction* walkHilbert(data, direction) {\n if (data.level < 1)\n return;\n if (data.tracker.shouldNotify(data.index)) {\n yield { progress: data.tracker.progress };\n }\n data.level--;\n switch (direction) {\n case 2 /* LEFT */:\n yield* walkHilbert(data, 1 /* UP */);\n visit(data, 3 /* RIGHT */);\n yield* walkHilbert(data, 2 /* LEFT */);\n visit(data, 4 /* DOWN */);\n yield* walkHilbert(data, 2 /* LEFT */);\n visit(data, 2 /* LEFT */);\n yield* walkHilbert(data, 4 /* DOWN */);\n break;\n case 3 /* RIGHT */:\n yield* walkHilbert(data, 4 /* DOWN */);\n visit(data, 2 /* LEFT */);\n yield* walkHilbert(data, 3 /* RIGHT */);\n visit(data, 1 /* UP */);\n yield* walkHilbert(data, 3 /* RIGHT */);\n visit(data, 3 /* RIGHT */);\n yield* walkHilbert(data, 1 /* UP */);\n break;\n case 1 /* UP */:\n yield* walkHilbert(data, 2 /* LEFT */);\n visit(data, 4 /* DOWN */);\n yield* walkHilbert(data, 1 /* UP */);\n visit(data, 3 /* RIGHT */);\n yield* walkHilbert(data, 1 /* UP */);\n visit(data, 1 /* UP */);\n yield* walkHilbert(data, 3 /* RIGHT */);\n break;\n case 4 /* DOWN */:\n yield* walkHilbert(data, 3 /* RIGHT */);\n visit(data, 1 /* UP */);\n yield* walkHilbert(data, 4 /* DOWN */);\n visit(data, 2 /* LEFT */);\n yield* walkHilbert(data, 4 /* DOWN */);\n visit(data, 4 /* DOWN */);\n yield* walkHilbert(data, 2 /* LEFT */);\n break;\n default:\n break;\n }\n data.level++;\n}\nfunction visit(data, direction) {\n if (data.x >= 0 && data.x < data.width && data.y >= 0 && data.y < data.height) {\n data.callback(data.x, data.y);\n data.index++;\n }\n switch (direction) {\n case 2 /* LEFT */:\n data.x--;\n break;\n case 3 /* RIGHT */:\n data.x++;\n break;\n case 1 /* UP */:\n data.y--;\n break;\n case 4 /* DOWN */:\n data.y++;\n break;\n }\n}\n\n// src/image/riemersma.ts\nvar ErrorDiffusionRiemersma = class extends AbstractImageQuantizer {\n constructor(colorDistanceCalculator, errorQueueSize = 16, errorPropagation = 1) {\n super();\n __publicField(this, \"_distance\");\n __publicField(this, \"_weights\");\n __publicField(this, \"_errorQueueSize\");\n this._distance = colorDistanceCalculator;\n this._errorQueueSize = errorQueueSize;\n this._weights = ErrorDiffusionRiemersma._createWeights(errorPropagation, errorQueueSize);\n }\n *quantize(pointContainer, palette) {\n const pointArray = pointContainer.getPointArray();\n const width = pointContainer.getWidth();\n const height = pointContainer.getHeight();\n const errorQueue = [];\n let head = 0;\n for (let i = 0; i < this._errorQueueSize; i++) {\n errorQueue[i] = { r: 0, g: 0, b: 0, a: 0 };\n }\n yield* hilbertCurve(width, height, (x2, y2) => {\n const p = pointArray[x2 + y2 * width];\n let { r, g, b, a } = p;\n for (let i = 0; i < this._errorQueueSize; i++) {\n const weight = this._weights[i];\n const e = errorQueue[(i + head) % this._errorQueueSize];\n r += e.r * weight;\n g += e.g * weight;\n b += e.b * weight;\n a += e.a * weight;\n }\n const correctedPoint = Point.createByRGBA(inRange0to255Rounded(r), inRange0to255Rounded(g), inRange0to255Rounded(b), inRange0to255Rounded(a));\n const quantizedPoint = palette.getNearestColor(this._distance, correctedPoint);\n head = (head + 1) % this._errorQueueSize;\n const tail = (head + this._errorQueueSize - 1) % this._errorQueueSize;\n errorQueue[tail].r = p.r - quantizedPoint.r;\n errorQueue[tail].g = p.g - quantizedPoint.g;\n errorQueue[tail].b = p.b - quantizedPoint.b;\n errorQueue[tail].a = p.a - quantizedPoint.a;\n p.from(quantizedPoint);\n });\n yield {\n pointContainer,\n progress: 100\n };\n }\n static _createWeights(errorPropagation, errorQueueSize) {\n const weights = [];\n const multiplier = Math.exp(Math.log(errorQueueSize) / (errorQueueSize - 1));\n for (let i = 0, next = 1; i < errorQueueSize; i++) {\n weights[i] = (next + 0.5 | 0) / errorQueueSize * errorPropagation;\n next *= multiplier;\n }\n return weights;\n }\n};\n\n// src/quality/index.ts\nvar quality_exports = {};\n__export(quality_exports, {\n ssim: () => ssim\n});\n\n// src/quality/ssim.ts\nvar K1 = 0.01;\nvar K2 = 0.03;\nfunction ssim(image1, image2) {\n if (image1.getHeight() !== image2.getHeight() || image1.getWidth() !== image2.getWidth()) {\n throw new Error(\"Images have different sizes!\");\n }\n const bitsPerComponent = 8;\n const L = (1 << bitsPerComponent) - 1;\n const c1 = (K1 * L) ** 2;\n const c2 = (K2 * L) ** 2;\n let numWindows = 0;\n let mssim = 0;\n iterate(image1, image2, (lumaValues1, lumaValues2, averageLumaValue1, averageLumaValue2) => {\n let sigxy = 0;\n let sigsqx = 0;\n let sigsqy = 0;\n for (let i = 0; i < lumaValues1.length; i++) {\n sigsqx += (lumaValues1[i] - averageLumaValue1) ** 2;\n sigsqy += (lumaValues2[i] - averageLumaValue2) ** 2;\n sigxy += (lumaValues1[i] - averageLumaValue1) * (lumaValues2[i] - averageLumaValue2);\n }\n const numPixelsInWin = lumaValues1.length - 1;\n sigsqx /= numPixelsInWin;\n sigsqy /= numPixelsInWin;\n sigxy /= numPixelsInWin;\n const numerator = (2 * averageLumaValue1 * averageLumaValue2 + c1) * (2 * sigxy + c2);\n const denominator = (averageLumaValue1 ** 2 + averageLumaValue2 ** 2 + c1) * (sigsqx + sigsqy + c2);\n const ssim2 = numerator / denominator;\n mssim += ssim2;\n numWindows++;\n });\n return mssim / numWindows;\n}\nfunction iterate(image1, image2, callback) {\n const windowSize = 8;\n const width = image1.getWidth();\n const height = image1.getHeight();\n for (let y2 = 0; y2 < height; y2 += windowSize) {\n for (let x2 = 0; x2 < width; x2 += windowSize) {\n const windowWidth = Math.min(windowSize, width - x2);\n const windowHeight = Math.min(windowSize, height - y2);\n const lumaValues1 = calculateLumaValuesForWindow(image1, x2, y2, windowWidth, windowHeight);\n const lumaValues2 = calculateLumaValuesForWindow(image2, x2, y2, windowWidth, windowHeight);\n const averageLuma1 = calculateAverageLuma(lumaValues1);\n const averageLuma2 = calculateAverageLuma(lumaValues2);\n callback(lumaValues1, lumaValues2, averageLuma1, averageLuma2);\n }\n }\n}\nfunction calculateLumaValuesForWindow(image, x2, y2, width, height) {\n const pointArray = image.getPointArray();\n const lumaValues = [];\n let counter = 0;\n for (let j = y2; j < y2 + height; j++) {\n const offset = j * image.getWidth();\n for (let i = x2; i < x2 + width; i++) {\n const point = pointArray[offset + i];\n lumaValues[counter] = point.r * 0.2126 /* RED */ + point.g * 0.7152 /* GREEN */ + point.b * 0.0722 /* BLUE */;\n counter++;\n }\n }\n return lumaValues;\n}\nfunction calculateAverageLuma(lumaValues) {\n let sumLuma = 0;\n for (const luma of lumaValues) {\n sumLuma += luma;\n }\n return sumLuma / lumaValues.length;\n}\n\n// src/basicAPI.ts\nvar setImmediateImpl = typeof setImmediate === \"function\" ? setImmediate : typeof process !== \"undefined\" && typeof (process == null ? void 0 : process.nextTick) === \"function\" ? (callback) => process.nextTick(callback) : (callback) => setTimeout(callback, 0);\nfunction buildPaletteSync(images, {\n colorDistanceFormula,\n paletteQuantization,\n colors\n} = {}) {\n const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);\n const paletteQuantizer = paletteQuantizationToPaletteQuantizer(distanceCalculator, paletteQuantization, colors);\n images.forEach((image) => paletteQuantizer.sample(image));\n return paletteQuantizer.quantizeSync();\n}\nasync function buildPalette(images, {\n colorDistanceFormula,\n paletteQuantization,\n colors,\n onProgress\n} = {}) {\n return new Promise((resolve, reject) => {\n const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);\n const paletteQuantizer = paletteQuantizationToPaletteQuantizer(distanceCalculator, paletteQuantization, colors);\n images.forEach((image) => paletteQuantizer.sample(image));\n let palette;\n const iterator = paletteQuantizer.quantize();\n const next = () => {\n try {\n const result = iterator.next();\n if (result.done) {\n resolve(palette);\n } else {\n if (result.value.palette)\n palette = result.value.palette;\n if (onProgress)\n onProgress(result.value.progress);\n setImmediateImpl(next);\n }\n } catch (error) {\n reject(error);\n }\n };\n setImmediateImpl(next);\n });\n}\nfunction applyPaletteSync(image, palette, { colorDistanceFormula, imageQuantization } = {}) {\n const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);\n const imageQuantizer = imageQuantizationToImageQuantizer(distanceCalculator, imageQuantization);\n return imageQuantizer.quantizeSync(image, palette);\n}\nasync function applyPalette(image, palette, {\n colorDistanceFormula,\n imageQuantization,\n onProgress\n} = {}) {\n return new Promise((resolve, reject) => {\n const distanceCalculator = colorDistanceFormulaToColorDistance(colorDistanceFormula);\n const imageQuantizer = imageQuantizationToImageQuantizer(distanceCalculator, imageQuantization);\n let outPointContainer;\n const iterator = imageQuantizer.quantize(image, palette);\n const next = () => {\n try {\n const result = iterator.next();\n if (result.done) {\n resolve(outPointContainer);\n } else {\n if (result.value.pointContainer) {\n outPointContainer = result.value.pointContainer;\n }\n if (onProgress)\n onProgress(result.value.progress);\n setImmediateImpl(next);\n }\n } catch (error) {\n reject(error);\n }\n };\n setImmediateImpl(next);\n });\n}\nfunction colorDistanceFormulaToColorDistance(colorDistanceFormula = \"euclidean-bt709\") {\n switch (colorDistanceFormula) {\n case \"cie94-graphic-arts\":\n return new CIE94GraphicArts();\n case \"cie94-textiles\":\n return new CIE94Textiles();\n case \"ciede2000\":\n return new CIEDE2000();\n case \"color-metric\":\n return new CMetric();\n case \"euclidean\":\n return new Euclidean();\n case \"euclidean-bt709\":\n return new EuclideanBT709();\n case \"euclidean-bt709-noalpha\":\n return new EuclideanBT709NoAlpha();\n case \"manhattan\":\n return new Manhattan();\n case \"manhattan-bt709\":\n return new ManhattanBT709();\n case \"manhattan-nommyde\":\n return new ManhattanNommyde();\n case \"pngquant\":\n return new PNGQuant();\n default:\n throw new Error(`Unknown colorDistanceFormula ${colorDistanceFormula}`);\n }\n}\nfunction imageQuantizationToImageQuantizer(distanceCalculator, imageQuantization = \"floyd-steinberg\") {\n switch (imageQuantization) {\n case \"nearest\":\n return new NearestColor(distanceCalculator);\n case \"riemersma\":\n return new ErrorDiffusionRiemersma(distanceCalculator);\n case \"floyd-steinberg\":\n return new ErrorDiffusionArray(distanceCalculator, 0 /* FloydSteinberg */);\n case \"false-floyd-steinberg\":\n return new ErrorDiffusionArray(distanceCalculator, 1 /* FalseFloydSteinberg */);\n case \"stucki\":\n return new ErrorDiffusionArray(distanceCalculator, 2 /* Stucki */);\n case \"atkinson\":\n return new ErrorDiffusionArray(distanceCalculator, 3 /* Atkinson */);\n case \"jarvis\":\n return new ErrorDiffusionArray(distanceCalculator, 4 /* Jarvis */);\n case \"burkes\":\n return new ErrorDiffusionArray(distanceCalculator, 5 /* Burkes */);\n case \"sierra\":\n return new ErrorDiffusionArray(distanceCalculator, 6 /* Sierra */);\n case \"two-sierra\":\n return new ErrorDiffusionArray(distanceCalculator, 7 /* TwoSierra */);\n case \"sierra-lite\":\n return new ErrorDiffusionArray(distanceCalculator, 8 /* SierraLite */);\n default:\n throw new Error(`Unknown imageQuantization ${imageQuantization}`);\n }\n}\nfunction paletteQuantizationToPaletteQuantizer(distanceCalculator, paletteQuantization = \"wuquant\", colors = 256) {\n switch (paletteQuantization) {\n case \"neuquant\":\n return new NeuQuant(distanceCalculator, colors);\n case \"rgbquant\":\n return new RGBQuant(distanceCalculator, colors);\n case \"wuquant\":\n return new WuQuant(distanceCalculator, colors);\n case \"neuquant-float\":\n return new NeuQuantFloat(distanceCalculator, colors);\n default:\n throw new Error(`Unknown paletteQuantization ${paletteQuantization}`);\n }\n}\nmodule.exports = __toCommonJS(src_exports);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n applyPalette,\n applyPaletteSync,\n buildPalette,\n buildPaletteSync,\n constants,\n conversion,\n distance,\n image,\n palette,\n quality,\n utils\n});\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * cie94.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * ciede2000.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * cmetric.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * common.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * constants.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * ditherErrorDiffusionArray.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * euclidean.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * helper.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * hueStatistics.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * iq.ts - Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * lab2rgb.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * lab2xyz.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * manhattanNeuQuant.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * nearestColor.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * palette.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * pngQuant.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * point.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * pointContainer.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * rgb2hsl.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * rgb2lab.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * rgb2xyz.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * ssim.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * wuQuant.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * xyz2lab.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * xyz2rgb.ts - part of Image Quantization Library\n */\n/**\n * @preserve\n * MIT License\n *\n * Copyright 2015-2018 Igor Bezkrovnyi\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n * riemersma.ts - part of Image Quantization Library\n */\n/**\n * @preserve TypeScript port:\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * colorHistogram.ts - part of Image Quantization Library\n */\n/**\n * @preserve TypeScript port:\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * neuquant.ts - part of Image Quantization Library\n */\n/**\n * @preserve TypeScript port:\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * rgbquant.ts - part of Image Quantization Library\n */\n//# sourceMappingURL=image-q.cjs.map\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export function isNodePattern(cb) {\n if (typeof cb === \"undefined\") {\n return false;\n }\n if (typeof cb !== \"function\") {\n throw new TypeError(\"Callback must be a function\");\n }\n return true;\n}\nexport function throwError(error, cb) {\n if (typeof error === \"string\") {\n error = new Error(error);\n }\n if (typeof cb === \"function\") {\n return cb.call(this, error);\n }\n throw error;\n}\nexport function scan(image, x, y, w, h, f) {\n // round input\n x = Math.round(x);\n y = Math.round(y);\n w = Math.round(w);\n h = Math.round(h);\n for (let _y = y; _y < y + h; _y++) {\n for (let _x = x; _x < x + w; _x++) {\n const idx = image.bitmap.width * _y + _x << 2;\n f.call(image, _x, _y, idx);\n }\n }\n return image;\n}\nexport function* scanIterator(image, x, y, w, h) {\n // round input\n x = Math.round(x);\n y = Math.round(y);\n w = Math.round(w);\n h = Math.round(h);\n for (let _y = y; _y < y + h; _y++) {\n for (let _x = x; _x < x + w; _x++) {\n const idx = image.bitmap.width * _y + _x << 2;\n yield {\n x: _x,\n y: _y,\n idx,\n image\n };\n }\n }\n}\n//# sourceMappingURL=index.js.map","// This file is autogenerated. It's used to publish ESM to npm.\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}\n\n// https://github.com/bgrins/TinyColor\n// Brian Grinstead, MIT License\n\nvar trimLeft = /^\\s+/;\nvar trimRight = /\\s+$/;\nfunction tinycolor(color, opts) {\n color = color ? color : \"\";\n opts = opts || {};\n\n // If input is already a tinycolor, return itself\n if (color instanceof tinycolor) {\n return color;\n }\n // If we are called as a function, call using new instead\n if (!(this instanceof tinycolor)) {\n return new tinycolor(color, opts);\n }\n var rgb = inputToRGB(color);\n this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format;\n this._gradientType = opts.gradientType;\n\n // Don't let the range of [0,255] come back in [0,1].\n // Potentially lose a little bit of precision here, but will fix issues where\n // .5 gets interpreted as half of the total, instead of half of 1\n // If it was supposed to be 128, this was already taken care of by `inputToRgb`\n if (this._r < 1) this._r = Math.round(this._r);\n if (this._g < 1) this._g = Math.round(this._g);\n if (this._b < 1) this._b = Math.round(this._b);\n this._ok = rgb.ok;\n}\ntinycolor.prototype = {\n isDark: function isDark() {\n return this.getBrightness() < 128;\n },\n isLight: function isLight() {\n return !this.isDark();\n },\n isValid: function isValid() {\n return this._ok;\n },\n getOriginalInput: function getOriginalInput() {\n return this._originalInput;\n },\n getFormat: function getFormat() {\n return this._format;\n },\n getAlpha: function getAlpha() {\n return this._a;\n },\n getBrightness: function getBrightness() {\n //http://www.w3.org/TR/AERT#color-contrast\n var rgb = this.toRgb();\n return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;\n },\n getLuminance: function getLuminance() {\n //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef\n var rgb = this.toRgb();\n var RsRGB, GsRGB, BsRGB, R, G, B;\n RsRGB = rgb.r / 255;\n GsRGB = rgb.g / 255;\n BsRGB = rgb.b / 255;\n if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4);\n if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4);\n if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4);\n return 0.2126 * R + 0.7152 * G + 0.0722 * B;\n },\n setAlpha: function setAlpha(value) {\n this._a = boundAlpha(value);\n this._roundA = Math.round(100 * this._a) / 100;\n return this;\n },\n toHsv: function toHsv() {\n var hsv = rgbToHsv(this._r, this._g, this._b);\n return {\n h: hsv.h * 360,\n s: hsv.s,\n v: hsv.v,\n a: this._a\n };\n },\n toHsvString: function toHsvString() {\n var hsv = rgbToHsv(this._r, this._g, this._b);\n var h = Math.round(hsv.h * 360),\n s = Math.round(hsv.s * 100),\n v = Math.round(hsv.v * 100);\n return this._a == 1 ? \"hsv(\" + h + \", \" + s + \"%, \" + v + \"%)\" : \"hsva(\" + h + \", \" + s + \"%, \" + v + \"%, \" + this._roundA + \")\";\n },\n toHsl: function toHsl() {\n var hsl = rgbToHsl(this._r, this._g, this._b);\n return {\n h: hsl.h * 360,\n s: hsl.s,\n l: hsl.l,\n a: this._a\n };\n },\n toHslString: function toHslString() {\n var hsl = rgbToHsl(this._r, this._g, this._b);\n var h = Math.round(hsl.h * 360),\n s = Math.round(hsl.s * 100),\n l = Math.round(hsl.l * 100);\n return this._a == 1 ? \"hsl(\" + h + \", \" + s + \"%, \" + l + \"%)\" : \"hsla(\" + h + \", \" + s + \"%, \" + l + \"%, \" + this._roundA + \")\";\n },\n toHex: function toHex(allow3Char) {\n return rgbToHex(this._r, this._g, this._b, allow3Char);\n },\n toHexString: function toHexString(allow3Char) {\n return \"#\" + this.toHex(allow3Char);\n },\n toHex8: function toHex8(allow4Char) {\n return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);\n },\n toHex8String: function toHex8String(allow4Char) {\n return \"#\" + this.toHex8(allow4Char);\n },\n toRgb: function toRgb() {\n return {\n r: Math.round(this._r),\n g: Math.round(this._g),\n b: Math.round(this._b),\n a: this._a\n };\n },\n toRgbString: function toRgbString() {\n return this._a == 1 ? \"rgb(\" + Math.round(this._r) + \", \" + Math.round(this._g) + \", \" + Math.round(this._b) + \")\" : \"rgba(\" + Math.round(this._r) + \", \" + Math.round(this._g) + \", \" + Math.round(this._b) + \", \" + this._roundA + \")\";\n },\n toPercentageRgb: function toPercentageRgb() {\n return {\n r: Math.round(bound01(this._r, 255) * 100) + \"%\",\n g: Math.round(bound01(this._g, 255) * 100) + \"%\",\n b: Math.round(bound01(this._b, 255) * 100) + \"%\",\n a: this._a\n };\n },\n toPercentageRgbString: function toPercentageRgbString() {\n return this._a == 1 ? \"rgb(\" + Math.round(bound01(this._r, 255) * 100) + \"%, \" + Math.round(bound01(this._g, 255) * 100) + \"%, \" + Math.round(bound01(this._b, 255) * 100) + \"%)\" : \"rgba(\" + Math.round(bound01(this._r, 255) * 100) + \"%, \" + Math.round(bound01(this._g, 255) * 100) + \"%, \" + Math.round(bound01(this._b, 255) * 100) + \"%, \" + this._roundA + \")\";\n },\n toName: function toName() {\n if (this._a === 0) {\n return \"transparent\";\n }\n if (this._a < 1) {\n return false;\n }\n return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;\n },\n toFilter: function toFilter(secondColor) {\n var hex8String = \"#\" + rgbaToArgbHex(this._r, this._g, this._b, this._a);\n var secondHex8String = hex8String;\n var gradientType = this._gradientType ? \"GradientType = 1, \" : \"\";\n if (secondColor) {\n var s = tinycolor(secondColor);\n secondHex8String = \"#\" + rgbaToArgbHex(s._r, s._g, s._b, s._a);\n }\n return \"progid:DXImageTransform.Microsoft.gradient(\" + gradientType + \"startColorstr=\" + hex8String + \",endColorstr=\" + secondHex8String + \")\";\n },\n toString: function toString(format) {\n var formatSet = !!format;\n format = format || this._format;\n var formattedString = false;\n var hasAlpha = this._a < 1 && this._a >= 0;\n var needsAlphaFormat = !formatSet && hasAlpha && (format === \"hex\" || format === \"hex6\" || format === \"hex3\" || format === \"hex4\" || format === \"hex8\" || format === \"name\");\n if (needsAlphaFormat) {\n // Special case for \"transparent\", all other non-alpha formats\n // will return rgba when there is transparency.\n if (format === \"name\" && this._a === 0) {\n return this.toName();\n }\n return this.toRgbString();\n }\n if (format === \"rgb\") {\n formattedString = this.toRgbString();\n }\n if (format === \"prgb\") {\n formattedString = this.toPercentageRgbString();\n }\n if (format === \"hex\" || format === \"hex6\") {\n formattedString = this.toHexString();\n }\n if (format === \"hex3\") {\n formattedString = this.toHexString(true);\n }\n if (format === \"hex4\") {\n formattedString = this.toHex8String(true);\n }\n if (format === \"hex8\") {\n formattedString = this.toHex8String();\n }\n if (format === \"name\") {\n formattedString = this.toName();\n }\n if (format === \"hsl\") {\n formattedString = this.toHslString();\n }\n if (format === \"hsv\") {\n formattedString = this.toHsvString();\n }\n return formattedString || this.toHexString();\n },\n clone: function clone() {\n return tinycolor(this.toString());\n },\n _applyModification: function _applyModification(fn, args) {\n var color = fn.apply(null, [this].concat([].slice.call(args)));\n this._r = color._r;\n this._g = color._g;\n this._b = color._b;\n this.setAlpha(color._a);\n return this;\n },\n lighten: function lighten() {\n return this._applyModification(_lighten, arguments);\n },\n brighten: function brighten() {\n return this._applyModification(_brighten, arguments);\n },\n darken: function darken() {\n return this._applyModification(_darken, arguments);\n },\n desaturate: function desaturate() {\n return this._applyModification(_desaturate, arguments);\n },\n saturate: function saturate() {\n return this._applyModification(_saturate, arguments);\n },\n greyscale: function greyscale() {\n return this._applyModification(_greyscale, arguments);\n },\n spin: function spin() {\n return this._applyModification(_spin, arguments);\n },\n _applyCombination: function _applyCombination(fn, args) {\n return fn.apply(null, [this].concat([].slice.call(args)));\n },\n analogous: function analogous() {\n return this._applyCombination(_analogous, arguments);\n },\n complement: function complement() {\n return this._applyCombination(_complement, arguments);\n },\n monochromatic: function monochromatic() {\n return this._applyCombination(_monochromatic, arguments);\n },\n splitcomplement: function splitcomplement() {\n return this._applyCombination(_splitcomplement, arguments);\n },\n // Disabled until https://github.com/bgrins/TinyColor/issues/254\n // polyad: function (number) {\n // return this._applyCombination(polyad, [number]);\n // },\n triad: function triad() {\n return this._applyCombination(polyad, [3]);\n },\n tetrad: function tetrad() {\n return this._applyCombination(polyad, [4]);\n }\n};\n\n// If input is an object, force 1 into \"1.0\" to handle ratios properly\n// String input requires \"1.0\" as input, so 1 will be treated as 1\ntinycolor.fromRatio = function (color, opts) {\n if (_typeof(color) == \"object\") {\n var newColor = {};\n for (var i in color) {\n if (color.hasOwnProperty(i)) {\n if (i === \"a\") {\n newColor[i] = color[i];\n } else {\n newColor[i] = convertToPercentage(color[i]);\n }\n }\n }\n color = newColor;\n }\n return tinycolor(color, opts);\n};\n\n// Given a string or object, convert that input to RGB\n// Possible string inputs:\n//\n// \"red\"\n// \"#f00\" or \"f00\"\n// \"#ff0000\" or \"ff0000\"\n// \"#ff000000\" or \"ff000000\"\n// \"rgb 255 0 0\" or \"rgb (255, 0, 0)\"\n// \"rgb 1.0 0 0\" or \"rgb (1, 0, 0)\"\n// \"rgba (255, 0, 0, 1)\" or \"rgba 255, 0, 0, 1\"\n// \"rgba (1.0, 0, 0, 1)\" or \"rgba 1.0, 0, 0, 1\"\n// \"hsl(0, 100%, 50%)\" or \"hsl 0 100% 50%\"\n// \"hsla(0, 100%, 50%, 1)\" or \"hsla 0 100% 50%, 1\"\n// \"hsv(0, 100%, 100%)\" or \"hsv 0 100% 100%\"\n//\nfunction inputToRGB(color) {\n var rgb = {\n r: 0,\n g: 0,\n b: 0\n };\n var a = 1;\n var s = null;\n var v = null;\n var l = null;\n var ok = false;\n var format = false;\n if (typeof color == \"string\") {\n color = stringInputToObject(color);\n }\n if (_typeof(color) == \"object\") {\n if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {\n rgb = rgbToRgb(color.r, color.g, color.b);\n ok = true;\n format = String(color.r).substr(-1) === \"%\" ? \"prgb\" : \"rgb\";\n } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {\n s = convertToPercentage(color.s);\n v = convertToPercentage(color.v);\n rgb = hsvToRgb(color.h, s, v);\n ok = true;\n format = \"hsv\";\n } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {\n s = convertToPercentage(color.s);\n l = convertToPercentage(color.l);\n rgb = hslToRgb(color.h, s, l);\n ok = true;\n format = \"hsl\";\n }\n if (color.hasOwnProperty(\"a\")) {\n a = color.a;\n }\n }\n a = boundAlpha(a);\n return {\n ok: ok,\n format: color.format || format,\n r: Math.min(255, Math.max(rgb.r, 0)),\n g: Math.min(255, Math.max(rgb.g, 0)),\n b: Math.min(255, Math.max(rgb.b, 0)),\n a: a\n };\n}\n\n// Conversion Functions\n// --------------------\n\n// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:\n// \n\n// `rgbToRgb`\n// Handle bounds / percentage checking to conform to CSS color spec\n// \n// *Assumes:* r, g, b in [0, 255] or [0, 1]\n// *Returns:* { r, g, b } in [0, 255]\nfunction rgbToRgb(r, g, b) {\n return {\n r: bound01(r, 255) * 255,\n g: bound01(g, 255) * 255,\n b: bound01(b, 255) * 255\n };\n}\n\n// `rgbToHsl`\n// Converts an RGB color value to HSL.\n// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]\n// *Returns:* { h, s, l } in [0,1]\nfunction rgbToHsl(r, g, b) {\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n var max = Math.max(r, g, b),\n min = Math.min(r, g, b);\n var h,\n s,\n l = (max + min) / 2;\n if (max == min) {\n h = s = 0; // achromatic\n } else {\n var d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n return {\n h: h,\n s: s,\n l: l\n };\n}\n\n// `hslToRgb`\n// Converts an HSL color value to RGB.\n// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]\n// *Returns:* { r, g, b } in the set [0, 255]\nfunction hslToRgb(h, s, l) {\n var r, g, b;\n h = bound01(h, 360);\n s = bound01(s, 100);\n l = bound01(l, 100);\n function hue2rgb(p, q, t) {\n if (t < 0) t += 1;\n if (t > 1) t -= 1;\n if (t < 1 / 6) return p + (q - p) * 6 * t;\n if (t < 1 / 2) return q;\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n }\n if (s === 0) {\n r = g = b = l; // achromatic\n } else {\n var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n var p = 2 * l - q;\n r = hue2rgb(p, q, h + 1 / 3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1 / 3);\n }\n return {\n r: r * 255,\n g: g * 255,\n b: b * 255\n };\n}\n\n// `rgbToHsv`\n// Converts an RGB color value to HSV\n// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]\n// *Returns:* { h, s, v } in [0,1]\nfunction rgbToHsv(r, g, b) {\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n var max = Math.max(r, g, b),\n min = Math.min(r, g, b);\n var h,\n s,\n v = max;\n var d = max - min;\n s = max === 0 ? 0 : d / max;\n if (max == min) {\n h = 0; // achromatic\n } else {\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n return {\n h: h,\n s: s,\n v: v\n };\n}\n\n// `hsvToRgb`\n// Converts an HSV color value to RGB.\n// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]\n// *Returns:* { r, g, b } in the set [0, 255]\nfunction hsvToRgb(h, s, v) {\n h = bound01(h, 360) * 6;\n s = bound01(s, 100);\n v = bound01(v, 100);\n var i = Math.floor(h),\n f = h - i,\n p = v * (1 - s),\n q = v * (1 - f * s),\n t = v * (1 - (1 - f) * s),\n mod = i % 6,\n r = [v, q, p, p, t, v][mod],\n g = [t, v, v, q, p, p][mod],\n b = [p, p, t, v, v, q][mod];\n return {\n r: r * 255,\n g: g * 255,\n b: b * 255\n };\n}\n\n// `rgbToHex`\n// Converts an RGB color to hex\n// Assumes r, g, and b are contained in the set [0, 255]\n// Returns a 3 or 6 character hex\nfunction rgbToHex(r, g, b, allow3Char) {\n var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];\n\n // Return a 3 character hex if possible\n if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);\n }\n return hex.join(\"\");\n}\n\n// `rgbaToHex`\n// Converts an RGBA color plus alpha transparency to hex\n// Assumes r, g, b are contained in the set [0, 255] and\n// a in [0, 1]. Returns a 4 or 8 character rgba hex\nfunction rgbaToHex(r, g, b, a, allow4Char) {\n var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))];\n\n // Return a 4 character hex if possible\n if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);\n }\n return hex.join(\"\");\n}\n\n// `rgbaToArgbHex`\n// Converts an RGBA color to an ARGB Hex8 string\n// Rarely used, but required for \"toFilter()\"\nfunction rgbaToArgbHex(r, g, b, a) {\n var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];\n return hex.join(\"\");\n}\n\n// `equals`\n// Can be called with any tinycolor input\ntinycolor.equals = function (color1, color2) {\n if (!color1 || !color2) return false;\n return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();\n};\ntinycolor.random = function () {\n return tinycolor.fromRatio({\n r: Math.random(),\n g: Math.random(),\n b: Math.random()\n });\n};\n\n// Modification Functions\n// ----------------------\n// Thanks to less.js for some of the basics here\n// \n\nfunction _desaturate(color, amount) {\n amount = amount === 0 ? 0 : amount || 10;\n var hsl = tinycolor(color).toHsl();\n hsl.s -= amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n}\nfunction _saturate(color, amount) {\n amount = amount === 0 ? 0 : amount || 10;\n var hsl = tinycolor(color).toHsl();\n hsl.s += amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n}\nfunction _greyscale(color) {\n return tinycolor(color).desaturate(100);\n}\nfunction _lighten(color, amount) {\n amount = amount === 0 ? 0 : amount || 10;\n var hsl = tinycolor(color).toHsl();\n hsl.l += amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n}\nfunction _brighten(color, amount) {\n amount = amount === 0 ? 0 : amount || 10;\n var rgb = tinycolor(color).toRgb();\n rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100))));\n rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100))));\n rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100))));\n return tinycolor(rgb);\n}\nfunction _darken(color, amount) {\n amount = amount === 0 ? 0 : amount || 10;\n var hsl = tinycolor(color).toHsl();\n hsl.l -= amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n}\n\n// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.\n// Values outside of this range will be wrapped into this range.\nfunction _spin(color, amount) {\n var hsl = tinycolor(color).toHsl();\n var hue = (hsl.h + amount) % 360;\n hsl.h = hue < 0 ? 360 + hue : hue;\n return tinycolor(hsl);\n}\n\n// Combination Functions\n// ---------------------\n// Thanks to jQuery xColor for some of the ideas behind these\n// \n\nfunction _complement(color) {\n var hsl = tinycolor(color).toHsl();\n hsl.h = (hsl.h + 180) % 360;\n return tinycolor(hsl);\n}\nfunction polyad(color, number) {\n if (isNaN(number) || number <= 0) {\n throw new Error(\"Argument to polyad must be a positive number\");\n }\n var hsl = tinycolor(color).toHsl();\n var result = [tinycolor(color)];\n var step = 360 / number;\n for (var i = 1; i < number; i++) {\n result.push(tinycolor({\n h: (hsl.h + i * step) % 360,\n s: hsl.s,\n l: hsl.l\n }));\n }\n return result;\n}\nfunction _splitcomplement(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [tinycolor(color), tinycolor({\n h: (h + 72) % 360,\n s: hsl.s,\n l: hsl.l\n }), tinycolor({\n h: (h + 216) % 360,\n s: hsl.s,\n l: hsl.l\n })];\n}\nfunction _analogous(color, results, slices) {\n results = results || 6;\n slices = slices || 30;\n var hsl = tinycolor(color).toHsl();\n var part = 360 / slices;\n var ret = [tinycolor(color)];\n for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) {\n hsl.h = (hsl.h + part) % 360;\n ret.push(tinycolor(hsl));\n }\n return ret;\n}\nfunction _monochromatic(color, results) {\n results = results || 6;\n var hsv = tinycolor(color).toHsv();\n var h = hsv.h,\n s = hsv.s,\n v = hsv.v;\n var ret = [];\n var modification = 1 / results;\n while (results--) {\n ret.push(tinycolor({\n h: h,\n s: s,\n v: v\n }));\n v = (v + modification) % 1;\n }\n return ret;\n}\n\n// Utility Functions\n// ---------------------\n\ntinycolor.mix = function (color1, color2, amount) {\n amount = amount === 0 ? 0 : amount || 50;\n var rgb1 = tinycolor(color1).toRgb();\n var rgb2 = tinycolor(color2).toRgb();\n var p = amount / 100;\n var rgba = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b,\n a: (rgb2.a - rgb1.a) * p + rgb1.a\n };\n return tinycolor(rgba);\n};\n\n// Readability Functions\n// ---------------------\n// false\n// tinycolor.isReadable(\"#000\", \"#111\",{level:\"AA\",size:\"large\"}) => false\ntinycolor.isReadable = function (color1, color2, wcag2) {\n var readability = tinycolor.readability(color1, color2);\n var wcag2Parms, out;\n out = false;\n wcag2Parms = validateWCAG2Parms(wcag2);\n switch (wcag2Parms.level + wcag2Parms.size) {\n case \"AAsmall\":\n case \"AAAlarge\":\n out = readability >= 4.5;\n break;\n case \"AAlarge\":\n out = readability >= 3;\n break;\n case \"AAAsmall\":\n out = readability >= 7;\n break;\n }\n return out;\n};\n\n// `mostReadable`\n// Given a base color and a list of possible foreground or background\n// colors for that base, returns the most readable color.\n// Optionally returns Black or White if the most readable color is unreadable.\n// *Example*\n// tinycolor.mostReadable(tinycolor.mostReadable(\"#123\", [\"#124\", \"#125\"],{includeFallbackColors:false}).toHexString(); // \"#112255\"\n// tinycolor.mostReadable(tinycolor.mostReadable(\"#123\", [\"#124\", \"#125\"],{includeFallbackColors:true}).toHexString(); // \"#ffffff\"\n// tinycolor.mostReadable(\"#a8015a\", [\"#faf3f3\"],{includeFallbackColors:true,level:\"AAA\",size:\"large\"}).toHexString(); // \"#faf3f3\"\n// tinycolor.mostReadable(\"#a8015a\", [\"#faf3f3\"],{includeFallbackColors:true,level:\"AAA\",size:\"small\"}).toHexString(); // \"#ffffff\"\ntinycolor.mostReadable = function (baseColor, colorList, args) {\n var bestColor = null;\n var bestScore = 0;\n var readability;\n var includeFallbackColors, level, size;\n args = args || {};\n includeFallbackColors = args.includeFallbackColors;\n level = args.level;\n size = args.size;\n for (var i = 0; i < colorList.length; i++) {\n readability = tinycolor.readability(baseColor, colorList[i]);\n if (readability > bestScore) {\n bestScore = readability;\n bestColor = tinycolor(colorList[i]);\n }\n }\n if (tinycolor.isReadable(baseColor, bestColor, {\n level: level,\n size: size\n }) || !includeFallbackColors) {\n return bestColor;\n } else {\n args.includeFallbackColors = false;\n return tinycolor.mostReadable(baseColor, [\"#fff\", \"#000\"], args);\n }\n};\n\n// Big List of Colors\n// ------------------\n// \nvar names = tinycolor.names = {\n aliceblue: \"f0f8ff\",\n antiquewhite: \"faebd7\",\n aqua: \"0ff\",\n aquamarine: \"7fffd4\",\n azure: \"f0ffff\",\n beige: \"f5f5dc\",\n bisque: \"ffe4c4\",\n black: \"000\",\n blanchedalmond: \"ffebcd\",\n blue: \"00f\",\n blueviolet: \"8a2be2\",\n brown: \"a52a2a\",\n burlywood: \"deb887\",\n burntsienna: \"ea7e5d\",\n cadetblue: \"5f9ea0\",\n chartreuse: \"7fff00\",\n chocolate: \"d2691e\",\n coral: \"ff7f50\",\n cornflowerblue: \"6495ed\",\n cornsilk: \"fff8dc\",\n crimson: \"dc143c\",\n cyan: \"0ff\",\n darkblue: \"00008b\",\n darkcyan: \"008b8b\",\n darkgoldenrod: \"b8860b\",\n darkgray: \"a9a9a9\",\n darkgreen: \"006400\",\n darkgrey: \"a9a9a9\",\n darkkhaki: \"bdb76b\",\n darkmagenta: \"8b008b\",\n darkolivegreen: \"556b2f\",\n darkorange: \"ff8c00\",\n darkorchid: \"9932cc\",\n darkred: \"8b0000\",\n darksalmon: \"e9967a\",\n darkseagreen: \"8fbc8f\",\n darkslateblue: \"483d8b\",\n darkslategray: \"2f4f4f\",\n darkslategrey: \"2f4f4f\",\n darkturquoise: \"00ced1\",\n darkviolet: \"9400d3\",\n deeppink: \"ff1493\",\n deepskyblue: \"00bfff\",\n dimgray: \"696969\",\n dimgrey: \"696969\",\n dodgerblue: \"1e90ff\",\n firebrick: \"b22222\",\n floralwhite: \"fffaf0\",\n forestgreen: \"228b22\",\n fuchsia: \"f0f\",\n gainsboro: \"dcdcdc\",\n ghostwhite: \"f8f8ff\",\n gold: \"ffd700\",\n goldenrod: \"daa520\",\n gray: \"808080\",\n green: \"008000\",\n greenyellow: \"adff2f\",\n grey: \"808080\",\n honeydew: \"f0fff0\",\n hotpink: \"ff69b4\",\n indianred: \"cd5c5c\",\n indigo: \"4b0082\",\n ivory: \"fffff0\",\n khaki: \"f0e68c\",\n lavender: \"e6e6fa\",\n lavenderblush: \"fff0f5\",\n lawngreen: \"7cfc00\",\n lemonchiffon: \"fffacd\",\n lightblue: \"add8e6\",\n lightcoral: \"f08080\",\n lightcyan: \"e0ffff\",\n lightgoldenrodyellow: \"fafad2\",\n lightgray: \"d3d3d3\",\n lightgreen: \"90ee90\",\n lightgrey: \"d3d3d3\",\n lightpink: \"ffb6c1\",\n lightsalmon: \"ffa07a\",\n lightseagreen: \"20b2aa\",\n lightskyblue: \"87cefa\",\n lightslategray: \"789\",\n lightslategrey: \"789\",\n lightsteelblue: \"b0c4de\",\n lightyellow: \"ffffe0\",\n lime: \"0f0\",\n limegreen: \"32cd32\",\n linen: \"faf0e6\",\n magenta: \"f0f\",\n maroon: \"800000\",\n mediumaquamarine: \"66cdaa\",\n mediumblue: \"0000cd\",\n mediumorchid: \"ba55d3\",\n mediumpurple: \"9370db\",\n mediumseagreen: \"3cb371\",\n mediumslateblue: \"7b68ee\",\n mediumspringgreen: \"00fa9a\",\n mediumturquoise: \"48d1cc\",\n mediumvioletred: \"c71585\",\n midnightblue: \"191970\",\n mintcream: \"f5fffa\",\n mistyrose: \"ffe4e1\",\n moccasin: \"ffe4b5\",\n navajowhite: \"ffdead\",\n navy: \"000080\",\n oldlace: \"fdf5e6\",\n olive: \"808000\",\n olivedrab: \"6b8e23\",\n orange: \"ffa500\",\n orangered: \"ff4500\",\n orchid: \"da70d6\",\n palegoldenrod: \"eee8aa\",\n palegreen: \"98fb98\",\n paleturquoise: \"afeeee\",\n palevioletred: \"db7093\",\n papayawhip: \"ffefd5\",\n peachpuff: \"ffdab9\",\n peru: \"cd853f\",\n pink: \"ffc0cb\",\n plum: \"dda0dd\",\n powderblue: \"b0e0e6\",\n purple: \"800080\",\n rebeccapurple: \"663399\",\n red: \"f00\",\n rosybrown: \"bc8f8f\",\n royalblue: \"4169e1\",\n saddlebrown: \"8b4513\",\n salmon: \"fa8072\",\n sandybrown: \"f4a460\",\n seagreen: \"2e8b57\",\n seashell: \"fff5ee\",\n sienna: \"a0522d\",\n silver: \"c0c0c0\",\n skyblue: \"87ceeb\",\n slateblue: \"6a5acd\",\n slategray: \"708090\",\n slategrey: \"708090\",\n snow: \"fffafa\",\n springgreen: \"00ff7f\",\n steelblue: \"4682b4\",\n tan: \"d2b48c\",\n teal: \"008080\",\n thistle: \"d8bfd8\",\n tomato: \"ff6347\",\n turquoise: \"40e0d0\",\n violet: \"ee82ee\",\n wheat: \"f5deb3\",\n white: \"fff\",\n whitesmoke: \"f5f5f5\",\n yellow: \"ff0\",\n yellowgreen: \"9acd32\"\n};\n\n// Make it easy to access colors via `hexNames[hex]`\nvar hexNames = tinycolor.hexNames = flip(names);\n\n// Utilities\n// ---------\n\n// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`\nfunction flip(o) {\n var flipped = {};\n for (var i in o) {\n if (o.hasOwnProperty(i)) {\n flipped[o[i]] = i;\n }\n }\n return flipped;\n}\n\n// Return a valid alpha value [0,1] with all invalid values being set to 1\nfunction boundAlpha(a) {\n a = parseFloat(a);\n if (isNaN(a) || a < 0 || a > 1) {\n a = 1;\n }\n return a;\n}\n\n// Take input from [0, n] and return it as [0, 1]\nfunction bound01(n, max) {\n if (isOnePointZero(n)) n = \"100%\";\n var processPercent = isPercentage(n);\n n = Math.min(max, Math.max(0, parseFloat(n)));\n\n // Automatically convert percentage into number\n if (processPercent) {\n n = parseInt(n * max, 10) / 100;\n }\n\n // Handle floating point rounding errors\n if (Math.abs(n - max) < 0.000001) {\n return 1;\n }\n\n // Convert into [0, 1] range if it isn't already\n return n % max / parseFloat(max);\n}\n\n// Force a number between 0 and 1\nfunction clamp01(val) {\n return Math.min(1, Math.max(0, val));\n}\n\n// Parse a base-16 hex value into a base-10 integer\nfunction parseIntFromHex(val) {\n return parseInt(val, 16);\n}\n\n// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1\n// \nfunction isOnePointZero(n) {\n return typeof n == \"string\" && n.indexOf(\".\") != -1 && parseFloat(n) === 1;\n}\n\n// Check to see if string passed in is a percentage\nfunction isPercentage(n) {\n return typeof n === \"string\" && n.indexOf(\"%\") != -1;\n}\n\n// Force a hex value to have 2 characters\nfunction pad2(c) {\n return c.length == 1 ? \"0\" + c : \"\" + c;\n}\n\n// Replace a decimal with it's percentage value\nfunction convertToPercentage(n) {\n if (n <= 1) {\n n = n * 100 + \"%\";\n }\n return n;\n}\n\n// Converts a decimal to a hex value\nfunction convertDecimalToHex(d) {\n return Math.round(parseFloat(d) * 255).toString(16);\n}\n// Converts a hex value to a decimal\nfunction convertHexToDecimal(h) {\n return parseIntFromHex(h) / 255;\n}\nvar matchers = function () {\n // \n var CSS_INTEGER = \"[-\\\\+]?\\\\d+%?\";\n\n // \n var CSS_NUMBER = \"[-\\\\+]?\\\\d*\\\\.\\\\d+%?\";\n\n // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.\n var CSS_UNIT = \"(?:\" + CSS_NUMBER + \")|(?:\" + CSS_INTEGER + \")\";\n\n // Actual matching.\n // Parentheses and commas are optional, but not required.\n // Whitespace can take the place of commas or opening paren\n var PERMISSIVE_MATCH3 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n var PERMISSIVE_MATCH4 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n return {\n CSS_UNIT: new RegExp(CSS_UNIT),\n rgb: new RegExp(\"rgb\" + PERMISSIVE_MATCH3),\n rgba: new RegExp(\"rgba\" + PERMISSIVE_MATCH4),\n hsl: new RegExp(\"hsl\" + PERMISSIVE_MATCH3),\n hsla: new RegExp(\"hsla\" + PERMISSIVE_MATCH4),\n hsv: new RegExp(\"hsv\" + PERMISSIVE_MATCH3),\n hsva: new RegExp(\"hsva\" + PERMISSIVE_MATCH4),\n hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,\n hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/\n };\n}();\n\n// `isValidCSSUnit`\n// Take in a single string / number and check to see if it looks like a CSS unit\n// (see `matchers` above for definition).\nfunction isValidCSSUnit(color) {\n return !!matchers.CSS_UNIT.exec(color);\n}\n\n// `stringInputToObject`\n// Permissive string parsing. Take in a number of formats, and output an object\n// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`\nfunction stringInputToObject(color) {\n color = color.replace(trimLeft, \"\").replace(trimRight, \"\").toLowerCase();\n var named = false;\n if (names[color]) {\n color = names[color];\n named = true;\n } else if (color == \"transparent\") {\n return {\n r: 0,\n g: 0,\n b: 0,\n a: 0,\n format: \"name\"\n };\n }\n\n // Try to match string input using regular expressions.\n // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]\n // Just return an object and let the conversion functions handle that.\n // This way the result will be the same whether the tinycolor is initialized with string or object.\n var match;\n if (match = matchers.rgb.exec(color)) {\n return {\n r: match[1],\n g: match[2],\n b: match[3]\n };\n }\n if (match = matchers.rgba.exec(color)) {\n return {\n r: match[1],\n g: match[2],\n b: match[3],\n a: match[4]\n };\n }\n if (match = matchers.hsl.exec(color)) {\n return {\n h: match[1],\n s: match[2],\n l: match[3]\n };\n }\n if (match = matchers.hsla.exec(color)) {\n return {\n h: match[1],\n s: match[2],\n l: match[3],\n a: match[4]\n };\n }\n if (match = matchers.hsv.exec(color)) {\n return {\n h: match[1],\n s: match[2],\n v: match[3]\n };\n }\n if (match = matchers.hsva.exec(color)) {\n return {\n h: match[1],\n s: match[2],\n v: match[3],\n a: match[4]\n };\n }\n if (match = matchers.hex8.exec(color)) {\n return {\n r: parseIntFromHex(match[1]),\n g: parseIntFromHex(match[2]),\n b: parseIntFromHex(match[3]),\n a: convertHexToDecimal(match[4]),\n format: named ? \"name\" : \"hex8\"\n };\n }\n if (match = matchers.hex6.exec(color)) {\n return {\n r: parseIntFromHex(match[1]),\n g: parseIntFromHex(match[2]),\n b: parseIntFromHex(match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n if (match = matchers.hex4.exec(color)) {\n return {\n r: parseIntFromHex(match[1] + \"\" + match[1]),\n g: parseIntFromHex(match[2] + \"\" + match[2]),\n b: parseIntFromHex(match[3] + \"\" + match[3]),\n a: convertHexToDecimal(match[4] + \"\" + match[4]),\n format: named ? \"name\" : \"hex8\"\n };\n }\n if (match = matchers.hex3.exec(color)) {\n return {\n r: parseIntFromHex(match[1] + \"\" + match[1]),\n g: parseIntFromHex(match[2] + \"\" + match[2]),\n b: parseIntFromHex(match[3] + \"\" + match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n return false;\n}\nfunction validateWCAG2Parms(parms) {\n // return valid WCAG2 parms for isReadable.\n // If input parms are invalid, return {\"level\":\"AA\", \"size\":\"small\"}\n var level, size;\n parms = parms || {\n level: \"AA\",\n size: \"small\"\n };\n level = (parms.level || \"AA\").toUpperCase();\n size = (parms.size || \"small\").toLowerCase();\n if (level !== \"AA\" && level !== \"AAA\") {\n level = \"AA\";\n }\n if (size !== \"small\" && size !== \"large\") {\n size = \"small\";\n }\n return {\n level: level,\n size: size\n };\n}\n\nexport { tinycolor as default };\n","/*\nCopyright (c) 2011 Elliot Shepherd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies 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 FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n// https://code.google.com/p/ironchef-team21/source/browse/ironchef_team21/src/ImagePHash.java\n\n/*\n * pHash-like image hash.\n * Author: Elliot Shepherd (elliot@jarofworms.com\n * Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html\n */\n\nfunction ImagePHash(size, smallerSize) {\n this.size = this.size || size;\n this.smallerSize = this.smallerSize || smallerSize;\n initCoefficients(this.size);\n}\nImagePHash.prototype.size = 32;\nImagePHash.prototype.smallerSize = 8;\nImagePHash.prototype.distance = function (s1, s2) {\n let counter = 0;\n for (let k = 0; k < s1.length; k++) {\n if (s1[k] !== s2[k]) {\n counter++;\n }\n }\n return counter / s1.length;\n};\n\n// Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on.\nImagePHash.prototype.getHash = function (img) {\n /* 1. Reduce size.\n * Like Average Hash, pHash starts with a small image.\n * However, the image is larger than 8x8; 32x32 is a good size.\n * This is really done to simplify the DCT computation and not\n * because it is needed to reduce the high frequencies.\n */\n img = img.clone().resize(this.size, this.size);\n\n /* 2. Reduce color.\n * The image is reduced to a grayscale just to further simplify\n * the number of computations.\n */\n img.grayscale();\n const vals = [];\n for (let x = 0; x < img.bitmap.width; x++) {\n vals[x] = [];\n for (let y = 0; y < img.bitmap.height; y++) {\n vals[x][y] = intToRGBA(img.getPixelColor(x, y)).b;\n }\n }\n\n /* 3. Compute the DCT.\n * The DCT separates the image into a collection of frequencies\n * and scalars. While JPEG uses an 8x8 DCT, this algorithm uses\n * a 32x32 DCT.\n */\n const dctVals = applyDCT(vals, this.size);\n\n /* 4. Reduce the DCT.\n * This is the magic step. While the DCT is 32x32, just keep the\n * top-left 8x8. Those represent the lowest frequencies in the\n * picture.\n */\n /* 5. Compute the average value.\n * Like the Average Hash, compute the mean DCT value (using only\n * the 8x8 DCT low-frequency values and excluding the first term\n * since the DC coefficient can be significantly different from\n * the other values and will throw off the average).\n */\n let total = 0;\n for (let x = 0; x < this.smallerSize; x++) {\n for (let y = 0; y < this.smallerSize; y++) {\n total += dctVals[x][y];\n }\n }\n const avg = total / (this.smallerSize * this.smallerSize);\n\n /* 6. Further reduce the DCT.\n * This is the magic step. Set the 64 hash bits to 0 or 1\n * depending on whether each of the 64 DCT values is above or\n * below the average value. The result doesn't tell us the\n * actual low frequencies; it just tells us the very-rough\n * relative scale of the frequencies to the mean. The result\n * will not vary as long as the overall structure of the image\n * remains the same; this can survive gamma and color histogram\n * adjustments without a problem.\n */\n let hash = \"\";\n for (let x = 0; x < this.smallerSize; x++) {\n for (let y = 0; y < this.smallerSize; y++) {\n hash += dctVals[x][y] > avg ? \"1\" : \"0\";\n }\n }\n return hash;\n};\n\n// DCT function stolen from http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java\n\n/**\n Convert a 32-bit integer color value to an RGBA object.\n */\nfunction intToRGBA(i) {\n const a = i & 0xff;\n i >>>= 8;\n const b = i & 0xff;\n i >>>= 8;\n const g = i & 0xff;\n i >>>= 8;\n const r = i & 0xff;\n return {\n r,\n g,\n b,\n a\n };\n}\nconst c = [];\nfunction initCoefficients(size) {\n for (let i = 1; i < size; i++) {\n c[i] = 1;\n }\n c[0] = 1 / Math.sqrt(2.0);\n}\nfunction applyDCT(f, size) {\n const N = size;\n const F = [];\n for (let u = 0; u < N; u++) {\n F[u] = [];\n for (let v = 0; v < N; v++) {\n let sum = 0;\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n sum += Math.cos((2 * i + 1) / (2.0 * N) * u * Math.PI) * Math.cos((2 * j + 1) / (2.0 * N) * v * Math.PI) * f[i][j];\n }\n }\n sum *= c[u] * c[v] / 4;\n F[u][v] = sum;\n }\n }\n return F;\n}\nexport default ImagePHash;\n//# sourceMappingURL=phash.js.map","import \"isomorphic-fetch\";\nexport default ((_ref, cb) => {\n let {\n url,\n ...options\n } = _ref;\n fetch(url, options).then(response => {\n if (response.ok) {\n return response.arrayBuffer().catch(error => {\n throw new Error(`Response is not a buffer for url ${url}. Error: ${error.message}`);\n });\n }\n throw new Error(`HTTP Status ${response.status} for url ${url}`);\n }).then(data => cb(null, data)).catch(error => cb(error));\n});\n//# sourceMappingURL=request.js.map","// used to auto resizing etc.\nexport const AUTO = -1;\n\n// Align modes for cover, contain, bit masks\nexport const HORIZONTAL_ALIGN_LEFT = 1;\nexport const HORIZONTAL_ALIGN_CENTER = 2;\nexport const HORIZONTAL_ALIGN_RIGHT = 4;\nexport const VERTICAL_ALIGN_TOP = 8;\nexport const VERTICAL_ALIGN_MIDDLE = 16;\nexport const VERTICAL_ALIGN_BOTTOM = 32;\n\n// blend modes\nexport const BLEND_SOURCE_OVER = \"srcOver\";\nexport const BLEND_DESTINATION_OVER = \"dstOver\";\nexport const BLEND_MULTIPLY = \"multiply\";\nexport const BLEND_ADD = \"add\";\nexport const BLEND_SCREEN = \"screen\";\nexport const BLEND_OVERLAY = \"overlay\";\nexport const BLEND_DARKEN = \"darken\";\nexport const BLEND_LIGHTEN = \"lighten\";\nexport const BLEND_HARDLIGHT = \"hardLight\";\nexport const BLEND_DIFFERENCE = \"difference\";\nexport const BLEND_EXCLUSION = \"exclusion\";\n\n// Edge Handling\nexport const EDGE_EXTEND = 1;\nexport const EDGE_WRAP = 2;\nexport const EDGE_CROP = 3;\n//# sourceMappingURL=constants.js.map","export function srcOver(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const r = (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a;\n const g = (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a;\n const b = (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function dstOver(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const r = (dst.r * dst.a + src.r * src.a * (1 - dst.a)) / a;\n const g = (dst.g * dst.a + src.g * src.a * (1 - dst.a)) / a;\n const b = (dst.b * dst.a + src.b * src.a * (1 - dst.a)) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function multiply(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;\n const g = (sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;\n const b = (sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function add(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (sra + dra) / a;\n const g = (sga + dga) / a;\n const b = (sba + dba) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function screen(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (sra * dst.a + dra * src.a - sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;\n const g = (sga * dst.a + dga * src.a - sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;\n const b = (sba * dst.a + dba * src.a - sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function overlay(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (2 * dra <= dst.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a;\n const g = (2 * dga <= dst.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a;\n const b = (2 * dba <= dst.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function darken(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (Math.min(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a;\n const g = (Math.min(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a;\n const b = (Math.min(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function lighten(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (Math.max(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a;\n const g = (Math.max(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a;\n const b = (Math.max(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function hardLight(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (2 * sra <= src.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a;\n const g = (2 * sga <= src.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a;\n const b = (2 * sba <= src.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function difference(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (sra + dra - 2 * Math.min(sra * dst.a, dra * src.a)) / a;\n const g = (sga + dga - 2 * Math.min(sga * dst.a, dga * src.a)) / a;\n const b = (sba + dba - 2 * Math.min(sba * dst.a, dba * src.a)) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\nexport function exclusion(src, dst) {\n let ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n src.a *= ops;\n const a = dst.a + src.a - dst.a * src.a;\n const sra = src.r * src.a;\n const sga = src.g * src.a;\n const sba = src.b * src.a;\n const dra = dst.r * dst.a;\n const dga = dst.g * dst.a;\n const dba = dst.b * dst.a;\n const r = (sra * dst.a + dra * src.a - 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;\n const g = (sga * dst.a + dga * src.a - 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;\n const b = (sba * dst.a + dba * src.a - 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;\n return {\n r,\n g,\n b,\n a\n };\n}\n//# sourceMappingURL=composite-modes.js.map","const promisify = function (fun, ctx) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return new Promise((resolve, reject) => {\n args.push((err, data) => {\n if (err) {\n reject(err);\n }\n resolve(data);\n });\n fun.bind(ctx)(...args);\n });\n};\nexport default promisify;\n//# sourceMappingURL=promisify.js.map","const mimeTypes = {};\nconst findType = extension => Object.entries(mimeTypes).find(type => type[1].includes(extension)) || [];\nexport const addType = (mime, extensions) => {\n mimeTypes[mime] = extensions;\n};\n\n/**\n * Lookup a mime type based on extension\n * @param {string} path path to find extension for\n * @returns {string} mime found mime type\n */\nexport const getType = path => {\n const pathParts = path.split(\"/\").slice(-1);\n const extension = pathParts[pathParts.length - 1].split(\".\").pop();\n const type = findType(extension);\n return type[0];\n};\n\n/**\n * Return file extension associated with a mime type\n * @param {string} type mime type to look up\n * @returns {string} extension file extension\n */\nexport const getExtension = type => (mimeTypes[type.toLowerCase()] || [])[0];\n//# sourceMappingURL=mime.js.map","import FileType from \"file-type\";\nimport EXIFParser from \"exif-parser\";\nimport { throwError } from \"@jimp/utils\";\nimport * as constants from \"../constants\";\nimport * as MIME from \"./mime\";\nimport promisify from \"./promisify\";\nasync function getMIMEFromBuffer(buffer, path) {\n const fileTypeFromBuffer = await FileType.fromBuffer(buffer);\n if (fileTypeFromBuffer) {\n // If fileType returns something for buffer, then return the mime given\n return fileTypeFromBuffer.mime;\n }\n if (path) {\n // If a path is supplied, and fileType yields no results, then retry with MIME\n // Path can be either a file path or a url\n return MIME.getType(path);\n }\n return null;\n}\n\n/*\n * Obtains image orientation from EXIF metadata.\n *\n * @param img {Jimp} a Jimp image object\n * @returns {number} a number 1-8 representing EXIF orientation,\n * in particular 1 if orientation tag is missing\n */\nfunction getExifOrientation(img) {\n return img._exif && img._exif.tags && img._exif.tags.Orientation || 1;\n}\n\n/**\n * Returns a function which translates EXIF-rotated coordinates into\n * non-rotated ones.\n *\n * Transformation reference: http://sylvana.net/jpegcrop/exif_orientation.html.\n *\n * @param img {Jimp} a Jimp image object\n * @returns {function} transformation function for transformBitmap().\n */\nfunction getExifOrientationTransformation(img) {\n const w = img.getWidth();\n const h = img.getHeight();\n switch (getExifOrientation(img)) {\n case 1:\n // Horizontal (normal)\n // does not need to be supported here\n return null;\n case 2:\n // Mirror horizontal\n return function (x, y) {\n return [w - x - 1, y];\n };\n case 3:\n // Rotate 180\n return function (x, y) {\n return [w - x - 1, h - y - 1];\n };\n case 4:\n // Mirror vertical\n return function (x, y) {\n return [x, h - y - 1];\n };\n case 5:\n // Mirror horizontal and rotate 270 CW\n return function (x, y) {\n return [y, x];\n };\n case 6:\n // Rotate 90 CW\n return function (x, y) {\n return [y, h - x - 1];\n };\n case 7:\n // Mirror horizontal and rotate 90 CW\n return function (x, y) {\n return [w - y - 1, h - x - 1];\n };\n case 8:\n // Rotate 270 CW\n return function (x, y) {\n return [w - y - 1, x];\n };\n default:\n return null;\n }\n}\n\n/*\n * Transforms bitmap in place (moves pixels around) according to given\n * transformation function.\n *\n * @param img {Jimp} a Jimp image object, which bitmap is supposed to\n * be transformed\n * @param width {number} bitmap width after the transformation\n * @param height {number} bitmap height after the transformation\n * @param transformation {function} transformation function which defines pixel\n * mapping between new and source bitmap. It takes a pair of coordinates\n * in the target, and returns a respective pair of coordinates in\n * the source bitmap, i.e. has following form:\n * `function(new_x, new_y) { return [src_x, src_y] }`.\n */\nfunction transformBitmap(img, width, height, transformation) {\n // Underscore-prefixed values are related to the source bitmap\n // Their counterparts with no prefix are related to the target bitmap\n const _data = img.bitmap.data;\n const _width = img.bitmap.width;\n const data = Buffer.alloc(_data.length);\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n const [_x, _y] = transformation(x, y);\n const idx = width * y + x << 2;\n const _idx = _width * _y + _x << 2;\n const pixel = _data.readUInt32BE(_idx);\n data.writeUInt32BE(pixel, idx);\n }\n }\n img.bitmap.data = data;\n img.bitmap.width = width;\n img.bitmap.height = height;\n}\n\n/*\n * Automagically rotates an image based on its EXIF data (if present).\n * @param img {Jimp} a Jimp image object\n */\nfunction exifRotate(img) {\n if (getExifOrientation(img) < 2) return;\n const transformation = getExifOrientationTransformation(img);\n const swapDimensions = getExifOrientation(img) > 4;\n const newWidth = swapDimensions ? img.bitmap.height : img.bitmap.width;\n const newHeight = swapDimensions ? img.bitmap.width : img.bitmap.height;\n transformBitmap(img, newWidth, newHeight, transformation);\n}\n\n// parses a bitmap from the constructor to the JIMP bitmap property\nexport async function parseBitmap(data, path, cb) {\n const mime = await getMIMEFromBuffer(data, path);\n if (typeof mime !== \"string\") {\n return cb(new Error(\"Could not find MIME for Buffer <\" + path + \">\"));\n }\n this._originalMime = mime.toLowerCase();\n try {\n const mime = this.getMIME();\n if (this.constructor.decoders[mime]) {\n this.bitmap = this.constructor.decoders[mime](data);\n } else {\n return throwError.call(this, \"Unsupported MIME type: \" + mime, cb);\n }\n } catch (error) {\n return cb.call(this, error, this);\n }\n try {\n this._exif = EXIFParser.create(data).parse();\n exifRotate(this); // EXIF data\n } catch (error) {\n /* meh */\n }\n cb.call(this, null, this);\n return this;\n}\nfunction compositeBitmapOverBackground(Jimp, image) {\n return new Jimp(image.bitmap.width, image.bitmap.height, image._background).composite(image, 0, 0).bitmap;\n}\n\n/**\n * Converts the image to a buffer\n * @param {(string|number)} mime the mime type of the image buffer to be created\n * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument\n * @returns {Jimp} this for chaining of methods\n */\nexport function getBuffer(mime, cb) {\n if (mime === constants.AUTO) {\n // allow auto MIME detection\n mime = this.getMIME();\n }\n if (typeof mime !== \"string\") {\n return throwError.call(this, \"mime must be a string\", cb);\n }\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", cb);\n }\n mime = mime.toLowerCase();\n if (this._rgba && this.constructor.hasAlpha[mime]) {\n this.bitmap.data = Buffer.from(this.bitmap.data);\n } else {\n // when format doesn't support alpha\n // composite onto a new image so that the background shows through alpha channels\n this.bitmap.data = compositeBitmapOverBackground(this.constructor, this).data;\n }\n if (this.constructor.encoders[mime]) {\n const buffer = this.constructor.encoders[mime](this);\n // Typically, buffers return a string or map. However, the gif library \"gifwrap\" seemingly returns promises.\n if (buffer instanceof Promise) {\n // trigger the callback when the promise has been resolved\n buffer.then(buff => {\n cb.call(this, null, buff);\n });\n } else {\n cb.call(this, null, buffer);\n }\n } else {\n return throwError.call(this, \"Unsupported MIME type: \" + mime, cb);\n }\n return this;\n}\nexport function getBufferAsync(mime) {\n return promisify(getBuffer, this, mime);\n}\n//# sourceMappingURL=image-bitmap.js.map","function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nimport fs from \"fs\";\nimport Path from \"path\";\nimport EventEmitter from \"events\";\nimport { isNodePattern, throwError, scan, scanIterator } from \"@jimp/utils\";\nimport anyBase from \"any-base\";\nimport pixelMatch from \"pixelmatch\";\nimport tinyColor from \"tinycolor2\";\nimport ImagePHash from \"./modules/phash\";\nimport request from \"./request\";\nimport composite from \"./composite\";\nimport promisify from \"./utils/promisify\";\nimport * as MIME from \"./utils/mime\";\nimport { parseBitmap, getBuffer, getBufferAsync } from \"./utils/image-bitmap\";\nimport * as constants from \"./constants\";\nconst alphabet = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_\";\n\n// an array storing the maximum string length of hashes at various bases\n// 0 and 1 do not exist as possible hash lengths\nconst maxHashLength = [NaN, NaN];\nfor (let i = 2; i < 65; i++) {\n const maxHash = anyBase(anyBase.BIN, alphabet.slice(0, i))(new Array(64 + 1).join(\"1\"));\n maxHashLength.push(maxHash.length);\n}\n\n// no operation\nfunction noop() {}\n\n// error checking methods\n\nfunction isArrayBuffer(test) {\n return Object.prototype.toString.call(test).toLowerCase().indexOf(\"arraybuffer\") > -1;\n}\n\n// Prepare a Buffer object from the arrayBuffer. Necessary in the browser > node conversion,\n// But this function is not useful when running in node directly\nfunction bufferFromArrayBuffer(arrayBuffer) {\n const buffer = Buffer.alloc(arrayBuffer.byteLength);\n const view = new Uint8Array(arrayBuffer);\n for (let i = 0; i < buffer.length; ++i) {\n buffer[i] = view[i];\n }\n return buffer;\n}\nfunction loadFromURL(options, cb) {\n request(options, (err, data) => {\n if (err) {\n return cb(err);\n }\n if (typeof data === \"object\" && Buffer.isBuffer(data)) {\n return cb(null, data);\n }\n if (typeof data === \"object\" && isArrayBuffer(data)) {\n return cb(null, bufferFromArrayBuffer(data));\n }\n return new Error(`Could not load Buffer from <${options.url}>`);\n });\n}\nfunction loadBufferFromPath(src, cb) {\n if (fs && typeof fs.readFile === \"function\" && !src.match(/^(http|ftp)s?:\\/\\/./)) {\n fs.readFile(src, cb);\n } else {\n loadFromURL({\n url: src\n }, cb);\n }\n}\nfunction isRawRGBAData(obj) {\n return obj && typeof obj === \"object\" && typeof obj.width === \"number\" && typeof obj.height === \"number\" && (Buffer.isBuffer(obj.data) || obj.data instanceof Uint8Array || typeof Uint8ClampedArray === \"function\" && obj.data instanceof Uint8ClampedArray) && (obj.data.length === obj.width * obj.height * 4 || obj.data.length === obj.width * obj.height * 3);\n}\nfunction makeRGBABufferFromRGB(buffer) {\n if (buffer.length % 3 !== 0) {\n throw new Error(\"Buffer length is incorrect\");\n }\n const rgbaBuffer = Buffer.allocUnsafe(buffer.length / 3 * 4);\n let j = 0;\n for (let i = 0; i < buffer.length; i++) {\n rgbaBuffer[j] = buffer[i];\n if ((i + 1) % 3 === 0) {\n rgbaBuffer[++j] = 255;\n }\n j++;\n }\n return rgbaBuffer;\n}\nconst emptyBitmap = {\n data: null,\n width: null,\n height: null\n};\n\n/**\n * Jimp constructor (from a file)\n * @param path a path to the image\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (from a url with options)\n * @param options { url, otherOptions}\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (from another Jimp image or raw image data)\n * @param image a Jimp image to clone\n * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (from a Buffer)\n * @param data a Buffer containing the image data\n * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (to generate a new image)\n * @param w the width of the image\n * @param h the height of the image\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap\n */\n\n/**\n * Jimp constructor (to generate a new image)\n * @param w the width of the image\n * @param h the height of the image\n * @param background color to fill the image with\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap\n */\n\nclass Jimp extends EventEmitter {\n // An object representing a bitmap in memory, comprising:\n // - data: a buffer of the bitmap data\n // - width: the width of the image in pixels\n // - height: the height of the image in pixels\n\n // Default colour to use for new pixels\n\n // Default MIME is PNG\n\n // Exif data for the image\n\n // Whether Transparency supporting formats will be exported as RGB or RGBA\n\n constructor() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n super();\n _defineProperty(this, \"bitmap\", emptyBitmap);\n _defineProperty(this, \"_background\", 0x00000000);\n _defineProperty(this, \"_originalMime\", Jimp.MIME_PNG);\n _defineProperty(this, \"_exif\", null);\n _defineProperty(this, \"_rgba\", true);\n _defineProperty(this, \"writeAsync\", path => promisify(this.write, this, path));\n _defineProperty(this, \"getBase64Async\", mime => promisify(this.getBase64, this, mime));\n _defineProperty(this, \"getBuffer\", getBuffer);\n _defineProperty(this, \"getBufferAsync\", getBufferAsync);\n _defineProperty(this, \"getPixelColour\", this.getPixelColor);\n _defineProperty(this, \"setPixelColour\", this.setPixelColor);\n const jimpInstance = this;\n let cb = noop;\n if (isArrayBuffer(args[0])) {\n args[0] = bufferFromArrayBuffer(args[0]);\n }\n function finish() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n const [err] = args;\n const evData = err || {};\n evData.methodName = \"constructor\";\n setTimeout(() => {\n // run on next tick.\n if (err && cb === noop) {\n jimpInstance.emitError(\"constructor\", err);\n } else if (!err) {\n jimpInstance.emitMulti(\"constructor\", \"initialized\");\n }\n cb.call(jimpInstance, ...args);\n }, 1);\n }\n if (typeof args[0] === \"number\" && typeof args[1] === \"number\" || parseInt(args[0], 10) && parseInt(args[1], 10)) {\n // create a new image\n const w = parseInt(args[0], 10);\n const h = parseInt(args[1], 10);\n cb = args[2];\n\n // with a hex color\n if (typeof args[2] === \"number\") {\n this._background = args[2];\n cb = args[3];\n }\n\n // with a css color\n if (typeof args[2] === \"string\") {\n this._background = Jimp.cssColorToHex(args[2]);\n cb = args[3];\n }\n if (typeof cb === \"undefined\") {\n cb = noop;\n }\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n this.bitmap = {\n data: Buffer.alloc(w * h * 4),\n width: w,\n height: h\n };\n for (let i = 0; i < this.bitmap.data.length; i += 4) {\n this.bitmap.data.writeUInt32BE(this._background, i);\n }\n finish(null, this);\n } else if (typeof args[0] === \"object\" && args[0].url) {\n cb = args[1] || noop;\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n loadFromURL(args[0], (err, data) => {\n if (err) {\n return throwError.call(this, err, finish);\n }\n this.parseBitmap(data, args[0].url, finish);\n });\n } else if (args[0] instanceof Jimp) {\n // clone an existing Jimp\n const [original] = args;\n cb = args[1];\n if (typeof cb === \"undefined\") {\n cb = noop;\n }\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n this.bitmap = {\n data: Buffer.from(original.bitmap.data),\n width: original.bitmap.width,\n height: original.bitmap.height\n };\n this._quality = original._quality;\n this._deflateLevel = original._deflateLevel;\n this._deflateStrategy = original._deflateStrategy;\n this._filterType = original._filterType;\n this._rgba = original._rgba;\n this._background = original._background;\n this._originalMime = original._originalMime;\n finish(null, this);\n } else if (isRawRGBAData(args[0])) {\n const [imageData] = args;\n cb = args[1] || noop;\n const isRGBA = imageData.width * imageData.height * 4 === imageData.data.length;\n const buffer = isRGBA ? Buffer.from(imageData.data) : makeRGBABufferFromRGB(imageData.data);\n this.bitmap = {\n data: buffer,\n width: imageData.width,\n height: imageData.height\n };\n finish(null, this);\n } else if (typeof args[0] === \"string\") {\n // read from a path\n const path = args[0];\n cb = args[1];\n if (typeof cb === \"undefined\") {\n cb = noop;\n }\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n loadBufferFromPath(path, (err, data) => {\n if (err) {\n return throwError.call(this, err, finish);\n }\n this.parseBitmap(data, path, finish);\n });\n } else if (typeof args[0] === \"object\" && Buffer.isBuffer(args[0])) {\n // read from a buffer\n const data = args[0];\n cb = args[1];\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", finish);\n }\n this.parseBitmap(data, null, finish);\n } else {\n // Allow client libs to add new ways to build a Jimp object.\n // Extra constructors must be added by `Jimp.appendConstructorOption()`\n cb = args[args.length - 1];\n if (typeof cb !== \"function\") {\n // TODO: try to solve the args after cb problem.\n cb = args[args.length - 2];\n if (typeof cb !== \"function\") {\n cb = noop;\n }\n }\n const extraConstructor = Jimp.__extraConstructors.find(c => c.test(...args));\n if (extraConstructor) {\n new Promise((resolve, reject) => {\n extraConstructor.run.call(this, resolve, reject, ...args);\n }).then(() => finish(null, this)).catch(finish);\n } else {\n return throwError.call(this, \"No matching constructor overloading was found. \" + \"Please see the docs for how to call the Jimp constructor.\", finish);\n }\n }\n }\n\n /**\n * Parse a bitmap with the loaded image types.\n *\n * @param {Buffer} data raw image data\n * @param {string} path optional path to file\n * @param {function(Error, Jimp)} finish (optional) a callback for when complete\n * @memberof Jimp\n */\n parseBitmap(data, path, finish) {\n parseBitmap.call(this, data, null, finish);\n }\n\n /**\n * Sets the type of the image (RGB or RGBA) when saving in a format that supports transparency (default is RGBA)\n * @param {boolean} bool A Boolean, true to use RGBA or false to use RGB\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n rgba(bool, cb) {\n if (typeof bool !== \"boolean\") {\n return throwError.call(this, \"bool must be a boolean, true for RGBA or false for RGB\", cb);\n }\n this._rgba = bool;\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n\n /**\n * Emit for multiple listeners\n * @param {string} methodName name of the method to emit an error for\n * @param {string} eventName name of the eventName to emit an error for\n * @param {object} data to emit\n */\n emitMulti(methodName, eventName) {\n let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n data = Object.assign(data, {\n methodName,\n eventName\n });\n this.emit(\"any\", data);\n if (methodName) {\n this.emit(methodName, data);\n }\n this.emit(eventName, data);\n }\n emitError(methodName, err) {\n this.emitMulti(methodName, \"error\", err);\n }\n\n /**\n * Get the current height of the image\n * @return {number} height of the image\n */\n getHeight() {\n return this.bitmap.height;\n }\n\n /**\n * Get the current width of the image\n * @return {number} width of the image\n */\n getWidth() {\n return this.bitmap.width;\n }\n\n /**\n * Nicely format Jimp object when sent to the console e.g. console.log(image)\n * @returns {string} pretty printed\n */\n inspect() {\n return \"\";\n }\n\n /**\n * Nicely format Jimp object when converted to a string\n * @returns {string} pretty printed\n */\n toString() {\n return \"[object Jimp]\";\n }\n\n /**\n * Returns the original MIME of the image (default: \"image/png\")\n * @returns {string} the MIME\n */\n getMIME() {\n const mime = this._originalMime || Jimp.MIME_PNG;\n return mime;\n }\n\n /**\n * Returns the appropriate file extension for the original MIME of the image (default: \"png\")\n * @returns {string} the file extension\n */\n getExtension() {\n const mime = this.getMIME();\n return MIME.getExtension(mime);\n }\n\n /**\n * Writes the image to a file\n * @param {string} path a path to the destination file\n * @param {function(Error, Jimp)} cb (optional) a function to call when the image is saved to disk\n * @returns {Jimp} this for chaining of methods\n */\n write(path, cb) {\n if (!fs || !fs.createWriteStream) {\n throw new Error(\"Cant access the filesystem. You can use the getBase64 method.\");\n }\n if (typeof path !== \"string\") {\n return throwError.call(this, \"path must be a string\", cb);\n }\n if (typeof cb === \"undefined\") {\n cb = noop;\n }\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", cb);\n }\n const mime = MIME.getType(path) || this.getMIME();\n const pathObj = Path.parse(path);\n if (pathObj.dir) {\n fs.mkdirSync(pathObj.dir, {\n recursive: true\n });\n }\n this.getBuffer(mime, (err, buffer) => {\n if (err) {\n return throwError.call(this, err, cb);\n }\n const stream = fs.createWriteStream(path);\n stream.on(\"open\", () => {\n stream.write(buffer);\n stream.end();\n }).on(\"error\", err => {\n return throwError.call(this, err, cb);\n });\n stream.on(\"finish\", () => {\n cb.call(this, null, this);\n });\n });\n return this;\n }\n /**\n * Converts the image to a base 64 string\n * @param {string} mime the mime type of the image data to be created\n * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument\n * @returns {Jimp} this for chaining of methods\n */\n getBase64(mime, cb) {\n if (mime === Jimp.AUTO) {\n // allow auto MIME detection\n mime = this.getMIME();\n }\n if (typeof mime !== \"string\") {\n return throwError.call(this, \"mime must be a string\", cb);\n }\n if (typeof cb !== \"function\") {\n return throwError.call(this, \"cb must be a function\", cb);\n }\n this.getBuffer(mime, function (err, data) {\n if (err) {\n return throwError.call(this, err, cb);\n }\n const src = \"data:\" + mime + \";base64,\" + data.toString(\"base64\");\n cb.call(this, null, src);\n });\n return this;\n }\n /**\n * Generates a perceptual hash of the image . And pads the string. Can configure base.\n * @param {number} base (optional) a number between 2 and 64 representing the base for the hash (e.g. 2 is binary, 10 is decimal, 16 is hex, 64 is base 64). Defaults to 64.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {string} a string representing the hash\n */\n hash(base, cb) {\n base = base || 64;\n if (typeof base === \"function\") {\n cb = base;\n base = 64;\n }\n if (typeof base !== \"number\") {\n return throwError.call(this, \"base must be a number\", cb);\n }\n if (base < 2 || base > 64) {\n return throwError.call(this, \"base must be a number between 2 and 64\", cb);\n }\n let hash = this.pHash();\n hash = anyBase(anyBase.BIN, alphabet.slice(0, base))(hash);\n while (hash.length < maxHashLength[base]) {\n hash = \"0\" + hash; // pad out with leading zeros\n }\n\n if (isNodePattern(cb)) {\n cb.call(this, null, hash);\n }\n return hash;\n }\n\n /**\n * Calculates the perceptual hash\n * @returns {number} the perceptual hash\n */\n pHash() {\n const pHash = new ImagePHash();\n return pHash.getHash(this);\n }\n\n /**\n * Calculates the hamming distance of the current image and a hash based on their perceptual hash\n * @param {hash} compareHash hash to compare to\n * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical\n */\n distanceFromHash(compareHash) {\n const pHash = new ImagePHash();\n const currentHash = pHash.getHash(this);\n return pHash.distance(currentHash, compareHash);\n }\n\n /**\n * Converts the image to a buffer\n * @param {string} mime the mime type of the image buffer to be created\n * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument\n * @returns {Jimp} this for chaining of methods\n */\n\n /**\n * Returns the offset of a pixel in the bitmap buffer\n * @param {number} x the x coordinate\n * @param {number} y the y coordinate\n * @param {number} edgeHandling (optional) define how to sum pixels from outside the border\n * @param {number} cb (optional) a callback for when complete\n * @returns {number} the index of the pixel or -1 if not found\n */\n getPixelIndex(x, y, edgeHandling, cb) {\n let xi;\n let yi;\n if (typeof edgeHandling === \"function\" && typeof cb === \"undefined\") {\n cb = edgeHandling;\n edgeHandling = null;\n }\n if (!edgeHandling) {\n edgeHandling = Jimp.EDGE_EXTEND;\n }\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n xi = x;\n yi = y;\n if (edgeHandling === Jimp.EDGE_EXTEND) {\n if (x < 0) xi = 0;\n if (x >= this.bitmap.width) xi = this.bitmap.width - 1;\n if (y < 0) yi = 0;\n if (y >= this.bitmap.height) yi = this.bitmap.height - 1;\n }\n if (edgeHandling === Jimp.EDGE_WRAP) {\n if (x < 0) {\n xi = this.bitmap.width + x;\n }\n if (x >= this.bitmap.width) {\n xi = x % this.bitmap.width;\n }\n if (y < 0) {\n yi = this.bitmap.height + y;\n }\n if (y >= this.bitmap.height) {\n yi = y % this.bitmap.height;\n }\n }\n let i = this.bitmap.width * yi + xi << 2;\n\n // if out of bounds index is -1\n if (xi < 0 || xi >= this.bitmap.width) {\n i = -1;\n }\n if (yi < 0 || yi >= this.bitmap.height) {\n i = -1;\n }\n if (isNodePattern(cb)) {\n cb.call(this, null, i);\n }\n return i;\n }\n\n /**\n * Returns the hex colour value of a pixel\n * @param {number} x the x coordinate\n * @param {number} y the y coordinate\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {number} the color of the pixel\n */\n getPixelColor(x, y, cb) {\n if (typeof x !== \"number\" || typeof y !== \"number\") return throwError.call(this, \"x and y must be numbers\", cb);\n const idx = this.getPixelIndex(x, y);\n const hex = this.bitmap.data.readUInt32BE(idx);\n if (isNodePattern(cb)) {\n cb.call(this, null, hex);\n }\n return hex;\n }\n /**\n * Returns the hex colour value of a pixel\n * @param {number} hex color to set\n * @param {number} x the x coordinate\n * @param {number} y the y coordinate\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {number} the index of the pixel or -1 if not found\n */\n setPixelColor(hex, x, y, cb) {\n if (typeof hex !== \"number\" || typeof x !== \"number\" || typeof y !== \"number\") return throwError.call(this, \"hex, x and y must be numbers\", cb);\n const idx = this.getPixelIndex(x, y);\n this.bitmap.data.writeUInt32BE(hex, idx);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n /**\n * Determine if the image contains opaque pixels.\n * @return {boolean} hasAlpha whether the image contains opaque pixels\n */\n hasAlpha() {\n const {\n width,\n height,\n data\n } = this.bitmap;\n const byteLen = width * height << 2;\n for (let idx = 3; idx < byteLen; idx += 4) {\n if (data[idx] !== 0xff) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Iterate scan through a region of the bitmap\n * @param {number} x the x coordinate to begin the scan at\n * @param {number} y the y coordinate to begin the scan at\n * @param w the width of the scan region\n * @param h the height of the scan region\n * @returns {IterableIterator<{x: number, y: number, idx: number, image: Jimp}>}\n */\n scanIterator(x, y, w, h) {\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\");\n }\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\");\n }\n return scanIterator(this, x, y, w, h);\n }\n}\nexport function addConstants(constants) {\n let jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp;\n Object.entries(constants).forEach(_ref => {\n let [name, value] = _ref;\n jimpInstance[name] = value;\n });\n}\nexport function addJimpMethods(methods) {\n let jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp;\n Object.entries(methods).forEach(_ref2 => {\n let [name, value] = _ref2;\n jimpInstance.prototype[name] = value;\n });\n}\naddConstants(constants);\naddJimpMethods({\n composite\n});\nJimp.__extraConstructors = [];\n\n/**\n * Allow client libs to add new ways to build a Jimp object.\n * @param {string} name identify the extra constructor.\n * @param {function} test a function that returns true when it accepts the arguments passed to the main constructor.\n * @param {function} run where the magic happens.\n */\nJimp.appendConstructorOption = function (name, test, run) {\n Jimp.__extraConstructors.push({\n name,\n test,\n run\n });\n};\n\n/**\n * Read an image from a file or a Buffer. Takes the same args as the constructor\n * @returns {Promise} a promise\n */\nJimp.read = function () {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n args[_key3] = arguments[_key3];\n }\n return new Promise((resolve, reject) => {\n // eslint-disable-next-line no-new\n new Jimp(...args, (err, image) => {\n if (err) reject(err);else resolve(image);\n });\n });\n};\nJimp.create = Jimp.read;\n\n/**\n * A static helper method that converts RGBA values to a single integer value\n * @param {number} r the red value (0-255)\n * @param {number} g the green value (0-255)\n * @param {number} b the blue value (0-255)\n * @param {number} a the alpha value (0-255)\n * @param {function(Error, Jimp)} cb (optional) A callback for when complete\n * @returns {number} an single integer colour value\n */\nJimp.rgbaToInt = function (r, g, b, a, cb) {\n if (typeof r !== \"number\" || typeof g !== \"number\" || typeof b !== \"number\" || typeof a !== \"number\") {\n return throwError.call(this, \"r, g, b and a must be numbers\", cb);\n }\n if (r < 0 || r > 255) {\n return throwError.call(this, \"r must be between 0 and 255\", cb);\n }\n if (g < 0 || g > 255) {\n throwError.call(this, \"g must be between 0 and 255\", cb);\n }\n if (b < 0 || b > 255) {\n return throwError.call(this, \"b must be between 0 and 255\", cb);\n }\n if (a < 0 || a > 255) {\n return throwError.call(this, \"a must be between 0 and 255\", cb);\n }\n let i = r & 0xff;\n i <<= 8;\n i |= g & 0xff;\n i <<= 8;\n i |= b & 0xff;\n i <<= 8;\n i |= a & 0xff;\n\n // Ensure sign is correct\n i >>>= 0;\n if (isNodePattern(cb)) {\n cb.call(this, null, i);\n }\n return i;\n};\n\n/**\n * A static helper method that converts RGBA values to a single integer value\n * @param {number} i a single integer value representing an RGBA colour (e.g. 0xFF0000FF for red)\n * @param {function(Error, Jimp)} cb (optional) A callback for when complete\n * @returns {object} an object with the properties r, g, b and a representing RGBA values\n */\nJimp.intToRGBA = function (i, cb) {\n if (typeof i !== \"number\") {\n return throwError.call(this, \"i must be a number\", cb);\n }\n const rgba = {};\n rgba.r = Math.floor(i / Math.pow(256, 3));\n rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2));\n rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1));\n rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0));\n if (isNodePattern(cb)) {\n cb.call(this, null, rgba);\n }\n return rgba;\n};\n\n/**\n * Converts a css color (Hex, 8-digit (RGBA) Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to a hex number\n * @param {string} cssColor a number\n * @returns {number} a hex number representing a color\n */\nJimp.cssColorToHex = function (cssColor) {\n cssColor = cssColor || 0; // 0, null, undefined, NaN\n\n if (typeof cssColor === \"number\") return Number(cssColor);\n return parseInt(tinyColor(cssColor).toHex8(), 16);\n};\n\n/**\n * Limits a number to between 0 or 255\n * @param {number} n a number\n * @returns {number} the number limited to between 0 or 255\n */\nJimp.limit255 = function (n) {\n n = Math.max(n, 0);\n n = Math.min(n, 255);\n return n;\n};\n\n/**\n * Diffs two images and returns\n * @param {Jimp} img1 a Jimp image to compare\n * @param {Jimp} img2 a Jimp image to compare\n * @param {number} threshold (optional) a number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1)\n * @returns {object} an object { percent: percent similar, diff: a Jimp image highlighting differences }\n */\nJimp.diff = function (img1, img2) {\n let threshold = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.1;\n if (!(img1 instanceof Jimp) || !(img2 instanceof Jimp)) return throwError.call(this, \"img1 and img2 must be an Jimp images\");\n const bmp1 = img1.bitmap;\n const bmp2 = img2.bitmap;\n if (bmp1.width !== bmp2.width || bmp1.height !== bmp2.height) {\n if (bmp1.width * bmp1.height > bmp2.width * bmp2.height) {\n // img1 is bigger\n img1 = img1.cloneQuiet().resize(bmp2.width, bmp2.height);\n } else {\n // img2 is bigger (or they are the same in area)\n img2 = img2.cloneQuiet().resize(bmp1.width, bmp1.height);\n }\n }\n if (typeof threshold !== \"number\" || threshold < 0 || threshold > 1) {\n return throwError.call(this, \"threshold must be a number between 0 and 1\");\n }\n const diff = new Jimp(bmp1.width, bmp1.height, 0xffffffff);\n const numDiffPixels = pixelMatch(bmp1.data, bmp2.data, diff.bitmap.data, diff.bitmap.width, diff.bitmap.height, {\n threshold\n });\n return {\n percent: numDiffPixels / (diff.bitmap.width * diff.bitmap.height),\n image: diff\n };\n};\n\n/**\n * Calculates the hamming distance of two images based on their perceptual hash\n * @param {Jimp} img1 a Jimp image to compare\n * @param {Jimp} img2 a Jimp image to compare\n * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical\n */\nJimp.distance = function (img1, img2) {\n const phash = new ImagePHash();\n const hash1 = phash.getHash(img1);\n const hash2 = phash.getHash(img2);\n return phash.distance(hash1, hash2);\n};\n\n/**\n * Calculates the hamming distance of two images based on their perceptual hash\n * @param {hash} hash1 a pHash\n * @param {hash} hash2 a pHash\n * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical\n */\nJimp.compareHashes = function (hash1, hash2) {\n const phash = new ImagePHash();\n return phash.distance(hash1, hash2);\n};\n\n/**\n * Compute color difference\n * 0 means no difference, 1 means maximum difference.\n * @param {number} rgba1: first color to compare.\n * @param {number} rgba2: second color to compare.\n * Both parameters must be an color object {r:val, g:val, b:val, a:val}\n * Where `a` is optional and `val` is an integer between 0 and 255.\n * @returns {number} float between 0 and 1.\n */\nJimp.colorDiff = function (rgba1, rgba2) {\n const pow = n => Math.pow(n, 2);\n const {\n max\n } = Math;\n const maxVal = 255 * 255 * 3;\n if (rgba1.a !== 0 && !rgba1.a) {\n rgba1.a = 255;\n }\n if (rgba2.a !== 0 && !rgba2.a) {\n rgba2.a = 255;\n }\n return (max(pow(rgba1.r - rgba2.r), pow(rgba1.r - rgba2.r - rgba1.a + rgba2.a)) + max(pow(rgba1.g - rgba2.g), pow(rgba1.g - rgba2.g - rgba1.a + rgba2.a)) + max(pow(rgba1.b - rgba2.b), pow(rgba1.b - rgba2.b - rgba1.a + rgba2.a))) / maxVal;\n};\n\n/**\n * Helper to create Jimp methods that emit events before and after its execution.\n * @param {string} methodName The name to be appended to Jimp prototype.\n * @param {string} evName The event name to be called.\n * It will be prefixed by `before-` and emitted when on method call.\n * It will be appended by `ed` and emitted after the method run.\n * @param {function} method A function implementing the method itself.\n * It will also create a quiet version that will not emit events, to not\n * mess the user code with many `changed` event calls. You can call with\n * `methodName + \"Quiet\"`.\n *\n * The emitted event comes with a object parameter to the listener with the\n * `methodName` as one attribute.\n */\nexport function jimpEvMethod(methodName, evName, method) {\n const evNameBefore = \"before-\" + evName;\n const evNameAfter = evName.replace(/e$/, \"\") + \"ed\";\n Jimp.prototype[methodName] = function () {\n let wrappedCb;\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n const cb = args[method.length - 1];\n const jimpInstance = this;\n if (typeof cb === \"function\") {\n wrappedCb = function () {\n for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n args[_key5] = arguments[_key5];\n }\n const [err, data] = args;\n if (err) {\n jimpInstance.emitError(methodName, err);\n } else {\n jimpInstance.emitMulti(methodName, evNameAfter, {\n [methodName]: data\n });\n }\n cb.apply(this, args);\n };\n args[args.length - 1] = wrappedCb;\n } else {\n wrappedCb = false;\n }\n this.emitMulti(methodName, evNameBefore);\n let result;\n try {\n result = method.apply(this, args);\n if (!wrappedCb) {\n this.emitMulti(methodName, evNameAfter, {\n [methodName]: result\n });\n }\n } catch (error) {\n error.methodName = methodName;\n this.emitError(methodName, error);\n }\n return result;\n };\n Jimp.prototype[methodName + \"Quiet\"] = method;\n}\n\n/**\n * Creates a new image that is a clone of this one.\n * @param {function(Error, Jimp)} cb (optional) A callback for when complete\n * @returns the new image\n */\njimpEvMethod(\"clone\", \"clone\", function (cb) {\n const clone = new Jimp(this);\n if (isNodePattern(cb)) {\n cb.call(clone, null, clone);\n }\n return clone;\n});\n\n/**\n * Simplify jimpEvMethod call for the common `change` evName.\n * @param {string} methodName name of the method\n * @param {function} method to watch changes for\n */\nexport function jimpEvChange(methodName, method) {\n jimpEvMethod(methodName, \"change\", method);\n}\n\n/**\n * Sets the type of the image (RGB or RGBA) when saving as PNG format (default is RGBA)\n * @param b A Boolean, true to use RGBA or false to use RGB\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\njimpEvChange(\"background\", function (hex, cb) {\n if (typeof hex !== \"number\") {\n return throwError.call(this, \"hex must be a hexadecimal rgba value\", cb);\n }\n this._background = hex;\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n});\n\n/**\n * Scans through a region of the bitmap, calling a function for each pixel.\n * @param {number} x the x coordinate to begin the scan at\n * @param {number} y the y coordinate to begin the scan at\n * @param w the width of the scan region\n * @param h the height of the scan region\n * @param f a function to call on even pixel; the (x, y) position of the pixel\n * and the index of the pixel in the bitmap buffer are passed to the function\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\njimpEvChange(\"scan\", function (x, y, w, h, f, cb) {\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n if (typeof f !== \"function\") {\n return throwError.call(this, \"f must be a function\", cb);\n }\n const result = scan(this, x, y, w, h, f);\n if (isNodePattern(cb)) {\n cb.call(this, null, result);\n }\n return result;\n});\nif (process.env.ENVIRONMENT === \"BROWSER\") {\n // For use in a web browser or web worker\n /* global self */\n let gl;\n if (typeof window !== \"undefined\" && typeof window === \"object\") {\n gl = window;\n }\n if (typeof self !== \"undefined\" && typeof self === \"object\") {\n gl = self;\n }\n gl.Jimp = Jimp;\n gl.Buffer = Buffer;\n}\nexport { addType } from \"./utils/mime\";\nexport default Jimp;\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\nimport * as constants from \"../constants\";\nimport * as compositeModes from \"./composite-modes\";\n\n/**\n * Composites a source image over to this image respecting alpha channels\n * @param {Jimp} src the source Jimp instance\n * @param {number} x the x position to blit the image\n * @param {number} y the y position to blit the image\n * @param {object} options determine what mode to use\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default function composite(src, x, y) {\n let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n let cb = arguments.length > 4 ? arguments[4] : undefined;\n if (typeof options === \"function\") {\n cb = options;\n options = {};\n }\n if (!(src instanceof this.constructor)) {\n return throwError.call(this, \"The source must be a Jimp image\", cb);\n }\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n let {\n mode,\n opacitySource,\n opacityDest\n } = options;\n if (!mode) {\n mode = constants.BLEND_SOURCE_OVER;\n }\n if (typeof opacitySource !== \"number\" || opacitySource < 0 || opacitySource > 1) {\n opacitySource = 1.0;\n }\n if (typeof opacityDest !== \"number\" || opacityDest < 0 || opacityDest > 1) {\n opacityDest = 1.0;\n }\n\n // eslint-disable-next-line import/namespace\n const blendmode = compositeModes[mode];\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n const baseImage = this;\n if (opacityDest !== 1.0) {\n baseImage.opacity(opacityDest);\n }\n src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) {\n const dstIdx = baseImage.getPixelIndex(x + sx, y + sy, constants.EDGE_CROP);\n if (dstIdx === -1) {\n // Skip target pixels outside of dst\n return;\n }\n const blended = blendmode({\n r: this.bitmap.data[idx + 0] / 255,\n g: this.bitmap.data[idx + 1] / 255,\n b: this.bitmap.data[idx + 2] / 255,\n a: this.bitmap.data[idx + 3] / 255\n }, {\n r: baseImage.bitmap.data[dstIdx + 0] / 255,\n g: baseImage.bitmap.data[dstIdx + 1] / 255,\n b: baseImage.bitmap.data[dstIdx + 2] / 255,\n a: baseImage.bitmap.data[dstIdx + 3] / 255\n }, opacitySource);\n baseImage.bitmap.data[dstIdx + 0] = this.constructor.limit255(blended.r * 255);\n baseImage.bitmap.data[dstIdx + 1] = this.constructor.limit255(blended.g * 255);\n baseImage.bitmap.data[dstIdx + 2] = this.constructor.limit255(blended.b * 255);\n baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(blended.a * 255);\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n}\n//# sourceMappingURL=index.js.map","import JPEG from \"jpeg-js\";\nimport { throwError, isNodePattern } from \"@jimp/utils\";\nconst MIME_TYPE = \"image/jpeg\";\nexport default (() => ({\n mime: {\n [MIME_TYPE]: [\"jpeg\", \"jpg\", \"jpe\"]\n },\n constants: {\n MIME_JPEG: MIME_TYPE\n },\n decoders: {\n [MIME_TYPE]: JPEG.decode\n },\n encoders: {\n [MIME_TYPE]: image => JPEG.encode(image.bitmap, image._quality).data\n },\n class: {\n // The quality to be used when saving JPEG images\n _quality: 100,\n /**\n * Sets the quality of the image when saving as JPEG format (default is 100)\n * @param {number} n The quality to use 0-100\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n quality(n, cb) {\n if (typeof n !== \"number\") {\n return throwError.call(this, \"n must be a number\", cb);\n }\n if (n < 0 || n > 100) {\n return throwError.call(this, \"n must be a number 0 - 100\", cb);\n }\n this._quality = Math.round(n);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n }\n}));\n//# sourceMappingURL=index.js.map","import { PNG } from \"pngjs\";\nimport { throwError, isNodePattern } from \"@jimp/utils\";\nconst MIME_TYPE = \"image/png\";\n\n// PNG filter types\nconst PNG_FILTER_AUTO = -1;\nconst PNG_FILTER_NONE = 0;\nconst PNG_FILTER_SUB = 1;\nconst PNG_FILTER_UP = 2;\nconst PNG_FILTER_AVERAGE = 3;\nconst PNG_FILTER_PATH = 4;\nexport default (() => ({\n mime: {\n [MIME_TYPE]: [\"png\"]\n },\n constants: {\n MIME_PNG: MIME_TYPE,\n PNG_FILTER_AUTO,\n PNG_FILTER_NONE,\n PNG_FILTER_SUB,\n PNG_FILTER_UP,\n PNG_FILTER_AVERAGE,\n PNG_FILTER_PATH\n },\n hasAlpha: {\n [MIME_TYPE]: true\n },\n decoders: {\n [MIME_TYPE]: PNG.sync.read\n },\n encoders: {\n [MIME_TYPE](data) {\n const png = new PNG({\n width: data.bitmap.width,\n height: data.bitmap.height\n });\n png.data = data.bitmap.data;\n return PNG.sync.write(png, {\n deflateLevel: data._deflateLevel,\n deflateStrategy: data._deflateStrategy,\n filterType: data._filterType,\n colorType: typeof data._colorType === \"number\" ? data._colorType : data._rgba ? 6 : 2,\n inputHasAlpha: data._rgba\n });\n }\n },\n class: {\n _deflateLevel: 9,\n _deflateStrategy: 3,\n _filterType: PNG_FILTER_AUTO,\n _colorType: null,\n /**\n * Sets the deflate level used when saving as PNG format (default is 9)\n * @param {number} l Deflate level to use 0-9. 0 is no compression. 9 (default) is maximum compression.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n deflateLevel(l, cb) {\n if (typeof l !== \"number\") {\n return throwError.call(this, \"l must be a number\", cb);\n }\n if (l < 0 || l > 9) {\n return throwError.call(this, \"l must be a number 0 - 9\", cb);\n }\n this._deflateLevel = Math.round(l);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Sets the deflate strategy used when saving as PNG format (default is 3)\n * @param {number} s Deflate strategy to use 0-3.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n deflateStrategy(s, cb) {\n if (typeof s !== \"number\") {\n return throwError.call(this, \"s must be a number\", cb);\n }\n if (s < 0 || s > 3) {\n return throwError.call(this, \"s must be a number 0 - 3\", cb);\n }\n this._deflateStrategy = Math.round(s);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Sets the filter type used when saving as PNG format (default is automatic filters)\n * @param {number} f The quality to use -1-4.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n filterType(f, cb) {\n if (typeof f !== \"number\") {\n return throwError.call(this, \"n must be a number\", cb);\n }\n if (f < -1 || f > 4) {\n return throwError.call(this, \"n must be -1 (auto) or a number 0 - 4\", cb);\n }\n this._filterType = Math.round(f);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Sets the color type used when saving as PNG format\n * @param {number} s color type to use 0, 2, 4, 6.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n colorType(s, cb) {\n if (typeof s !== \"number\") {\n return throwError.call(this, \"s must be a number\", cb);\n }\n if (s !== 0 && s !== 2 && s !== 4 && s !== 6) {\n return throwError.call(this, \"s must be a number 0, 2, 4, 6.\", cb);\n }\n this._colorType = Math.round(s);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n }\n}));\n//# sourceMappingURL=index.js.map","import BMP from \"bmp-js\";\nimport { scan } from \"@jimp/utils\";\nconst MIME_TYPE = \"image/bmp\";\nconst MIME_TYPE_SECOND = \"image/x-ms-bmp\";\nfunction toAGBR(image) {\n return scan(image, 0, 0, image.bitmap.width, image.bitmap.height, function (x, y, index) {\n const red = this.bitmap.data[index + 0];\n const green = this.bitmap.data[index + 1];\n const blue = this.bitmap.data[index + 2];\n const alpha = this.bitmap.data[index + 3];\n this.bitmap.data[index + 0] = alpha;\n this.bitmap.data[index + 1] = blue;\n this.bitmap.data[index + 2] = green;\n this.bitmap.data[index + 3] = red;\n }).bitmap;\n}\nfunction fromAGBR(bitmap) {\n return scan({\n bitmap\n }, 0, 0, bitmap.width, bitmap.height, function (x, y, index) {\n const alpha = this.bitmap.data[index + 0];\n const blue = this.bitmap.data[index + 1];\n const green = this.bitmap.data[index + 2];\n const red = this.bitmap.data[index + 3];\n this.bitmap.data[index + 0] = red;\n this.bitmap.data[index + 1] = green;\n this.bitmap.data[index + 2] = blue;\n this.bitmap.data[index + 3] = bitmap.is_with_alpha ? alpha : 0xff;\n }).bitmap;\n}\nconst decode = data => fromAGBR(BMP.decode(data));\nconst encode = image => BMP.encode(toAGBR(image)).data;\nexport default (() => ({\n mime: {\n [MIME_TYPE]: [\"bmp\"]\n },\n constants: {\n MIME_BMP: MIME_TYPE,\n MIME_X_MS_BMP: MIME_TYPE_SECOND\n },\n decoders: {\n [MIME_TYPE]: decode,\n [MIME_TYPE_SECOND]: decode\n },\n encoders: {\n [MIME_TYPE]: encode,\n [MIME_TYPE_SECOND]: encode\n }\n}));\n//# sourceMappingURL=index.js.map","import utif from \"utif2\";\nconst MIME_TYPE = \"image/tiff\";\nexport default (() => ({\n mime: {\n [MIME_TYPE]: [\"tiff\", \"tif\"]\n },\n constants: {\n MIME_TIFF: MIME_TYPE\n },\n decoders: {\n [MIME_TYPE]: data => {\n const ifds = utif.decode(data);\n const page = ifds[0];\n ifds.forEach(ifd => {\n utif.decodeImage(data, ifd);\n });\n const rgba = utif.toRGBA8(page);\n return {\n data: Buffer.from(rgba),\n width: page.t256[0],\n height: page.t257[0]\n };\n }\n },\n encoders: {\n [MIME_TYPE]: image => {\n const tiff = utif.encodeImage(image.bitmap.data, image.bitmap.width, image.bitmap.height);\n return Buffer.from(tiff);\n }\n }\n}));\n//# sourceMappingURL=index.js.map","import GIF from \"omggif\";\nimport { GifUtil, GifFrame, BitmapImage, GifCodec } from \"gifwrap\";\nconst MIME_TYPE = \"image/gif\";\nexport default (() => ({\n mime: {\n [MIME_TYPE]: [\"gif\"]\n },\n constants: {\n MIME_GIF: MIME_TYPE\n },\n decoders: {\n [MIME_TYPE]: data => {\n const gifObj = new GIF.GifReader(data);\n const gifData = Buffer.alloc(gifObj.width * gifObj.height * 4);\n gifObj.decodeAndBlitFrameRGBA(0, gifData);\n return {\n data: gifData,\n width: gifObj.width,\n height: gifObj.height\n };\n }\n },\n encoders: {\n [MIME_TYPE]: data => {\n const bitmap = new BitmapImage(data.bitmap);\n GifUtil.quantizeDekker(bitmap, 256);\n const newFrame = new GifFrame(bitmap);\n const gifCodec = new GifCodec();\n return gifCodec.encodeGif([newFrame], {}).then(newGif => {\n return newGif.buffer;\n });\n }\n }\n}));\n//# sourceMappingURL=index.js.map","export const mulTable = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1];\nexport const shgTable = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18];\n//# sourceMappingURL=blur-tables.js.map","import tinyColor from \"tinycolor2\";\nimport { throwError, isNodePattern } from \"@jimp/utils\";\nfunction applyKernel(im, kernel, x, y) {\n const value = [0, 0, 0];\n const size = (kernel.length - 1) / 2;\n for (let kx = 0; kx < kernel.length; kx += 1) {\n for (let ky = 0; ky < kernel[kx].length; ky += 1) {\n const idx = im.getPixelIndex(x + kx - size, y + ky - size);\n value[0] += im.bitmap.data[idx] * kernel[kx][ky];\n value[1] += im.bitmap.data[idx + 1] * kernel[kx][ky];\n value[2] += im.bitmap.data[idx + 2] * kernel[kx][ky];\n }\n }\n return value;\n}\nconst isDef = v => typeof v !== \"undefined\" && v !== null;\nfunction greyscale(cb) {\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n const grey = parseInt(0.2126 * this.bitmap.data[idx] + 0.7152 * this.bitmap.data[idx + 1] + 0.0722 * this.bitmap.data[idx + 2], 10);\n this.bitmap.data[idx] = grey;\n this.bitmap.data[idx + 1] = grey;\n this.bitmap.data[idx + 2] = grey;\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n}\nfunction mix(clr, clr2) {\n let p = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;\n return {\n r: (clr2.r - clr.r) * (p / 100) + clr.r,\n g: (clr2.g - clr.g) * (p / 100) + clr.g,\n b: (clr2.b - clr.b) * (p / 100) + clr.b\n };\n}\nfunction colorFn(actions, cb) {\n if (!actions || !Array.isArray(actions)) {\n return throwError.call(this, \"actions must be an array\", cb);\n }\n actions = actions.map(action => {\n if (action.apply === \"xor\" || action.apply === \"mix\") {\n action.params[0] = tinyColor(action.params[0]).toRgb();\n }\n return action;\n });\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {\n let clr = {\n r: this.bitmap.data[idx],\n g: this.bitmap.data[idx + 1],\n b: this.bitmap.data[idx + 2]\n };\n const colorModifier = (i, amount) => this.constructor.limit255(clr[i] + amount);\n actions.forEach(action => {\n if (action.apply === \"mix\") {\n clr = mix(clr, action.params[0], action.params[1]);\n } else if (action.apply === \"tint\") {\n clr = mix(clr, {\n r: 255,\n g: 255,\n b: 255\n }, action.params[0]);\n } else if (action.apply === \"shade\") {\n clr = mix(clr, {\n r: 0,\n g: 0,\n b: 0\n }, action.params[0]);\n } else if (action.apply === \"xor\") {\n clr = {\n r: clr.r ^ action.params[0].r,\n g: clr.g ^ action.params[0].g,\n b: clr.b ^ action.params[0].b\n };\n } else if (action.apply === \"red\") {\n clr.r = colorModifier(\"r\", action.params[0]);\n } else if (action.apply === \"green\") {\n clr.g = colorModifier(\"g\", action.params[0]);\n } else if (action.apply === \"blue\") {\n clr.b = colorModifier(\"b\", action.params[0]);\n } else {\n if (action.apply === \"hue\") {\n action.apply = \"spin\";\n }\n clr = tinyColor(clr);\n if (!clr[action.apply]) {\n return throwError.call(this, \"action \" + action.apply + \" not supported\", cb);\n }\n clr = clr[action.apply](...action.params).toRgb();\n }\n });\n this.bitmap.data[idx] = clr.r;\n this.bitmap.data[idx + 1] = clr.g;\n this.bitmap.data[idx + 2] = clr.b;\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n}\nexport const ColorActionName = Object.freeze({\n LIGHTEN: \"lighten\",\n BRIGHTEN: \"brighten\",\n DARKEN: \"darken\",\n DESATURATE: \"desaturate\",\n SATURATE: \"saturate\",\n GREYSCALE: \"greyscale\",\n SPIN: \"spin\",\n HUE: \"hue\",\n MIX: \"mix\",\n TINT: \"tint\",\n SHADE: \"shade\",\n XOR: \"xor\",\n RED: \"red\",\n GREEN: \"green\",\n BLUE: \"blue\"\n});\nexport default (() => ({\n /**\n * Adjusts the brightness of the image\n * @param {number} val the amount to adjust the brightness, a number between -1 and +1\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n brightness(val, cb) {\n if (typeof val !== \"number\") {\n return throwError.call(this, \"val must be numbers\", cb);\n }\n if (val < -1 || val > +1) {\n return throwError.call(this, \"val must be a number between -1 and +1\", cb);\n }\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n if (val < 0.0) {\n this.bitmap.data[idx] *= 1 + val;\n this.bitmap.data[idx + 1] *= 1 + val;\n this.bitmap.data[idx + 2] *= 1 + val;\n } else {\n this.bitmap.data[idx] += (255 - this.bitmap.data[idx]) * val;\n this.bitmap.data[idx + 1] += (255 - this.bitmap.data[idx + 1]) * val;\n this.bitmap.data[idx + 2] += (255 - this.bitmap.data[idx + 2]) * val;\n }\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Adjusts the contrast of the image\n * @param {number} val the amount to adjust the contrast, a number between -1 and +1\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n contrast(val, cb) {\n if (typeof val !== \"number\") {\n return throwError.call(this, \"val must be numbers\", cb);\n }\n if (val < -1 || val > +1) {\n return throwError.call(this, \"val must be a number between -1 and +1\", cb);\n }\n const factor = (val + 1) / (1 - val);\n function adjust(value) {\n value = Math.floor(factor * (value - 127) + 127);\n return value < 0 ? 0 : value > 255 ? 255 : value;\n }\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n this.bitmap.data[idx] = adjust(this.bitmap.data[idx]);\n this.bitmap.data[idx + 1] = adjust(this.bitmap.data[idx + 1]);\n this.bitmap.data[idx + 2] = adjust(this.bitmap.data[idx + 2]);\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Apply a posterize effect\n * @param {number} n the amount to adjust the contrast, minimum threshold is two\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n posterize(n, cb) {\n if (typeof n !== \"number\") {\n return throwError.call(this, \"n must be numbers\", cb);\n }\n if (n < 2) {\n n = 2;\n } // minimum of 2 levels\n\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n this.bitmap.data[idx] = Math.floor(this.bitmap.data[idx] / 255 * (n - 1)) / (n - 1) * 255;\n this.bitmap.data[idx + 1] = Math.floor(this.bitmap.data[idx + 1] / 255 * (n - 1)) / (n - 1) * 255;\n this.bitmap.data[idx + 2] = Math.floor(this.bitmap.data[idx + 2] / 255 * (n - 1)) / (n - 1) * 255;\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Removes colour from the image using ITU Rec 709 luminance values\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n greyscale,\n // Alias of greyscale for our American friends\n grayscale: greyscale,\n /**\n * Multiplies the opacity of each pixel by a factor between 0 and 1\n * @param {number} f A number, the factor by which to multiply the opacity of each pixel\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n opacity(f, cb) {\n if (typeof f !== \"number\") return throwError.call(this, \"f must be a number\", cb);\n if (f < 0 || f > 1) return throwError.call(this, \"f must be a number from 0 to 1\", cb);\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n const v = this.bitmap.data[idx + 3] * f;\n this.bitmap.data[idx + 3] = v;\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Applies a sepia tone to the image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n sepia(cb) {\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n let red = this.bitmap.data[idx];\n let green = this.bitmap.data[idx + 1];\n let blue = this.bitmap.data[idx + 2];\n red = red * 0.393 + green * 0.769 + blue * 0.189;\n green = red * 0.349 + green * 0.686 + blue * 0.168;\n blue = red * 0.272 + green * 0.534 + blue * 0.131;\n this.bitmap.data[idx] = red < 255 ? red : 255;\n this.bitmap.data[idx + 1] = green < 255 ? green : 255;\n this.bitmap.data[idx + 2] = blue < 255 ? blue : 255;\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Fades each pixel by a factor between 0 and 1\n * @param {number} f A number from 0 to 1. 0 will haven no effect. 1 will turn the image completely transparent.\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n fade(f, cb) {\n if (typeof f !== \"number\") {\n return throwError.call(this, \"f must be a number\", cb);\n }\n if (f < 0 || f > 1) {\n return throwError.call(this, \"f must be a number from 0 to 1\", cb);\n }\n\n // this method is an alternative to opacity (which may be deprecated)\n this.opacity(1 - f);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Adds each element of the image to its local neighbors, weighted by the kernel\n * @param {array} kernel a matrix to weight the neighbors sum\n * @param {number} edgeHandling (optional) define how to sum pixels from outside the border\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n convolution(kernel, edgeHandling, cb) {\n if (typeof edgeHandling === \"function\" && typeof cb === \"undefined\") {\n cb = edgeHandling;\n edgeHandling = null;\n }\n if (!edgeHandling) {\n edgeHandling = this.constructor.EDGE_EXTEND;\n }\n const newData = Buffer.from(this.bitmap.data);\n const kRows = kernel.length;\n const kCols = kernel[0].length;\n const rowEnd = Math.floor(kRows / 2);\n const colEnd = Math.floor(kCols / 2);\n const rowIni = -rowEnd;\n const colIni = -colEnd;\n let weight;\n let rSum;\n let gSum;\n let bSum;\n let ri;\n let gi;\n let bi;\n let xi;\n let yi;\n let idxi;\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n bSum = 0;\n gSum = 0;\n rSum = 0;\n for (let row = rowIni; row <= rowEnd; row++) {\n for (let col = colIni; col <= colEnd; col++) {\n xi = x + col;\n yi = y + row;\n weight = kernel[row + rowEnd][col + colEnd];\n idxi = this.getPixelIndex(xi, yi, edgeHandling);\n if (idxi === -1) {\n bi = 0;\n gi = 0;\n ri = 0;\n } else {\n ri = this.bitmap.data[idxi + 0];\n gi = this.bitmap.data[idxi + 1];\n bi = this.bitmap.data[idxi + 2];\n }\n rSum += weight * ri;\n gSum += weight * gi;\n bSum += weight * bi;\n }\n }\n if (rSum < 0) {\n rSum = 0;\n }\n if (gSum < 0) {\n gSum = 0;\n }\n if (bSum < 0) {\n bSum = 0;\n }\n if (rSum > 255) {\n rSum = 255;\n }\n if (gSum > 255) {\n gSum = 255;\n }\n if (bSum > 255) {\n bSum = 255;\n }\n newData[idx + 0] = rSum;\n newData[idx + 1] = gSum;\n newData[idx + 2] = bSum;\n });\n this.bitmap.data = newData;\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Set the alpha channel on every pixel to fully opaque\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n opaque(cb) {\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n this.bitmap.data[idx + 3] = 255;\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Pixelates the image or a region\n * @param {number} size the size of the pixels\n * @param {number} x (optional) the x position of the region to pixelate\n * @param {number} y (optional) the y position of the region to pixelate\n * @param {number} w (optional) the width of the region to pixelate\n * @param {number} h (optional) the height of the region to pixelate\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n pixelate(size, x, y, w, h, cb) {\n if (typeof x === \"function\") {\n cb = x;\n h = null;\n w = null;\n y = null;\n x = null;\n } else {\n if (typeof size !== \"number\") {\n return throwError.call(this, \"size must be a number\", cb);\n }\n if (isDef(x) && typeof x !== \"number\") {\n return throwError.call(this, \"x must be a number\", cb);\n }\n if (isDef(y) && typeof y !== \"number\") {\n return throwError.call(this, \"y must be a number\", cb);\n }\n if (isDef(w) && typeof w !== \"number\") {\n return throwError.call(this, \"w must be a number\", cb);\n }\n if (isDef(h) && typeof h !== \"number\") {\n return throwError.call(this, \"h must be a number\", cb);\n }\n }\n const kernel = [[1 / 16, 2 / 16, 1 / 16], [2 / 16, 4 / 16, 2 / 16], [1 / 16, 2 / 16, 1 / 16]];\n x = x || 0;\n y = y || 0;\n w = isDef(w) ? w : this.bitmap.width - x;\n h = isDef(h) ? h : this.bitmap.height - y;\n const source = this.cloneQuiet();\n this.scanQuiet(x, y, w, h, function (xx, yx, idx) {\n xx = size * Math.floor(xx / size);\n yx = size * Math.floor(yx / size);\n const value = applyKernel(source, kernel, xx, yx);\n this.bitmap.data[idx] = value[0];\n this.bitmap.data[idx + 1] = value[1];\n this.bitmap.data[idx + 2] = value[2];\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Applies a convolution kernel to the image or a region\n * @param {array} kernel the convolution kernel\n * @param {number} x (optional) the x position of the region to apply convolution to\n * @param {number} y (optional) the y position of the region to apply convolution to\n * @param {number} w (optional) the width of the region to apply convolution to\n * @param {number} h (optional) the height of the region to apply convolution to\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n convolute(kernel, x, y, w, h, cb) {\n if (!Array.isArray(kernel)) return throwError.call(this, \"the kernel must be an array\", cb);\n if (typeof x === \"function\") {\n cb = x;\n x = null;\n y = null;\n w = null;\n h = null;\n } else {\n if (isDef(x) && typeof x !== \"number\") {\n return throwError.call(this, \"x must be a number\", cb);\n }\n if (isDef(y) && typeof y !== \"number\") {\n return throwError.call(this, \"y must be a number\", cb);\n }\n if (isDef(w) && typeof w !== \"number\") {\n return throwError.call(this, \"w must be a number\", cb);\n }\n if (isDef(h) && typeof h !== \"number\") {\n return throwError.call(this, \"h must be a number\", cb);\n }\n }\n x = isDef(x) ? x : 0;\n y = isDef(y) ? y : 0;\n w = isDef(w) ? w : this.bitmap.width - x;\n h = isDef(h) ? h : this.bitmap.height - y;\n const source = this.cloneQuiet();\n this.scanQuiet(x, y, w, h, function (xx, yx, idx) {\n const value = applyKernel(source, kernel, xx, yx);\n this.bitmap.data[idx] = this.constructor.limit255(value[0]);\n this.bitmap.data[idx + 1] = this.constructor.limit255(value[1]);\n this.bitmap.data[idx + 2] = this.constructor.limit255(value[2]);\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Apply multiple color modification rules\n * @param {array} actions list of color modification rules, in following format: { apply: '', params: [ ] }\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp }this for chaining of methods\n */\n color: colorFn,\n colour: colorFn\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Apply a ordered dithering effect\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nfunction dither(cb) {\n const rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6];\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n const thresholdId = ((y & 3) << 2) + x % 4;\n const dither = rgb565Matrix[thresholdId];\n this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff);\n this.bitmap.data[idx + 1] = Math.min(this.bitmap.data[idx + 1] + dither, 0xff);\n this.bitmap.data[idx + 2] = Math.min(this.bitmap.data[idx + 2] + dither, 0xff);\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n}\nexport default (() => ({\n dither565: dither,\n dither16: dither\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Flip the image horizontally\n * @param {boolean} horizontal a Boolean, if true the image will be flipped horizontally\n * @param {boolean} vertical a Boolean, if true the image will be flipped vertically\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nfunction flipFn(horizontal, vertical, cb) {\n if (typeof horizontal !== \"boolean\" || typeof vertical !== \"boolean\") return throwError.call(this, \"horizontal and vertical must be Booleans\", cb);\n const bitmap = Buffer.alloc(this.bitmap.data.length);\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n const _x = horizontal ? this.bitmap.width - 1 - x : x;\n const _y = vertical ? this.bitmap.height - 1 - y : y;\n const _idx = this.bitmap.width * _y + _x << 2;\n const data = this.bitmap.data.readUInt32BE(idx);\n bitmap.writeUInt32BE(data, _idx);\n });\n this.bitmap.data = Buffer.from(bitmap);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n}\nexport default (() => ({\n flip: flipFn,\n mirror: flipFn\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Get an image's histogram\n * @return {object} An object with an array of color occurrence counts for each channel (r,g,b)\n */\nfunction histogram() {\n const histogram = {\n r: new Array(256).fill(0),\n g: new Array(256).fill(0),\n b: new Array(256).fill(0)\n };\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, index) {\n histogram.r[this.bitmap.data[index + 0]]++;\n histogram.g[this.bitmap.data[index + 1]]++;\n histogram.b[this.bitmap.data[index + 2]]++;\n });\n return histogram;\n}\n\n/**\n * Normalize values\n * @param {integer} value Pixel channel value.\n * @param {integer} min Minimum value for channel\n * @param {integer} max Maximum value for channel\n * @return {integer} normalized values\n */\nconst normalize = function (value, min, max) {\n return (value - min) * 255 / (max - min);\n};\nconst getBounds = function (histogramChannel) {\n return [histogramChannel.findIndex(value => value > 0), 255 - histogramChannel.slice().reverse().findIndex(value => value > 0)];\n};\n\n/**\n * Normalizes the image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n normalize(cb) {\n const h = histogram.call(this);\n\n // store bounds (minimum and maximum values)\n const bounds = {\n r: getBounds(h.r),\n g: getBounds(h.g),\n b: getBounds(h.b)\n };\n\n // apply value transformations\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n const r = this.bitmap.data[idx + 0];\n const g = this.bitmap.data[idx + 1];\n const b = this.bitmap.data[idx + 2];\n this.bitmap.data[idx + 0] = normalize(r, bounds.r[0], bounds.r[1]);\n this.bitmap.data[idx + 1] = normalize(g, bounds.g[0], bounds.g[1]);\n this.bitmap.data[idx + 2] = normalize(b, bounds.b[0], bounds.b[1]);\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","export function measureText(font, text) {\n let x = 0;\n for (let i = 0; i < text.length; i++) {\n if (font.chars[text[i]]) {\n const kerning = font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]] ? font.kernings[text[i]][text[i + 1]] : 0;\n x += (font.chars[text[i]].xadvance || 0) + kerning;\n }\n }\n return x;\n}\nexport function splitLines(font, text, maxWidth) {\n const words = text.replace(/[\\r\\n]+/g, \" \\n\").split(\" \");\n const lines = [];\n let currentLine = [];\n let longestLine = 0;\n words.forEach(word => {\n const line = [...currentLine, word].join(\" \");\n const length = measureText(font, line);\n if (length <= maxWidth && !word.includes(\"\\n\")) {\n if (length > longestLine) {\n longestLine = length;\n }\n currentLine.push(word);\n } else {\n lines.push(currentLine);\n currentLine = [word.replace(\"\\n\", \"\")];\n }\n });\n lines.push(currentLine);\n return {\n lines,\n longestLine\n };\n}\nexport function measureTextHeight(font, text, maxWidth) {\n const {\n lines\n } = splitLines(font, text, maxWidth);\n return lines.length * font.common.lineHeight;\n}\n//# sourceMappingURL=measure-text.js.map","import Path from \"path\";\nimport bMFont from \"load-bmfont\";\nimport { isNodePattern, throwError } from \"@jimp/utils\";\nimport { measureText, measureTextHeight, splitLines } from \"./measure-text\";\nfunction xOffsetBasedOnAlignment(constants, font, line, maxWidth, alignment) {\n if (alignment === constants.HORIZONTAL_ALIGN_LEFT) {\n return 0;\n }\n if (alignment === constants.HORIZONTAL_ALIGN_CENTER) {\n return (maxWidth - measureText(font, line)) / 2;\n }\n return maxWidth - measureText(font, line);\n}\nfunction drawCharacter(image, font, x, y, char) {\n if (char.width > 0 && char.height > 0) {\n const characterPage = font.pages[char.page];\n image.blit(characterPage, x + char.xoffset, y + char.yoffset, char.x, char.y, char.width, char.height);\n }\n return image;\n}\nfunction printText(font, x, y, text, defaultCharWidth) {\n for (let i = 0; i < text.length; i++) {\n let char;\n if (font.chars[text[i]]) {\n char = text[i];\n } else if (/\\s/.test(text[i])) {\n char = \"\";\n } else {\n char = \"?\";\n }\n const fontChar = font.chars[char] || {};\n const fontKerning = font.kernings[char];\n drawCharacter(this, font, x, y, fontChar || {});\n const kerning = fontKerning && fontKerning[text[i + 1]] ? fontKerning[text[i + 1]] : 0;\n x += kerning + (fontChar.xadvance || defaultCharWidth);\n }\n}\nfunction loadPages(Jimp, dir, pages) {\n const newPages = pages.map(page => {\n return Jimp.read(dir + \"/\" + page);\n });\n return Promise.all(newPages);\n}\nconst dir = process.env.DIRNAME || `${__dirname}/../`;\nexport default (() => ({\n constants: {\n measureText,\n measureTextHeight,\n FONT_SANS_8_BLACK: Path.join(dir, \"fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt\"),\n FONT_SANS_10_BLACK: Path.join(dir, \"fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt\"),\n FONT_SANS_12_BLACK: Path.join(dir, \"fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt\"),\n FONT_SANS_14_BLACK: Path.join(dir, \"fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt\"),\n FONT_SANS_16_BLACK: Path.join(dir, \"fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt\"),\n FONT_SANS_32_BLACK: Path.join(dir, \"fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt\"),\n FONT_SANS_64_BLACK: Path.join(dir, \"fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt\"),\n FONT_SANS_128_BLACK: Path.join(dir, \"fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt\"),\n FONT_SANS_8_WHITE: Path.join(dir, \"fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt\"),\n FONT_SANS_16_WHITE: Path.join(dir, \"fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt\"),\n FONT_SANS_32_WHITE: Path.join(dir, \"fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt\"),\n FONT_SANS_64_WHITE: Path.join(dir, \"fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt\"),\n FONT_SANS_128_WHITE: Path.join(dir, \"fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt\"),\n /**\n * Loads a bitmap font from a file\n * @param {string} file the file path of a .fnt file\n * @param {function(Error, Jimp)} cb (optional) a function to call when the font is loaded\n * @returns {Promise} a promise\n */\n loadFont(file, cb) {\n if (typeof file !== \"string\") return throwError.call(this, \"file must be a string\", cb);\n return new Promise((resolve, reject) => {\n cb = cb || function (err, font) {\n if (err) reject(err);else resolve(font);\n };\n bMFont(file, (err, font) => {\n const chars = {};\n const kernings = {};\n if (err) {\n return throwError.call(this, err, cb);\n }\n for (let i = 0; i < font.chars.length; i++) {\n chars[String.fromCharCode(font.chars[i].id)] = font.chars[i];\n }\n for (let i = 0; i < font.kernings.length; i++) {\n const firstString = String.fromCharCode(font.kernings[i].first);\n kernings[firstString] = kernings[firstString] || {};\n kernings[firstString][String.fromCharCode(font.kernings[i].second)] = font.kernings[i].amount;\n }\n loadPages(this, Path.dirname(file), font.pages).then(pages => {\n cb(null, {\n chars,\n kernings,\n pages,\n common: font.common,\n info: font.info\n });\n });\n });\n });\n }\n },\n class: {\n /**\n * Draws a text on a image on a given boundary\n * @param {Jimp} font a bitmap font loaded from `Jimp.loadFont` command\n * @param {number} x the x position to start drawing the text\n * @param {number} y the y position to start drawing the text\n * @param {any} text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`)\n * @param {number} maxWidth (optional) the boundary width to draw in\n * @param {number} maxHeight (optional) the boundary height to draw in\n * @param {function(Error, Jimp)} cb (optional) a function to call when the text is written\n * @returns {Jimp} this for chaining of methods\n */\n print(font, x, y, text, maxWidth, maxHeight, cb) {\n if (typeof maxWidth === \"function\" && typeof cb === \"undefined\") {\n cb = maxWidth;\n maxWidth = Infinity;\n }\n if (typeof maxWidth === \"undefined\") {\n maxWidth = Infinity;\n }\n if (typeof maxHeight === \"function\" && typeof cb === \"undefined\") {\n cb = maxHeight;\n maxHeight = Infinity;\n }\n if (typeof maxHeight === \"undefined\") {\n maxHeight = Infinity;\n }\n if (typeof font !== \"object\") {\n return throwError.call(this, \"font must be a Jimp loadFont\", cb);\n }\n if (typeof x !== \"number\" || typeof y !== \"number\" || typeof maxWidth !== \"number\") {\n return throwError.call(this, \"x, y and maxWidth must be numbers\", cb);\n }\n if (typeof maxWidth !== \"number\") {\n return throwError.call(this, \"maxWidth must be a number\", cb);\n }\n if (typeof maxHeight !== \"number\") {\n return throwError.call(this, \"maxHeight must be a number\", cb);\n }\n let alignmentX;\n let alignmentY;\n if (typeof text === \"object\" && text.text !== null && text.text !== undefined) {\n alignmentX = text.alignmentX || this.constructor.HORIZONTAL_ALIGN_LEFT;\n alignmentY = text.alignmentY || this.constructor.VERTICAL_ALIGN_TOP;\n ({\n text\n } = text);\n } else {\n alignmentX = this.constructor.HORIZONTAL_ALIGN_LEFT;\n alignmentY = this.constructor.VERTICAL_ALIGN_TOP;\n text = text.toString();\n }\n if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_BOTTOM) {\n y += maxHeight - measureTextHeight(font, text, maxWidth);\n } else if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_MIDDLE) {\n y += maxHeight / 2 - measureTextHeight(font, text, maxWidth) / 2;\n }\n const defaultCharWidth = Object.entries(font.chars)[0][1].xadvance;\n const {\n lines,\n longestLine\n } = splitLines(font, text, maxWidth);\n lines.forEach(line => {\n const lineString = line.join(\" \");\n const alignmentWidth = xOffsetBasedOnAlignment(this.constructor, font, lineString, maxWidth, alignmentX);\n printText.call(this, font, x + alignmentWidth, y, lineString, defaultCharWidth);\n y += font.common.lineHeight;\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this, {\n x: x + longestLine,\n y\n });\n }\n return this;\n }\n }\n}));\n//# sourceMappingURL=index.js.map","// JavaScript Image Resizer (c) 2012 - Grant Galitz\n// Released to public domain 29 July 2013: https://github.com/grantgalitz/JS-Image-Resizer/issues/4\n\nfunction Resize(widthOriginal, heightOriginal, targetWidth, targetHeight, blendAlpha, interpolationPass, resizeCallback) {\n this.widthOriginal = Math.abs(Math.floor(widthOriginal) || 0);\n this.heightOriginal = Math.abs(Math.floor(heightOriginal) || 0);\n this.targetWidth = Math.abs(Math.floor(targetWidth) || 0);\n this.targetHeight = Math.abs(Math.floor(targetHeight) || 0);\n this.colorChannels = blendAlpha ? 4 : 3;\n this.interpolationPass = Boolean(interpolationPass);\n this.resizeCallback = typeof resizeCallback === \"function\" ? resizeCallback : function () {};\n this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels;\n this.originalWidthMultipliedByChannels = this.widthOriginal * this.colorChannels;\n this.originalHeightMultipliedByChannels = this.heightOriginal * this.colorChannels;\n this.widthPassResultSize = this.targetWidthMultipliedByChannels * this.heightOriginal;\n this.finalResultSize = this.targetWidthMultipliedByChannels * this.targetHeight;\n this.initialize();\n}\nResize.prototype.initialize = function () {\n // Perform some checks:\n if (this.widthOriginal > 0 && this.heightOriginal > 0 && this.targetWidth > 0 && this.targetHeight > 0) {\n this.configurePasses();\n } else {\n throw new Error(\"Invalid settings specified for the resizer.\");\n }\n};\nResize.prototype.configurePasses = function () {\n if (this.widthOriginal === this.targetWidth) {\n // Bypass the width resizer pass:\n this.resizeWidth = this.bypassResizer;\n } else {\n // Setup the width resizer pass:\n this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth;\n if (this.ratioWeightWidthPass < 1 && this.interpolationPass) {\n this.initializeFirstPassBuffers(true);\n this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthInterpolatedRGBA : this.resizeWidthInterpolatedRGB;\n } else {\n this.initializeFirstPassBuffers(false);\n this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthRGBA : this.resizeWidthRGB;\n }\n }\n if (this.heightOriginal === this.targetHeight) {\n // Bypass the height resizer pass:\n this.resizeHeight = this.bypassResizer;\n } else {\n // Setup the height resizer pass:\n this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight;\n if (this.ratioWeightHeightPass < 1 && this.interpolationPass) {\n this.initializeSecondPassBuffers(true);\n this.resizeHeight = this.resizeHeightInterpolated;\n } else {\n this.initializeSecondPassBuffers(false);\n this.resizeHeight = this.colorChannels === 4 ? this.resizeHeightRGBA : this.resizeHeightRGB;\n }\n }\n};\nResize.prototype._resizeWidthInterpolatedRGBChannels = function (buffer, fourthChannel) {\n const channelsNum = fourthChannel ? 4 : 3;\n const ratioWeight = this.ratioWeightWidthPass;\n const outputBuffer = this.widthBuffer;\n let weight = 0;\n let finalOffset = 0;\n let pixelOffset = 0;\n let firstWeight = 0;\n let secondWeight = 0;\n let targetPosition;\n\n // Handle for only one interpolation input being valid for start calculation:\n for (targetPosition = 0; weight < 1 / 3; targetPosition += channelsNum, weight += ratioWeight) {\n for (finalOffset = targetPosition, pixelOffset = 0; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {\n outputBuffer[finalOffset] = buffer[pixelOffset];\n outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];\n outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];\n if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];\n }\n }\n\n // Adjust for overshoot of the last pass's counter:\n weight -= 1 / 3;\n let interpolationWidthSourceReadStop;\n for (interpolationWidthSourceReadStop = this.widthOriginal - 1; weight < interpolationWidthSourceReadStop; targetPosition += channelsNum, weight += ratioWeight) {\n // Calculate weightings:\n secondWeight = weight % 1;\n firstWeight = 1 - secondWeight;\n // Interpolate:\n for (finalOffset = targetPosition, pixelOffset = Math.floor(weight) * channelsNum; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {\n outputBuffer[finalOffset + 0] = buffer[pixelOffset + 0] * firstWeight + buffer[pixelOffset + channelsNum + 0] * secondWeight;\n outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1] * firstWeight + buffer[pixelOffset + channelsNum + 1] * secondWeight;\n outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2] * firstWeight + buffer[pixelOffset + channelsNum + 2] * secondWeight;\n if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3] * firstWeight + buffer[pixelOffset + channelsNum + 3] * secondWeight;\n }\n }\n\n // Handle for only one interpolation input being valid for end calculation:\n for (interpolationWidthSourceReadStop = this.originalWidthMultipliedByChannels - channelsNum; targetPosition < this.targetWidthMultipliedByChannels; targetPosition += channelsNum) {\n for (finalOffset = targetPosition, pixelOffset = interpolationWidthSourceReadStop; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {\n outputBuffer[finalOffset] = buffer[pixelOffset];\n outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];\n outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];\n if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];\n }\n }\n return outputBuffer;\n};\nResize.prototype._resizeWidthRGBChannels = function (buffer, fourthChannel) {\n const channelsNum = fourthChannel ? 4 : 3;\n const ratioWeight = this.ratioWeightWidthPass;\n const ratioWeightDivisor = 1 / ratioWeight;\n const nextLineOffsetOriginalWidth = this.originalWidthMultipliedByChannels - channelsNum + 1;\n const nextLineOffsetTargetWidth = this.targetWidthMultipliedByChannels - channelsNum + 1;\n const output = this.outputWidthWorkBench;\n const outputBuffer = this.widthBuffer;\n const trustworthyColorsCount = this.outputWidthWorkBenchOpaquePixelsCount;\n let weight = 0;\n let amountToNext = 0;\n let actualPosition = 0;\n let currentPosition = 0;\n let line = 0;\n let pixelOffset = 0;\n let outputOffset = 0;\n let multiplier = 1;\n let r = 0;\n let g = 0;\n let b = 0;\n let a = 0;\n do {\n for (line = 0; line < this.originalHeightMultipliedByChannels;) {\n output[line++] = 0;\n output[line++] = 0;\n output[line++] = 0;\n if (fourthChannel) {\n output[line++] = 0;\n trustworthyColorsCount[line / channelsNum - 1] = 0;\n }\n }\n weight = ratioWeight;\n do {\n amountToNext = 1 + actualPosition - currentPosition;\n multiplier = Math.min(weight, amountToNext);\n for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) {\n r = buffer[pixelOffset];\n g = buffer[++pixelOffset];\n b = buffer[++pixelOffset];\n a = fourthChannel ? buffer[++pixelOffset] : 255;\n // Ignore RGB values if pixel is completely transparent\n output[line++] += (a ? r : 0) * multiplier;\n output[line++] += (a ? g : 0) * multiplier;\n output[line++] += (a ? b : 0) * multiplier;\n if (fourthChannel) {\n output[line++] += a * multiplier;\n trustworthyColorsCount[line / channelsNum - 1] += a ? multiplier : 0;\n }\n }\n if (weight >= amountToNext) {\n actualPosition += channelsNum;\n currentPosition = actualPosition;\n weight -= amountToNext;\n } else {\n currentPosition += weight;\n break;\n }\n } while (weight > 0 && actualPosition < this.originalWidthMultipliedByChannels);\n for (line = 0, pixelOffset = outputOffset; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetTargetWidth) {\n weight = fourthChannel ? trustworthyColorsCount[line / channelsNum] : 1;\n multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor;\n outputBuffer[pixelOffset] = output[line++] * multiplier;\n outputBuffer[++pixelOffset] = output[line++] * multiplier;\n outputBuffer[++pixelOffset] = output[line++] * multiplier;\n if (fourthChannel) outputBuffer[++pixelOffset] = output[line++] * ratioWeightDivisor;\n }\n outputOffset += channelsNum;\n } while (outputOffset < this.targetWidthMultipliedByChannels);\n return outputBuffer;\n};\nResize.prototype._resizeHeightRGBChannels = function (buffer, fourthChannel) {\n const ratioWeight = this.ratioWeightHeightPass;\n const ratioWeightDivisor = 1 / ratioWeight;\n const output = this.outputHeightWorkBench;\n const outputBuffer = this.heightBuffer;\n const trustworthyColorsCount = this.outputHeightWorkBenchOpaquePixelsCount;\n let weight = 0;\n let amountToNext = 0;\n let actualPosition = 0;\n let currentPosition = 0;\n let pixelOffset = 0;\n let outputOffset = 0;\n let caret = 0;\n let multiplier = 1;\n let r = 0;\n let g = 0;\n let b = 0;\n let a = 0;\n do {\n for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {\n output[pixelOffset++] = 0;\n output[pixelOffset++] = 0;\n output[pixelOffset++] = 0;\n if (fourthChannel) {\n output[pixelOffset++] = 0;\n trustworthyColorsCount[pixelOffset / 4 - 1] = 0;\n }\n }\n weight = ratioWeight;\n do {\n amountToNext = 1 + actualPosition - currentPosition;\n multiplier = Math.min(weight, amountToNext);\n caret = actualPosition;\n for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {\n r = buffer[caret++];\n g = buffer[caret++];\n b = buffer[caret++];\n a = fourthChannel ? buffer[caret++] : 255;\n // Ignore RGB values if pixel is completely transparent\n output[pixelOffset++] += (a ? r : 0) * multiplier;\n output[pixelOffset++] += (a ? g : 0) * multiplier;\n output[pixelOffset++] += (a ? b : 0) * multiplier;\n if (fourthChannel) {\n output[pixelOffset++] += a * multiplier;\n trustworthyColorsCount[pixelOffset / 4 - 1] += a ? multiplier : 0;\n }\n }\n if (weight >= amountToNext) {\n actualPosition = caret;\n currentPosition = actualPosition;\n weight -= amountToNext;\n } else {\n currentPosition += weight;\n break;\n }\n } while (weight > 0 && actualPosition < this.widthPassResultSize);\n for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {\n weight = fourthChannel ? trustworthyColorsCount[pixelOffset / 4] : 1;\n multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor;\n outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);\n outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);\n outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);\n if (fourthChannel) {\n outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor);\n }\n }\n } while (outputOffset < this.finalResultSize);\n return outputBuffer;\n};\nResize.prototype.resizeWidthInterpolatedRGB = function (buffer) {\n return this._resizeWidthInterpolatedRGBChannels(buffer, false);\n};\nResize.prototype.resizeWidthInterpolatedRGBA = function (buffer) {\n return this._resizeWidthInterpolatedRGBChannels(buffer, true);\n};\nResize.prototype.resizeWidthRGB = function (buffer) {\n return this._resizeWidthRGBChannels(buffer, false);\n};\nResize.prototype.resizeWidthRGBA = function (buffer) {\n return this._resizeWidthRGBChannels(buffer, true);\n};\nResize.prototype.resizeHeightInterpolated = function (buffer) {\n const ratioWeight = this.ratioWeightHeightPass;\n const outputBuffer = this.heightBuffer;\n let weight = 0;\n let finalOffset = 0;\n let pixelOffset = 0;\n let pixelOffsetAccumulated = 0;\n let pixelOffsetAccumulated2 = 0;\n let firstWeight = 0;\n let secondWeight = 0;\n let interpolationHeightSourceReadStop;\n\n // Handle for only one interpolation input being valid for start calculation:\n for (; weight < 1 / 3; weight += ratioWeight) {\n for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {\n outputBuffer[finalOffset++] = Math.round(buffer[pixelOffset++]);\n }\n }\n\n // Adjust for overshoot of the last pass's counter:\n weight -= 1 / 3;\n for (interpolationHeightSourceReadStop = this.heightOriginal - 1; weight < interpolationHeightSourceReadStop; weight += ratioWeight) {\n // Calculate weightings:\n secondWeight = weight % 1;\n firstWeight = 1 - secondWeight;\n // Interpolate:\n pixelOffsetAccumulated = Math.floor(weight) * this.targetWidthMultipliedByChannels;\n pixelOffsetAccumulated2 = pixelOffsetAccumulated + this.targetWidthMultipliedByChannels;\n for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) {\n outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++] * firstWeight + buffer[pixelOffsetAccumulated2++] * secondWeight);\n }\n }\n\n // Handle for only one interpolation input being valid for end calculation:\n while (finalOffset < this.finalResultSize) {\n for (pixelOffset = 0, pixelOffsetAccumulated = interpolationHeightSourceReadStop * this.targetWidthMultipliedByChannels; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) {\n outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++]);\n }\n }\n return outputBuffer;\n};\nResize.prototype.resizeHeightRGB = function (buffer) {\n return this._resizeHeightRGBChannels(buffer, false);\n};\nResize.prototype.resizeHeightRGBA = function (buffer) {\n return this._resizeHeightRGBChannels(buffer, true);\n};\nResize.prototype.resize = function (buffer) {\n this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer)));\n};\nResize.prototype.bypassResizer = function (buffer) {\n // Just return the buffer passed:\n return buffer;\n};\nResize.prototype.initializeFirstPassBuffers = function (BILINEARAlgo) {\n // Initialize the internal width pass buffers:\n this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize);\n if (!BILINEARAlgo) {\n this.outputWidthWorkBench = this.generateFloatBuffer(this.originalHeightMultipliedByChannels);\n if (this.colorChannels > 3) {\n this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.heightOriginal);\n }\n }\n};\nResize.prototype.initializeSecondPassBuffers = function (BILINEARAlgo) {\n // Initialize the internal height pass buffers:\n this.heightBuffer = this.generateUint8Buffer(this.finalResultSize);\n if (!BILINEARAlgo) {\n this.outputHeightWorkBench = this.generateFloatBuffer(this.targetWidthMultipliedByChannels);\n if (this.colorChannels > 3) {\n this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.targetWidth);\n }\n }\n};\nResize.prototype.generateFloatBuffer = function (bufferLength) {\n // Generate a float32 typed array buffer:\n try {\n return new Float32Array(bufferLength);\n } catch (error) {\n return [];\n }\n};\nResize.prototype.generateFloat64Buffer = function (bufferLength) {\n // Generate a float64 typed array buffer:\n try {\n return new Float64Array(bufferLength);\n } catch (error) {\n return [];\n }\n};\nResize.prototype.generateUint8Buffer = function (bufferLength) {\n // Generate a uint8 typed array buffer:\n try {\n return new Uint8Array(bufferLength);\n } catch (error) {\n return [];\n }\n};\nexport default Resize;\n//# sourceMappingURL=resize.js.map","/**\n * Copyright (c) 2015 Guyon Roche\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:

\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\nconst operations = {\n nearestNeighbor(src, dst) {\n const wSrc = src.width;\n const hSrc = src.height;\n const wDst = dst.width;\n const hDst = dst.height;\n const bufSrc = src.data;\n const bufDst = dst.data;\n for (let i = 0; i < hDst; i++) {\n for (let j = 0; j < wDst; j++) {\n let posDst = (i * wDst + j) * 4;\n const iSrc = Math.floor(i * hSrc / hDst);\n const jSrc = Math.floor(j * wSrc / wDst);\n let posSrc = (iSrc * wSrc + jSrc) * 4;\n bufDst[posDst++] = bufSrc[posSrc++];\n bufDst[posDst++] = bufSrc[posSrc++];\n bufDst[posDst++] = bufSrc[posSrc++];\n bufDst[posDst++] = bufSrc[posSrc++];\n }\n }\n },\n bilinearInterpolation(src, dst) {\n const wSrc = src.width;\n const hSrc = src.height;\n const wDst = dst.width;\n const hDst = dst.height;\n const bufSrc = src.data;\n const bufDst = dst.data;\n const interpolate = function (k, kMin, vMin, kMax, vMax) {\n // special case - k is integer\n if (kMin === kMax) {\n return vMin;\n }\n return Math.round((k - kMin) * vMax + (kMax - k) * vMin);\n };\n const assign = function (pos, offset, x, xMin, xMax, y, yMin, yMax) {\n let posMin = (yMin * wSrc + xMin) * 4 + offset;\n let posMax = (yMin * wSrc + xMax) * 4 + offset;\n const vMin = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]);\n\n // special case, y is integer\n if (yMax === yMin) {\n bufDst[pos + offset] = vMin;\n } else {\n posMin = (yMax * wSrc + xMin) * 4 + offset;\n posMax = (yMax * wSrc + xMax) * 4 + offset;\n const vMax = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]);\n bufDst[pos + offset] = interpolate(y, yMin, vMin, yMax, vMax);\n }\n };\n for (let i = 0; i < hDst; i++) {\n for (let j = 0; j < wDst; j++) {\n const posDst = (i * wDst + j) * 4;\n // x & y in src coordinates\n const x = j * wSrc / wDst;\n const xMin = Math.floor(x);\n const xMax = Math.min(Math.ceil(x), wSrc - 1);\n const y = i * hSrc / hDst;\n const yMin = Math.floor(y);\n const yMax = Math.min(Math.ceil(y), hSrc - 1);\n assign(posDst, 0, x, xMin, xMax, y, yMin, yMax);\n assign(posDst, 1, x, xMin, xMax, y, yMin, yMax);\n assign(posDst, 2, x, xMin, xMax, y, yMin, yMax);\n assign(posDst, 3, x, xMin, xMax, y, yMin, yMax);\n }\n }\n },\n _interpolate2D(src, dst, options, interpolate) {\n const bufSrc = src.data;\n const bufDst = dst.data;\n const wSrc = src.width;\n const hSrc = src.height;\n const wDst = dst.width;\n const hDst = dst.height;\n\n // when dst smaller than src/2, interpolate first to a multiple between 0.5 and 1.0 src, then sum squares\n const wM = Math.max(1, Math.floor(wSrc / wDst));\n const wDst2 = wDst * wM;\n const hM = Math.max(1, Math.floor(hSrc / hDst));\n const hDst2 = hDst * hM;\n\n // ===========================================================\n // Pass 1 - interpolate rows\n // buf1 has width of dst2 and height of src\n const buf1 = Buffer.alloc(wDst2 * hSrc * 4);\n for (let i = 0; i < hSrc; i++) {\n for (let j = 0; j < wDst2; j++) {\n // i in src coords, j in dst coords\n\n // calculate x in src coords\n // this interpolation requires 4 sample points and the two inner ones must be real\n // the outer points can be fudged for the edges.\n // therefore (wSrc-1)/wDst2\n const x = j * (wSrc - 1) / wDst2;\n const xPos = Math.floor(x);\n const t = x - xPos;\n const srcPos = (i * wSrc + xPos) * 4;\n const buf1Pos = (i * wDst2 + j) * 4;\n for (let k = 0; k < 4; k++) {\n const kPos = srcPos + k;\n const x0 = xPos > 0 ? bufSrc[kPos - 4] : 2 * bufSrc[kPos] - bufSrc[kPos + 4];\n const x1 = bufSrc[kPos];\n const x2 = bufSrc[kPos + 4];\n const x3 = xPos < wSrc - 2 ? bufSrc[kPos + 8] : 2 * bufSrc[kPos + 4] - bufSrc[kPos];\n buf1[buf1Pos + k] = interpolate(x0, x1, x2, x3, t);\n }\n }\n }\n // this._writeFile(wDst2, hSrc, buf1, \"out/buf1.jpg\");\n\n // ===========================================================\n // Pass 2 - interpolate columns\n // buf2 has width and height of dst2\n const buf2 = Buffer.alloc(wDst2 * hDst2 * 4);\n for (let i = 0; i < hDst2; i++) {\n for (let j = 0; j < wDst2; j++) {\n // i&j in dst2 coords\n\n // calculate y in buf1 coords\n // this interpolation requires 4 sample points and the two inner ones must be real\n // the outer points can be fudged for the edges.\n // therefore (hSrc-1)/hDst2\n const y = i * (hSrc - 1) / hDst2;\n const yPos = Math.floor(y);\n const t = y - yPos;\n const buf1Pos = (yPos * wDst2 + j) * 4;\n const buf2Pos = (i * wDst2 + j) * 4;\n for (let k = 0; k < 4; k++) {\n const kPos = buf1Pos + k;\n const y0 = yPos > 0 ? buf1[kPos - wDst2 * 4] : 2 * buf1[kPos] - buf1[kPos + wDst2 * 4];\n const y1 = buf1[kPos];\n const y2 = buf1[kPos + wDst2 * 4];\n const y3 = yPos < hSrc - 2 ? buf1[kPos + wDst2 * 8] : 2 * buf1[kPos + wDst2 * 4] - buf1[kPos];\n buf2[buf2Pos + k] = interpolate(y0, y1, y2, y3, t);\n }\n }\n }\n // this._writeFile(wDst2, hDst2, buf2, \"out/buf2.jpg\");\n\n // ===========================================================\n // Pass 3 - scale to dst\n const m = wM * hM;\n if (m > 1) {\n for (let i = 0; i < hDst; i++) {\n for (let j = 0; j < wDst; j++) {\n // i&j in dst bounded coords\n let r = 0;\n let g = 0;\n let b = 0;\n let a = 0;\n let realColors = 0;\n for (let y = 0; y < hM; y++) {\n const yPos = i * hM + y;\n for (let x = 0; x < wM; x++) {\n const xPos = j * wM + x;\n const xyPos = (yPos * wDst2 + xPos) * 4;\n const pixelAlpha = buf2[xyPos + 3];\n if (pixelAlpha) {\n r += buf2[xyPos];\n g += buf2[xyPos + 1];\n b += buf2[xyPos + 2];\n realColors++;\n }\n a += pixelAlpha;\n }\n }\n const pos = (i * wDst + j) * 4;\n bufDst[pos] = realColors ? Math.round(r / realColors) : 0;\n bufDst[pos + 1] = realColors ? Math.round(g / realColors) : 0;\n bufDst[pos + 2] = realColors ? Math.round(b / realColors) : 0;\n bufDst[pos + 3] = Math.round(a / m);\n }\n }\n } else {\n // replace dst buffer with buf2\n dst.data = buf2;\n }\n },\n bicubicInterpolation(src, dst, options) {\n const interpolateCubic = function (x0, x1, x2, x3, t) {\n const a0 = x3 - x2 - x0 + x1;\n const a1 = x0 - x1 - a0;\n const a2 = x2 - x0;\n const a3 = x1;\n return Math.max(0, Math.min(255, a0 * (t * t * t) + a1 * (t * t) + a2 * t + a3));\n };\n return this._interpolate2D(src, dst, options, interpolateCubic);\n },\n hermiteInterpolation(src, dst, options) {\n const interpolateHermite = function (x0, x1, x2, x3, t) {\n const c0 = x1;\n const c1 = 0.5 * (x2 - x0);\n const c2 = x0 - 2.5 * x1 + 2 * x2 - 0.5 * x3;\n const c3 = 0.5 * (x3 - x0) + 1.5 * (x1 - x2);\n return Math.max(0, Math.min(255, Math.round(((c3 * t + c2) * t + c1) * t + c0)));\n };\n return this._interpolate2D(src, dst, options, interpolateHermite);\n },\n bezierInterpolation(src, dst, options) {\n // between 2 points y(n), y(n+1), use next points out, y(n-1), y(n+2)\n // to predict control points (a & b) to be placed at n+0.5\n // ya(n) = y(n) + (y(n+1)-y(n-1))/4\n // yb(n) = y(n+1) - (y(n+2)-y(n))/4\n // then use std bezier to interpolate [n,n+1)\n // y(n+t) = y(n)*(1-t)^3 + 3 * ya(n)*(1-t)^2*t + 3 * yb(n)*(1-t)*t^2 + y(n+1)*t^3\n // note the 3* factor for the two control points\n // for edge cases, can choose:\n // y(-1) = y(0) - 2*(y(1)-y(0))\n // y(w) = y(w-1) + 2*(y(w-1)-y(w-2))\n // but can go with y(-1) = y(0) and y(w) = y(w-1)\n const interpolateBezier = function (x0, x1, x2, x3, t) {\n // x1, x2 are the knots, use x0 and x3 to calculate control points\n const cp1 = x1 + (x2 - x0) / 4;\n const cp2 = x2 - (x3 - x1) / 4;\n const nt = 1 - t;\n const c0 = x1 * nt * nt * nt;\n const c1 = 3 * cp1 * nt * nt * t;\n const c2 = 3 * cp2 * nt * t * t;\n const c3 = x2 * t * t * t;\n return Math.max(0, Math.min(255, Math.round(c0 + c1 + c2 + c3)));\n };\n return this._interpolate2D(src, dst, options, interpolateBezier);\n }\n};\nexport default operations;\n//# sourceMappingURL=resize2.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Rotates an image counter-clockwise by multiple of 90 degrees. NB: 'this' must be a Jimp object.\n *\n * This function is based on matrix rotation. Check this to get an initial idea how it works: https://stackoverflow.com/a/8664879/10561909\n *\n * @param {number} deg the number of degrees to rotate the image by, it should be a multiple of 90\n */\nfunction matrixRotate(deg) {\n if (Math.abs(deg) % 90 !== 0) {\n throw new Error(\"Unsupported matrix rotation degree\");\n }\n deg %= 360;\n if (Math.abs(deg) === 0) {\n // no rotation for 0, 360, -360, 720, -720, ...\n return;\n }\n const w = this.bitmap.width;\n const h = this.bitmap.height;\n\n // decide which rotation angle to use\n let angle;\n switch (deg) {\n // 90 degree & -270 degree are same\n case 90:\n case -270:\n angle = 90;\n break;\n case 180:\n case -180:\n angle = 180;\n break;\n case 270:\n case -90:\n angle = -90;\n break;\n default:\n throw new Error(\"Unsupported matrix rotation degree\");\n }\n // After this switch block, angle will be 90, 180 or -90\n\n // calculate the new width and height\n const nW = angle === 180 ? w : h;\n const nH = angle === 180 ? h : w;\n const dstBuffer = Buffer.alloc(this.bitmap.data.length);\n\n // function to translate the x, y coordinate to the index of the pixel in the buffer\n function createIdxTranslationFunction(w, h) {\n return function (x, y) {\n return y * w + x << 2;\n };\n }\n const srcIdxFunction = createIdxTranslationFunction(w, h);\n const dstIdxFunction = createIdxTranslationFunction(nW, nH);\n for (let x = 0; x < w; x++) {\n for (let y = 0; y < h; y++) {\n const srcIdx = srcIdxFunction(x, y);\n const pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx);\n let dstIdx;\n switch (angle) {\n case 90:\n dstIdx = dstIdxFunction(y, w - x - 1);\n break;\n case -90:\n dstIdx = dstIdxFunction(h - y - 1, x);\n break;\n case 180:\n dstIdx = dstIdxFunction(w - x - 1, h - y - 1);\n break;\n default:\n throw new Error(\"Unsupported matrix rotation angle\");\n }\n dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);\n }\n }\n this.bitmap.data = dstBuffer;\n this.bitmap.width = nW;\n this.bitmap.height = nH;\n}\n\n/**\n * Rotates an image counter-clockwise by an arbitrary number of degrees. NB: 'this' must be a Jimp object.\n * @param {number} deg the number of degrees to rotate the image by\n * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed\n */\nfunction advancedRotate(deg, mode) {\n deg %= 360;\n const rad = deg * Math.PI / 180;\n const cosine = Math.cos(rad);\n const sine = Math.sin(rad);\n\n // the final width and height will change if resize == true\n let w = this.bitmap.width;\n let h = this.bitmap.height;\n if (mode === true || typeof mode === \"string\") {\n // resize the image to it maximum dimension and blit the existing image\n // onto the center so that when it is rotated the image is kept in bounds\n\n // http://stackoverflow.com/questions/3231176/how-to-get-size-of-a-rotated-rectangle\n // Plus 1 border pixel to ensure to show all rotated result for some cases.\n w = Math.ceil(Math.abs(this.bitmap.width * cosine) + Math.abs(this.bitmap.height * sine)) + 1;\n h = Math.ceil(Math.abs(this.bitmap.width * sine) + Math.abs(this.bitmap.height * cosine)) + 1;\n // Ensure destination to have even size to a better result.\n if (w % 2 !== 0) {\n w++;\n }\n if (h % 2 !== 0) {\n h++;\n }\n const c = this.cloneQuiet();\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n this.bitmap.data.writeUInt32BE(this._background, idx);\n });\n const max = Math.max(w, h, this.bitmap.width, this.bitmap.height);\n this.resize(max, max, mode);\n this.blit(c, this.bitmap.width / 2 - c.bitmap.width / 2, this.bitmap.height / 2 - c.bitmap.height / 2);\n }\n const bW = this.bitmap.width;\n const bH = this.bitmap.height;\n const dstBuffer = Buffer.alloc(this.bitmap.data.length);\n function createTranslationFunction(deltaX, deltaY) {\n return function (x, y) {\n return {\n x: x + deltaX,\n y: y + deltaY\n };\n };\n }\n const translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2));\n const translate2Screen = createTranslationFunction(bW / 2 + 0.5, bH / 2 + 0.5);\n for (let y = 1; y <= bH; y++) {\n for (let x = 1; x <= bW; x++) {\n const cartesian = translate2Cartesian(x, y);\n const source = translate2Screen(cosine * cartesian.x - sine * cartesian.y, cosine * cartesian.y + sine * cartesian.x);\n const dstIdx = bW * (y - 1) + x - 1 << 2;\n if (source.x >= 0 && source.x < bW && source.y >= 0 && source.y < bH) {\n const srcIdx = (bW * (source.y | 0) + source.x | 0) << 2;\n const pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx);\n dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);\n } else {\n // reset off-image pixels\n dstBuffer.writeUInt32BE(this._background, dstIdx);\n }\n }\n }\n this.bitmap.data = dstBuffer;\n if (mode === true || typeof mode === \"string\") {\n // now crop the image to the final size\n const x = bW / 2 - w / 2;\n const y = bH / 2 - h / 2;\n this.crop(x, y, w, h);\n }\n}\nexport default (() => ({\n /**\n * Rotates the image counter-clockwise by a number of degrees. By default the width and height of the image will be resized appropriately.\n * @param {number} deg the number of degrees to rotate the image by\n * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n rotate(deg, mode, cb) {\n // enable overloading\n if (typeof mode === \"undefined\" || mode === null) {\n // e.g. image.resize(120);\n // e.g. image.resize(120, null, cb);\n // e.g. image.resize(120, undefined, cb);\n mode = true;\n }\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n // e.g. image.resize(120, cb);\n cb = mode;\n mode = true;\n }\n if (typeof deg !== \"number\") {\n return throwError.call(this, \"deg must be a number\", cb);\n }\n if (typeof mode !== \"boolean\" && typeof mode !== \"string\") {\n return throwError.call(this, \"mode must be a boolean or a string\", cb);\n }\n\n // use matrixRotate if the angle is a multiple of 90 degrees (eg: 180 or -90) and resize is allowed or not needed.\n const matrixRotateAllowed = deg % 90 === 0 && (mode || this.bitmap.width === this.bitmap.height || deg % 180 === 0);\n if (matrixRotateAllowed) {\n matrixRotate.call(this, deg);\n } else {\n advancedRotate.call(this, deg, mode, cb);\n }\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { mergeDeep } from \"timm\";\nimport blit from \"@jimp/plugin-blit\";\nimport blur from \"@jimp/plugin-blur\";\nimport circle from \"@jimp/plugin-circle\";\nimport color from \"@jimp/plugin-color\";\nimport contain from \"@jimp/plugin-contain\";\nimport cover from \"@jimp/plugin-cover\";\nimport crop from \"@jimp/plugin-crop\";\nimport displace from \"@jimp/plugin-displace\";\nimport dither from \"@jimp/plugin-dither\";\nimport fisheye from \"@jimp/plugin-fisheye\";\nimport flip from \"@jimp/plugin-flip\";\nimport gaussian from \"@jimp/plugin-gaussian\";\nimport invert from \"@jimp/plugin-invert\";\nimport mask from \"@jimp/plugin-mask\";\nimport normalize from \"@jimp/plugin-normalize\";\nimport print from \"@jimp/plugin-print\";\nimport resize from \"@jimp/plugin-resize\";\nimport rotate from \"@jimp/plugin-rotate\";\nimport scale from \"@jimp/plugin-scale\";\nimport shadow from \"@jimp/plugin-shadow\";\nimport threshold from \"@jimp/plugin-threshold\";\nconst plugins = [blit, blur, circle, color, contain, cover, crop, displace, dither, fisheye, flip, gaussian, invert, mask, normalize, print, resize, rotate, scale, shadow, threshold];\nexport default (jimpEvChange => {\n const initializedPlugins = plugins.map(pluginModule => {\n let plugin = pluginModule(jimpEvChange) || {};\n if (!plugin.class && !plugin.constants) {\n // Default to class function\n plugin = {\n class: plugin\n };\n }\n return plugin;\n });\n return mergeDeep(...initializedPlugins);\n});\n//# sourceMappingURL=index.js.map","import { throwError, isNodePattern } from \"@jimp/utils\";\nexport default (() => ({\n /**\n * Blits a source image on to this image\n * @param {Jimp} src the source Jimp instance\n * @param {number} x the x position to blit the image\n * @param {number} y the y position to blit the image\n * @param {number} srcx (optional) the x position from which to crop the source image\n * @param {number} srcy (optional) the y position from which to crop the source image\n * @param {number} srcw (optional) the width to which to crop the source image\n * @param {number} srch (optional) the height to which to crop the source image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n blit(src, x, y, srcx, srcy, srcw, srch, cb) {\n if (!(src instanceof this.constructor)) {\n return throwError.call(this, \"The source must be a Jimp image\", cb);\n }\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n if (typeof srcx === \"function\") {\n cb = srcx;\n srcx = 0;\n srcy = 0;\n srcw = src.bitmap.width;\n srch = src.bitmap.height;\n } else if (typeof srcx === typeof srcy && typeof srcy === typeof srcw && typeof srcw === typeof srch) {\n srcx = srcx || 0;\n srcy = srcy || 0;\n srcw = srcw || src.bitmap.width;\n srch = srch || src.bitmap.height;\n } else {\n return throwError.call(this, \"srcx, srcy, srcw, srch must be numbers\", cb);\n }\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n\n // round input\n srcx = Math.round(srcx);\n srcy = Math.round(srcy);\n srcw = Math.round(srcw);\n srch = Math.round(srch);\n const maxWidth = this.bitmap.width;\n const maxHeight = this.bitmap.height;\n const baseImage = this;\n src.scanQuiet(srcx, srcy, srcw, srch, function (sx, sy, idx) {\n const xOffset = x + sx - srcx;\n const yOffset = y + sy - srcy;\n if (xOffset >= 0 && yOffset >= 0 && maxWidth - xOffset > 0 && maxHeight - yOffset > 0) {\n const dstIdx = baseImage.getPixelIndex(xOffset, yOffset);\n const src = {\n r: this.bitmap.data[idx],\n g: this.bitmap.data[idx + 1],\n b: this.bitmap.data[idx + 2],\n a: this.bitmap.data[idx + 3]\n };\n const dst = {\n r: baseImage.bitmap.data[dstIdx],\n g: baseImage.bitmap.data[dstIdx + 1],\n b: baseImage.bitmap.data[dstIdx + 2],\n a: baseImage.bitmap.data[dstIdx + 3]\n };\n baseImage.bitmap.data[dstIdx] = (src.a * (src.r - dst.r) - dst.r + 255 >> 8) + dst.r;\n baseImage.bitmap.data[dstIdx + 1] = (src.a * (src.g - dst.g) - dst.g + 255 >> 8) + dst.g;\n baseImage.bitmap.data[dstIdx + 2] = (src.a * (src.b - dst.b) - dst.b + 255 >> 8) + dst.b;\n baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(dst.a + src.a);\n }\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { throwError, isNodePattern } from \"@jimp/utils\";\nimport { mulTable, shgTable } from \"./blur-tables\";\n\n/*\n Superfast Blur (0.5)\n http://www.quasimondo.com/BoxBlurForCanvas/FastBlur.js\n\n Copyright (c) 2011 Mario Klingemann\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n*/\n\nexport default (() => ({\n /**\n * A fast blur algorithm that produces similar effect to a Gaussian blur - but MUCH quicker\n * @param {number} r the pixel radius of the blur\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n blur(r, cb) {\n if (typeof r !== \"number\") return throwError.call(this, \"r must be a number\", cb);\n if (r < 1) return throwError.call(this, \"r must be greater than 0\", cb);\n let rsum;\n let gsum;\n let bsum;\n let asum;\n let x;\n let y;\n let i;\n let p;\n let p1;\n let p2;\n let yp;\n let yi;\n let yw;\n let pa;\n const wm = this.bitmap.width - 1;\n const hm = this.bitmap.height - 1;\n // const wh = this.bitmap.width * this.bitmap.height;\n const rad1 = r + 1;\n const mulSum = mulTable[r];\n const shgSum = shgTable[r];\n const red = [];\n const green = [];\n const blue = [];\n const alpha = [];\n const vmin = [];\n const vmax = [];\n let iterations = 2;\n while (iterations-- > 0) {\n yi = 0;\n yw = 0;\n for (y = 0; y < this.bitmap.height; y++) {\n rsum = this.bitmap.data[yw] * rad1;\n gsum = this.bitmap.data[yw + 1] * rad1;\n bsum = this.bitmap.data[yw + 2] * rad1;\n asum = this.bitmap.data[yw + 3] * rad1;\n for (i = 1; i <= r; i++) {\n p = yw + ((i > wm ? wm : i) << 2);\n rsum += this.bitmap.data[p++];\n gsum += this.bitmap.data[p++];\n bsum += this.bitmap.data[p++];\n asum += this.bitmap.data[p];\n }\n for (x = 0; x < this.bitmap.width; x++) {\n red[yi] = rsum;\n green[yi] = gsum;\n blue[yi] = bsum;\n alpha[yi] = asum;\n if (y === 0) {\n vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2;\n vmax[x] = (p = x - r) > 0 ? p << 2 : 0;\n }\n p1 = yw + vmin[x];\n p2 = yw + vmax[x];\n rsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];\n gsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];\n bsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];\n asum += this.bitmap.data[p1] - this.bitmap.data[p2];\n yi++;\n }\n yw += this.bitmap.width << 2;\n }\n for (x = 0; x < this.bitmap.width; x++) {\n yp = x;\n rsum = red[yp] * rad1;\n gsum = green[yp] * rad1;\n bsum = blue[yp] * rad1;\n asum = alpha[yp] * rad1;\n for (i = 1; i <= r; i++) {\n yp += i > hm ? 0 : this.bitmap.width;\n rsum += red[yp];\n gsum += green[yp];\n bsum += blue[yp];\n asum += alpha[yp];\n }\n yi = x << 2;\n for (y = 0; y < this.bitmap.height; y++) {\n pa = asum * mulSum >>> shgSum;\n this.bitmap.data[yi + 3] = pa;\n\n // normalize alpha\n if (pa > 255) {\n this.bitmap.data[yi + 3] = 255;\n }\n if (pa > 0) {\n pa = 255 / pa;\n this.bitmap.data[yi] = (rsum * mulSum >>> shgSum) * pa;\n this.bitmap.data[yi + 1] = (gsum * mulSum >>> shgSum) * pa;\n this.bitmap.data[yi + 2] = (bsum * mulSum >>> shgSum) * pa;\n } else {\n this.bitmap.data[yi + 2] = 0;\n this.bitmap.data[yi + 1] = 0;\n this.bitmap.data[yi] = 0;\n }\n if (x === 0) {\n vmin[y] = ((p = y + rad1) < hm ? p : hm) * this.bitmap.width;\n vmax[y] = (p = y - r) > 0 ? p * this.bitmap.width : 0;\n }\n p1 = x + vmin[y];\n p2 = x + vmax[y];\n rsum += red[p1] - red[p2];\n gsum += green[p1] - green[p2];\n bsum += blue[p1] - blue[p2];\n asum += alpha[p1] - alpha[p2];\n yi += this.bitmap.width << 2;\n }\n }\n }\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Creates a circle out of an image.\n * @param {function(Error, Jimp)} options (optional) radius, x, y\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n circle() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let cb = arguments.length > 1 ? arguments[1] : undefined;\n if (typeof options === \"function\") {\n cb = options;\n options = {};\n }\n const radius = options.radius || (this.bitmap.width > this.bitmap.height ? this.bitmap.height : this.bitmap.width) / 2;\n const center = {\n x: typeof options.x === \"number\" ? options.x : this.bitmap.width / 2,\n y: typeof options.y === \"number\" ? options.y : this.bitmap.height / 2\n };\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n const curR = Math.sqrt(Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2));\n if (radius - curR <= 0.0) {\n this.bitmap.data[idx + 3] = 0;\n } else if (radius - curR < 1.0) {\n this.bitmap.data[idx + 3] = 255 * (radius - curR);\n }\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed.\n * @param {number} w the width to resize the image to\n * @param {number} h the height to resize the image to\n * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n contain(w, h, alignBits, mode, cb) {\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n\n // permit any sort of optional parameters combination\n if (typeof alignBits === \"string\") {\n if (typeof mode === \"function\" && typeof cb === \"undefined\") cb = mode;\n mode = alignBits;\n alignBits = null;\n }\n if (typeof alignBits === \"function\") {\n if (typeof cb === \"undefined\") cb = alignBits;\n mode = null;\n alignBits = null;\n }\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE;\n const hbits = alignBits & (1 << 3) - 1;\n const vbits = alignBits >> 3;\n\n // check if more flags than one is in the bit sets\n if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) {\n return throwError.call(this, \"only use one flag per alignment direction\", cb);\n }\n const alignH = hbits >> 1; // 0, 1, 2\n const alignV = vbits >> 1; // 0, 1, 2\n\n const f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width;\n const c = this.cloneQuiet().scale(f, mode);\n this.resize(w, h, mode);\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n this.bitmap.data.writeUInt32BE(this._background, idx);\n });\n this.blit(c, (this.bitmap.width - c.bitmap.width) / 2 * alignH, (this.bitmap.height - c.bitmap.height) / 2 * alignV);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped.\n * @param {number} w the width to resize the image to\n * @param {number} h the height to resize the image to\n * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n cover(w, h, alignBits, mode, cb) {\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n if (alignBits && typeof alignBits === \"function\" && typeof cb === \"undefined\") {\n cb = alignBits;\n alignBits = null;\n mode = null;\n } else if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE;\n const hbits = alignBits & (1 << 3) - 1;\n const vbits = alignBits >> 3;\n\n // check if more flags than one is in the bit sets\n if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) return throwError.call(this, \"only use one flag per alignment direction\", cb);\n const alignH = hbits >> 1; // 0, 1, 2\n const alignV = vbits >> 1; // 0, 1, 2\n\n const f = w / h > this.bitmap.width / this.bitmap.height ? w / this.bitmap.width : h / this.bitmap.height;\n this.scale(f, mode);\n this.crop((this.bitmap.width - w) / 2 * alignH, (this.bitmap.height - h) / 2 * alignV, w, h);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","/* eslint-disable no-labels */\n\nimport { throwError, isNodePattern } from \"@jimp/utils\";\nexport default function pluginCrop(event) {\n /**\n * Crops the image at a given point to a give size\n * @param {number} x the x coordinate to crop form\n * @param {number} y the y coordinate to crop form\n * @param w the width of the crop region\n * @param h the height of the crop region\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n event(\"crop\", function (x, y, w, h, cb) {\n if (typeof x !== \"number\" || typeof y !== \"number\") return throwError.call(this, \"x and y must be numbers\", cb);\n if (typeof w !== \"number\" || typeof h !== \"number\") return throwError.call(this, \"w and h must be numbers\", cb);\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n w = Math.round(w);\n h = Math.round(h);\n if (x === 0 && w === this.bitmap.width) {\n // shortcut\n const start = w * y + x << 2;\n const end = start + (h * w << 2);\n this.bitmap.data = this.bitmap.data.slice(start, end);\n } else {\n const bitmap = Buffer.allocUnsafe(w * h * 4);\n let offset = 0;\n this.scanQuiet(x, y, w, h, function (x, y, idx) {\n const data = this.bitmap.data.readUInt32BE(idx, true);\n bitmap.writeUInt32BE(data, offset, true);\n offset += 4;\n });\n this.bitmap.data = bitmap;\n }\n this.bitmap.width = w;\n this.bitmap.height = h;\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n });\n return {\n class: {\n /**\n * Autocrop same color borders from this image\n * @param {number} tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%)\n * @param {boolean} cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true)\n * @param {function(Error, Jimp)} cb (optional): a callback for when complete (default: no callback)\n * @returns {Jimp} this for chaining of methods\n */\n autocrop() {\n const w = this.bitmap.width;\n const h = this.bitmap.height;\n const minPixelsPerSide = 1; // to avoid cropping completely the image, resulting in an invalid 0 sized image\n\n let cb; // callback\n let leaveBorder = 0; // Amount of pixels in border to leave\n let tolerance = 0.0002; // percent of color difference tolerance (default value)\n let cropOnlyFrames = true; // flag to force cropping only if the image has a real \"frame\"\n // i.e. all 4 sides have some border (default value)\n let cropSymmetric = false; // flag to force cropping top be symmetric.\n // i.e. north and south / east and west are cropped by the same value\n let ignoreSides = {\n north: false,\n south: false,\n east: false,\n west: false\n };\n\n // parse arguments\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n for (let a = 0, len = args.length; a < len; a++) {\n if (typeof args[a] === \"number\") {\n // tolerance value passed\n tolerance = args[a];\n }\n if (typeof args[a] === \"boolean\") {\n // cropOnlyFrames value passed\n cropOnlyFrames = args[a];\n }\n if (typeof args[a] === \"function\") {\n // callback value passed\n cb = args[a];\n }\n if (typeof args[a] === \"object\") {\n // config object passed\n const config = args[a];\n if (typeof config.tolerance !== \"undefined\") {\n ({\n tolerance\n } = config);\n }\n if (typeof config.cropOnlyFrames !== \"undefined\") {\n ({\n cropOnlyFrames\n } = config);\n }\n if (typeof config.cropSymmetric !== \"undefined\") {\n ({\n cropSymmetric\n } = config);\n }\n if (typeof config.leaveBorder !== \"undefined\") {\n ({\n leaveBorder\n } = config);\n }\n if (typeof config.ignoreSides !== \"undefined\") {\n ({\n ignoreSides\n } = config);\n }\n }\n }\n\n /**\n * All borders must be of the same color as the top left pixel, to be cropped.\n * It should be possible to crop borders each with a different color,\n * but since there are many ways for corners to intersect, it would\n * introduce unnecessary complexity to the algorithm.\n */\n\n // scan each side for same color borders\n let colorTarget = this.getPixelColor(0, 0); // top left pixel color is the target color\n const rgba1 = this.constructor.intToRGBA(colorTarget);\n\n // for north and east sides\n let northPixelsToCrop = 0;\n let eastPixelsToCrop = 0;\n let southPixelsToCrop = 0;\n let westPixelsToCrop = 0;\n\n // north side (scan rows from north to south)\n colorTarget = this.getPixelColor(0, 0);\n if (!ignoreSides.north) {\n north: for (let y = 0; y < h - minPixelsPerSide; y++) {\n for (let x = 0; x < w; x++) {\n const colorXY = this.getPixelColor(x, y);\n const rgba2 = this.constructor.intToRGBA(colorXY);\n if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {\n // this pixel is too distant from the first one: abort this side scan\n break north;\n }\n }\n\n // this row contains all pixels with the same color: increment this side pixels to crop\n northPixelsToCrop++;\n }\n }\n\n // west side (scan columns from west to east)\n colorTarget = this.getPixelColor(w, 0);\n if (!ignoreSides.west) {\n west: for (let x = 0; x < w - minPixelsPerSide; x++) {\n for (let y = 0 + northPixelsToCrop; y < h; y++) {\n const colorXY = this.getPixelColor(x, y);\n const rgba2 = this.constructor.intToRGBA(colorXY);\n if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {\n // this pixel is too distant from the first one: abort this side scan\n break west;\n }\n }\n\n // this column contains all pixels with the same color: increment this side pixels to crop\n westPixelsToCrop++;\n }\n }\n\n // south side (scan rows from south to north)\n colorTarget = this.getPixelColor(0, h);\n if (!ignoreSides.south) {\n south: for (let y = h - 1; y >= northPixelsToCrop + minPixelsPerSide; y--) {\n for (let x = w - eastPixelsToCrop - 1; x >= 0; x--) {\n const colorXY = this.getPixelColor(x, y);\n const rgba2 = this.constructor.intToRGBA(colorXY);\n if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {\n // this pixel is too distant from the first one: abort this side scan\n break south;\n }\n }\n\n // this row contains all pixels with the same color: increment this side pixels to crop\n southPixelsToCrop++;\n }\n }\n\n // east side (scan columns from east to west)\n colorTarget = this.getPixelColor(w, h);\n if (!ignoreSides.east) {\n east: for (let x = w - 1; x >= 0 + westPixelsToCrop + minPixelsPerSide; x--) {\n for (let y = h - 1; y >= 0 + northPixelsToCrop; y--) {\n const colorXY = this.getPixelColor(x, y);\n const rgba2 = this.constructor.intToRGBA(colorXY);\n if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {\n // this pixel is too distant from the first one: abort this side scan\n break east;\n }\n }\n\n // this column contains all pixels with the same color: increment this side pixels to crop\n eastPixelsToCrop++;\n }\n }\n\n // decide if a crop is needed\n let doCrop = false;\n\n // apply leaveBorder\n westPixelsToCrop -= leaveBorder;\n eastPixelsToCrop -= leaveBorder;\n northPixelsToCrop -= leaveBorder;\n southPixelsToCrop -= leaveBorder;\n if (cropSymmetric) {\n const horizontal = Math.min(eastPixelsToCrop, westPixelsToCrop);\n const vertical = Math.min(northPixelsToCrop, southPixelsToCrop);\n westPixelsToCrop = horizontal;\n eastPixelsToCrop = horizontal;\n northPixelsToCrop = vertical;\n southPixelsToCrop = vertical;\n }\n\n // make sure that crops are >= 0\n westPixelsToCrop = westPixelsToCrop >= 0 ? westPixelsToCrop : 0;\n eastPixelsToCrop = eastPixelsToCrop >= 0 ? eastPixelsToCrop : 0;\n northPixelsToCrop = northPixelsToCrop >= 0 ? northPixelsToCrop : 0;\n southPixelsToCrop = southPixelsToCrop >= 0 ? southPixelsToCrop : 0;\n\n // safety checks\n const widthOfRemainingPixels = w - (westPixelsToCrop + eastPixelsToCrop);\n const heightOfRemainingPixels = h - (southPixelsToCrop + northPixelsToCrop);\n if (cropOnlyFrames) {\n // crop image if all sides should be cropped\n doCrop = eastPixelsToCrop !== 0 && northPixelsToCrop !== 0 && westPixelsToCrop !== 0 && southPixelsToCrop !== 0;\n } else {\n // crop image if at least one side should be cropped\n doCrop = eastPixelsToCrop !== 0 || northPixelsToCrop !== 0 || westPixelsToCrop !== 0 || southPixelsToCrop !== 0;\n }\n if (doCrop) {\n // do the real crop\n this.crop(westPixelsToCrop, northPixelsToCrop, widthOfRemainingPixels, heightOfRemainingPixels);\n }\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n }\n };\n}\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Displaces the image based on the provided displacement map\n * @param {object} map the source Jimp instance\n * @param {number} offset the maximum displacement value\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n displace(map, offset, cb) {\n if (typeof map !== \"object\" || map.constructor !== this.constructor) {\n return throwError.call(this, \"The source must be a Jimp image\", cb);\n }\n if (typeof offset !== \"number\") {\n return throwError.call(this, \"factor must be a number\", cb);\n }\n const source = this.cloneQuiet();\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n let displacement = map.bitmap.data[idx] / 256 * offset;\n displacement = Math.round(displacement);\n const ids = this.getPixelIndex(x + displacement, y);\n this.bitmap.data[ids] = source.bitmap.data[idx];\n this.bitmap.data[ids + 1] = source.bitmap.data[idx + 1];\n this.bitmap.data[ids + 2] = source.bitmap.data[idx + 2];\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Creates a circle out of an image.\n * @param {object} options (optional) r: radius of effect\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n fisheye() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {\n r: 2.5\n };\n let cb = arguments.length > 1 ? arguments[1] : undefined;\n if (typeof options === \"function\") {\n cb = options;\n options = {\n r: 2.5\n };\n }\n const source = this.cloneQuiet();\n const {\n width,\n height\n } = source.bitmap;\n source.scanQuiet(0, 0, width, height, (x, y) => {\n const hx = x / width;\n const hy = y / height;\n const r = Math.sqrt(Math.pow(hx - 0.5, 2) + Math.pow(hy - 0.5, 2));\n const rn = 2 * Math.pow(r, options.r);\n const cosA = (hx - 0.5) / r;\n const sinA = (hy - 0.5) / r;\n const newX = Math.round((rn * cosA + 0.5) * width);\n const newY = Math.round((rn * sinA + 0.5) * height);\n const color = source.getPixelColor(newX, newY);\n this.setPixelColor(color, x, y);\n });\n\n /* Set center pixel color, otherwise it will be transparent */\n this.setPixelColor(source.getPixelColor(width / 2, height / 2), width / 2, height / 2);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Applies a true Gaussian blur to the image (warning: this is VERY slow)\n * @param {number} r the pixel radius of the blur\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n gaussian(r, cb) {\n // http://blog.ivank.net/fastest-gaussian-blur.html\n if (typeof r !== \"number\") {\n return throwError.call(this, \"r must be a number\", cb);\n }\n if (r < 1) {\n return throwError.call(this, \"r must be greater than 0\", cb);\n }\n const rs = Math.ceil(r * 2.57); // significant radius\n const range = rs * 2 + 1;\n const rr2 = r * r * 2;\n const rr2pi = rr2 * Math.PI;\n const weights = [];\n for (let y = 0; y < range; y++) {\n weights[y] = [];\n for (let x = 0; x < range; x++) {\n const dsq = (x - rs) ** 2 + (y - rs) ** 2;\n weights[y][x] = Math.exp(-dsq / rr2) / rr2pi;\n }\n }\n for (let y = 0; y < this.bitmap.height; y++) {\n for (let x = 0; x < this.bitmap.width; x++) {\n let red = 0;\n let green = 0;\n let blue = 0;\n let alpha = 0;\n let wsum = 0;\n for (let iy = 0; iy < range; iy++) {\n for (let ix = 0; ix < range; ix++) {\n const x1 = Math.min(this.bitmap.width - 1, Math.max(0, ix + x - rs));\n const y1 = Math.min(this.bitmap.height - 1, Math.max(0, iy + y - rs));\n const weight = weights[iy][ix];\n const idx = y1 * this.bitmap.width + x1 << 2;\n red += this.bitmap.data[idx] * weight;\n green += this.bitmap.data[idx + 1] * weight;\n blue += this.bitmap.data[idx + 2] * weight;\n alpha += this.bitmap.data[idx + 3] * weight;\n wsum += weight;\n }\n const idx = y * this.bitmap.width + x << 2;\n this.bitmap.data[idx] = Math.round(red / wsum);\n this.bitmap.data[idx + 1] = Math.round(green / wsum);\n this.bitmap.data[idx + 2] = Math.round(blue / wsum);\n this.bitmap.data[idx + 3] = Math.round(alpha / wsum);\n }\n }\n }\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Inverts the image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n invert(cb) {\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {\n this.bitmap.data[idx] = 255 - this.bitmap.data[idx];\n this.bitmap.data[idx + 1] = 255 - this.bitmap.data[idx + 1];\n this.bitmap.data[idx + 2] = 255 - this.bitmap.data[idx + 2];\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent.\n * @param {Jimp} src the source Jimp instance\n * @param {number} x the horizontal position to blit the image\n * @param {number} y the vertical position to blit the image\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n mask(src) {\n let x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n let y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n let cb = arguments.length > 3 ? arguments[3] : undefined;\n if (!(src instanceof this.constructor)) {\n return throwError.call(this, \"The source must be a Jimp image\", cb);\n }\n if (typeof x !== \"number\" || typeof y !== \"number\") {\n return throwError.call(this, \"x and y must be numbers\", cb);\n }\n\n // round input\n x = Math.round(x);\n y = Math.round(y);\n const w = this.bitmap.width;\n const h = this.bitmap.height;\n const baseImage = this;\n src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) {\n const destX = x + sx;\n const destY = y + sy;\n if (destX >= 0 && destY >= 0 && destX < w && destY < h) {\n const dstIdx = baseImage.getPixelIndex(destX, destY);\n const {\n data\n } = this.bitmap;\n const avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3;\n baseImage.bitmap.data[dstIdx + 3] *= avg / 255;\n }\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { throwError, isNodePattern } from \"@jimp/utils\";\nimport Resize from \"./modules/resize\";\nimport Resize2 from \"./modules/resize2\";\nexport default (() => ({\n constants: {\n RESIZE_NEAREST_NEIGHBOR: \"nearestNeighbor\",\n RESIZE_BILINEAR: \"bilinearInterpolation\",\n RESIZE_BICUBIC: \"bicubicInterpolation\",\n RESIZE_HERMITE: \"hermiteInterpolation\",\n RESIZE_BEZIER: \"bezierInterpolation\"\n },\n class: {\n /**\n * Resizes the image to a set width and height using a 2-pass bilinear algorithm\n * @param {number} w the width to resize the image to (or Jimp.AUTO)\n * @param {number} h the height to resize the image to (or Jimp.AUTO)\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n resize(w, h, mode, cb) {\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n if (w === this.constructor.AUTO && h === this.constructor.AUTO) {\n return throwError.call(this, \"w and h cannot both be set to auto\", cb);\n }\n if (w === this.constructor.AUTO) {\n w = this.bitmap.width * (h / this.bitmap.height);\n }\n if (h === this.constructor.AUTO) {\n h = this.bitmap.height * (w / this.bitmap.width);\n }\n if (w < 0 || h < 0) {\n return throwError.call(this, \"w and h must be positive numbers\", cb);\n }\n\n // round inputs\n w = Math.round(w) || 1;\n h = Math.round(h) || 1;\n if (typeof Resize2[mode] === \"function\") {\n const dst = {\n data: Buffer.alloc(w * h * 4),\n width: w,\n height: h\n };\n Resize2[mode](this.bitmap, dst);\n this.bitmap = dst;\n } else {\n const image = this;\n const resize = new Resize(this.bitmap.width, this.bitmap.height, w, h, true, true, buffer => {\n image.bitmap.data = Buffer.from(buffer);\n image.bitmap.width = w;\n image.bitmap.height = h;\n });\n resize.resize(this.bitmap.data);\n }\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\nexport default (() => ({\n /**\n * Uniformly scales the image by a factor.\n * @param {number} f the factor to scale the image by\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n scale(f, mode, cb) {\n if (typeof f !== \"number\") {\n return throwError.call(this, \"f must be a number\", cb);\n }\n if (f < 0) {\n return throwError.call(this, \"f must be a positive number\", cb);\n }\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n const w = this.bitmap.width * f;\n const h = this.bitmap.height * f;\n this.resize(w, h, mode);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n },\n /**\n * Scale the image to the largest size that fits inside the rectangle that has the given width and height.\n * @param {number} w the width to resize the image to\n * @param {number} h the height to resize the image to\n * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\n scaleToFit(w, h, mode, cb) {\n if (typeof w !== \"number\" || typeof h !== \"number\") {\n return throwError.call(this, \"w and h must be numbers\", cb);\n }\n if (typeof mode === \"function\" && typeof cb === \"undefined\") {\n cb = mode;\n mode = null;\n }\n const f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width;\n this.scale(f, mode);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern } from \"@jimp/utils\";\n\n/**\n * Creates a circle out of an image.\n * @param {function(Error, Jimp)} options (optional)\n * opacity - opacity of the shadow between 0 and 1\n * size,- of the shadow\n * blur - how blurry the shadow is\n * x- x position of shadow\n * y - y position of shadow\n * @param {function(Error, Jimp)} cb (optional) a callback for when complete\n * @returns {Jimp} this for chaining of methods\n */\nexport default (() => ({\n shadow() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let cb = arguments.length > 1 ? arguments[1] : undefined;\n if (typeof options === \"function\") {\n cb = options;\n options = {};\n }\n const {\n opacity = 0.7,\n size = 1.1,\n x = -25,\n y = 25,\n blur = 5\n } = options;\n\n // clone the image\n const orig = this.clone();\n const shadow = this.clone();\n\n // turn all it's pixels black\n shadow.scan(0, 0, shadow.bitmap.width, shadow.bitmap.height, (x, y, idx) => {\n shadow.bitmap.data[idx] = 0x00;\n shadow.bitmap.data[idx + 1] = 0x00;\n shadow.bitmap.data[idx + 2] = 0x00;\n // up the opacity a little,\n shadow.bitmap.data[idx + 3] = shadow.constructor.limit255(shadow.bitmap.data[idx + 3] * opacity);\n this.bitmap.data[idx] = 0x00;\n this.bitmap.data[idx + 1] = 0x00;\n this.bitmap.data[idx + 2] = 0x00;\n this.bitmap.data[idx + 3] = 0x00;\n });\n\n // enlarge it. This creates a \"shadow\".\n shadow.resize(shadow.bitmap.width * size, shadow.bitmap.height * size).blur(blur);\n\n // Then blit the \"shadow\" onto the background and the image on top of that.\n this.composite(shadow, x, y);\n this.composite(orig, 0, 0);\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import { isNodePattern, throwError } from \"@jimp/utils\";\n\n/**\n * Applies a minimum color threshold to a greyscale image. Converts image to greyscale by default\n * @param {number} options object\n * max: A number auto limited between 0 - 255\n * replace: (optional) A number auto limited between 0 - 255 (default 255)\n * autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true)\n * @param {number} cb (optional) a callback for when complete\n * @return {this} this for chaining of methods\n */\nexport default (() => ({\n threshold(_ref, cb) {\n let {\n max,\n replace = 255,\n autoGreyscale = true\n } = _ref;\n if (typeof max !== \"number\") {\n return throwError.call(this, \"max must be a number\", cb);\n }\n if (typeof replace !== \"number\") {\n return throwError.call(this, \"replace must be a number\", cb);\n }\n if (typeof autoGreyscale !== \"boolean\") {\n return throwError.call(this, \"autoGreyscale must be a boolean\", cb);\n }\n max = this.constructor.limit255(max);\n replace = this.constructor.limit255(replace);\n if (autoGreyscale) {\n this.greyscale();\n }\n this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {\n const grey = this.bitmap.data[idx] < max ? this.bitmap.data[idx] : replace;\n this.bitmap.data[idx] = grey;\n this.bitmap.data[idx + 1] = grey;\n this.bitmap.data[idx + 2] = grey;\n });\n if (isNodePattern(cb)) {\n cb.call(this, null, this);\n }\n return this;\n }\n}));\n//# sourceMappingURL=index.js.map","import Jimp, { addType, addJimpMethods, addConstants, jimpEvChange } from \"@jimp/core\";\nexport default function configure(configuration) {\n let jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp;\n const jimpConfig = {\n hasAlpha: {},\n encoders: {},\n decoders: {},\n class: {},\n constants: {}\n };\n function addToConfig(newConfig) {\n Object.entries(newConfig).forEach(_ref => {\n let [key, value] = _ref;\n jimpConfig[key] = {\n ...jimpConfig[key],\n ...value\n };\n });\n }\n function addImageType(typeModule) {\n const type = typeModule();\n if (Array.isArray(type.mime)) {\n addType(...type.mime);\n } else {\n Object.entries(type.mime).forEach(mimeType => addType(...mimeType));\n }\n delete type.mime;\n addToConfig(type);\n }\n function addPlugin(pluginModule) {\n const plugin = pluginModule(jimpEvChange) || {};\n if (!plugin.class && !plugin.constants) {\n // Default to class function\n addToConfig({\n class: plugin\n });\n } else {\n addToConfig(plugin);\n }\n }\n if (configuration.types) {\n configuration.types.forEach(addImageType);\n jimpInstance.decoders = {\n ...jimpInstance.decoders,\n ...jimpConfig.decoders\n };\n jimpInstance.encoders = {\n ...jimpInstance.encoders,\n ...jimpConfig.encoders\n };\n jimpInstance.hasAlpha = {\n ...jimpInstance.hasAlpha,\n ...jimpConfig.hasAlpha\n };\n }\n if (configuration.plugins) {\n configuration.plugins.forEach(addPlugin);\n }\n addJimpMethods(jimpConfig.class, jimpInstance);\n addConstants(jimpConfig.constants, jimpInstance);\n return Jimp;\n}\n//# sourceMappingURL=index.js.map","import configure from \"@jimp/custom\";\n\nimport types from \"@jimp/types\";\nimport plugins from \"@jimp/plugins\";\n\nexport default configure({\n types: [types],\n plugins: [plugins],\n});\n","import { mergeDeep } from \"timm\";\nimport jpeg from \"@jimp/jpeg\";\nimport png from \"@jimp/png\";\nimport bmp from \"@jimp/bmp\";\nimport tiff from \"@jimp/tiff\";\nimport gif from \"@jimp/gif\";\nexport default (() => mergeDeep(jpeg(), png(), bmp(), tiff(), gif()));\n//# sourceMappingURL=index.js.map"],"names":["Converter","anyBase","srcAlphabet","dstAlphabet","converter","number","convert","BIN","OCT","DEC","HEX","module","exports","length","Error","this","prototype","i","divide","newlen","numberMap","fromBase","toBase","result","isValid","indexOf","parseInt","slice","concat","byteLength","b64","lens","getLens","validLen","placeHoldersLen","toByteArray","tmp","arr","Arr","_byteLength","curByte","len","revLookup","charCodeAt","fromByteArray","uint8","extraBytes","parts","maxChunkLength","len2","push","encodeChunk","lookup","join","Uint8Array","Array","code","start","end","num","output","encode","decode","BmpDecoder","buffer","is_with_alpha","pos","bottom_up","flag","toString","parseHeader","parseRGBA","fileSize","readUInt32LE","reserved","offset","headerSize","width","height","readInt32LE","planes","readUInt16LE","bitPP","compress","rawSize","hr","vr","colors","importantColors","palette","blue","readUInt8","green","red","quad","bitn","data","Buffer","bit1","xlen","Math","ceil","mode","y","line","x","b","location","rgb","bit4","fill","lines","low_nibble","a","c","setPixelData","call","rgbIndex","before","after","bit8","bit15","dif_w","_1_5","B","alpha","bit16","maskRed","maskGreen","maskBlue","mask0","ns","bit24","bit32","getData","bmpData","BmpEncoder","imgData","rgbSize","headerInfoSize","tempBuffer","write","writeUInt32LE","writeInt32LE","writeUInt16LE","rowBytes","p","fillOffset","quality","isBuffer","equals","base64","ieee754","K_MAX_LENGTH","createBuffer","RangeError","buf","__proto__","arg","encodingOrOffset","TypeError","allocUnsafe","from","value","string","encoding","isEncoding","actual","fromString","ArrayBuffer","isView","fromArrayLike","isInstance","array","byteOffset","undefined","fromArrayBuffer","valueOf","obj","checked","copy","numberIsNaN","type","isArray","fromObject","Symbol","toPrimitive","assertSize","size","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","m","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","String","read","readUInt16BE","foundIndex","found","j","hexWrite","Number","remaining","strLen","parsed","substr","utf8Write","blitBuffer","asciiWrite","str","byteArray","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","min","res","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","MAX_ARGUMENTS_LENGTH","fromCharCode","apply","decodeCodePointsArray","TYPED_ARRAY_SUPPORT","foo","e","typedArraySupport","console","error","Object","defineProperty","enumerable","get","species","configurable","writable","poolSize","alloc","allocUnsafeSlow","_isBuffer","compare","list","swap16","swap32","swap64","toLocaleString","inspect","max","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","includes","isFinite","toJSON","_arr","ret","out","bytes","checkOffset","ext","checkInt","checkIEEE754","writeFloat","littleEndian","noAssert","writeDouble","newBuf","subarray","readUIntLE","mul","readUIntBE","readUInt32BE","readIntLE","pow","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16BE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","set","INVALID_BASE64_RE","Infinity","leadSurrogate","split","base64clean","src","dst","constructor","name","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","d","s","NaN","rt","abs","isNaN","floor","log","LN2","ReflectOwnKeys","R","Reflect","ReflectApply","receiver","args","Function","ownKeys","getOwnPropertySymbols","getOwnPropertyNames","NumberIsNaN","EventEmitter","init","once","emitter","Promise","resolve","reject","errorListener","err","removeListener","resolver","eventTargetAgnosticAddListener","handler","flags","on","addErrorHandlerIfEventEmitter","_events","_eventsCount","_maxListeners","defaultMaxListeners","checkListener","listener","_getMaxListeners","that","_addListener","prepend","events","existing","warning","create","newListener","emit","unshift","warned","w","count","warn","onceWrapper","fired","wrapFn","_onceWrap","state","wrapped","bind","_listeners","unwrap","evlistener","unwrapListeners","arrayClone","listenerCount","addEventListener","wrapListener","removeEventListener","getPrototypeOf","setMaxListeners","getMaxListeners","doError","er","message","context","listeners","addListener","prependListener","prependOnceListener","position","originalListener","shift","index","pop","spliceOne","off","removeAllListeners","key","keys","rawListeners","eventNames","Parser","global","eval","DOMBufferStream","NodeBufferStream","BufferStream","bigEndian","endPosition","setBigEndian","nextUInt8","nextInt8","nextUInt16","nextUInt32","nextInt16","nextInt32","nextFloat","nextDouble","nextBuffer","remainingLength","nextString","mark","self","openWithOffset","offsetFrom","marker","skip","amount","branch","parseNumber","hours","minutes","parseDateTimeParts","dateParts","timeParts","map","year","month","day","seconds","Date","UTC","parseDateWithTimezoneFormat","dateTimeStr","timezoneParts","timezoneOffset","timestamp","parseDateWithSpecFormat","parseExifDate","isSpecFormat","charAt","arrayBuffer","parentOffset","view","DataView","getUint8","getInt8","getUint16","getUint32","getInt16","getInt32","getFloat32","getFloat64","getParentOffset","exif","gps","readExifValue","format","stream","readExifTag","tiffMarker","values","tagType","bytesPerComponent","getBytesPerComponent","components","valueBytes","lastNull","readIFDSection","iterator","tag","numberOfEntries","IFD0","IFD1","GPSIFD","SubIFD","InteropIFD","parseTags","subIfdOffset","gpsOffset","interopOffset","tiffHeader","readHeader","ifd0Stream","ifd1Offset","ifd1Stream","gpsStream","subIfdStream","interopStream","parseSections","markerType","getSizeFromSOFSection","getSectionName","nameStruct","jpeg","simplify","ExifResult","startMarker","tags","imageSize","thumbnailOffset","thumbnailLength","thumbnailType","app1Offset","readBinaryTags","resolveTagNames","simplifyValues","hidePointers","returnTags","hasThumbnail","mime","getThumbnailOffset","getThumbnailLength","getThumbnailBuffer","_getThumbnailStream","getImageSize","getThumbnailSize","sectionType","sectionStream","enableBinaryFields","enable","enablePointers","enableTagNames","enableImageSize","enableReturnTags","enableSimpleValues","parse","tagNames","getTagValue","setTagValue","t","section","sectionOffset","ifdSection","simplifyValue","hasOwnProperty","castDegreeValues","castDateValues","date","degreeTags","refType","refName","posVal","dateTags","forEach","degreeVal","degreeNumRef","degree","dateStrVal","Token","strtok3","supported","minimumBytes","async","fromStream","tokenizer","fromTokenizer","close","fromBuffer","input","_check","headers","options","header","entries","mask","_fromTokenizer","EndOfStreamError","check","checkString","stringToBytes","fileInfo","MAX_SAFE_INTEGER","peekBuffer","mayBeLess","ignore","id3HeaderLen","readToken","uint32SyncSafeToken","readBuffer","zipHeader","compressedSize","uncompressedSize","filenameLength","extraFieldLength","filename","StringType","endsWith","startsWith","nextHeaderIndex","brandMajor","maxBufferSize","readField","msb","peekNumber","UINT8","ic","id","readElement","lenField","nrLen","readChildren","level","children","re","readChunkHeader","INT32_BE","chunk","guid","UINT64_LE","payload","typeId","jsonSize","JSON","files","_","tarHeaderChecksumMatches","readableStream","pass","PassThrough","outputStream","pipeline","pipe","fileType","Set","extensions","mimeTypes","core","fromFile","path","assign","character","readSum","sum","isCallable","toStr","forEachArray","forEachString","forEachObject","object","k","thisArg","GifReaderLZWOutputIndexStream","code_stream","output_length","min_code_size","clear_code","eoi_code","next_code","cur_code_size","code_mask","cur_shift","cur","op","subblock_size","code_table","Int32Array","prev_code","chase_code","chase_length","chase","GifWriter","gopts","loop_count","loop","global_palette","check_palette_and_num_colors","num_colors","gp_num_colors_pow2","background","gp_num_colors","il","ended","addFrame","h","indexed_pixels","opts","using_local_palette","delay","disposal","use_transparency","transparent_index","transparent","index_stream","cur_subblock","emit_bytes_to_buffer","bit_block_size","emit_code","ib_code","cur_key","cur_code","GifWriterOutputLZWCodeStream","getOutputBuffer","setOutputBuffer","v","getOutputBufferPosition","setOutputBufferPosition","GifReader","pf0","global_palette_flag","num_global_colors","global_palette_offset","global_palette_size","no_eof","frames","block_size","pf1","pf2","interlace_flag","num_local_colors","palette_offset","palette_size","has_local_palette","data_offset","data_length","interlaced","numFrames","loopCount","frameInfo","frame_num","decodeAndBlitFrameBGRA","pixels","frame","num_pixels","trans","framewidth","framestride","xleft","opbeg","opend","scanstride","interlaceskip","r","g","decodeAndBlitFrameRGBA","BitmapImage","firstArg","sourceBitmap","bitmap","thirdArg","fillRGBA","blit","toImage","toX","toY","fromX","fromY","fromWidth","fromHeight","Erro","sourceBuf","targetBuf","sourceByteWidth","targetByteWidth","copyByteWidth","si","ti","rgba","bufByteWidth","bi","getRGBA","getRGBASet","rgbaSet","add","greyscale","scan","idx","grey","round","reframe","xOffset","yOffset","cropX","cropY","cropWidth","cropHeight","newX","newY","image","GifError","scale","factor","isInteger","sourceWidth","sourceHeight","destByteWidth","destBuf","priorDestRowIndex","sourceIndex","destIndex","color","cx","cy","scanAllCoords","scanHandler","bufferLength","scanAllIndexes","Gif","spec","loops","usesTransparency","colorScope","GlobalColorsPreferred","GlobalColorsOnly","LocalColorsOnly","messageOrError","super","stack","Omggif","GifUtil","GifFrame","PER_FRAME_OVERHEAD","_colorLookupLinear","_colorLookupBinary","mid","_extendPaletteToPowerOf2","colorCount","powerOf2","_getFrameSizeEst","pixelBitWidth","_getPixelBitWidth","indexCount","_writeFrame","gifWriter","frameIndex","isLocalPalette","colorToIndexFunc","colorBuffer","indexBuffer","transparentIndex","_getIndexedImage","delayCentisecs","disposalMethod","endOfFrame","startOfFrame","tryAgain","biggerBuffer","GifCodec","_transparentRGB","transparentRGB","_transparentRGBA","_testInitialBufferSize","decodeGif","reader","frameCount","_decodeFrame","encodeGif","dims","getMaxDimensions","maxWidth","maxHeight","_encodeGif","alreadyUsedTransparency","info","ii","colorInfo","getColorInfo","localPalettes","palettes","bufferSizeEst","_encodeLocal","globalPalette","extendedGlobalPalette","_encodeGlobal","_getSizeEstimateGlobal","sizeEst","PER_GIF_OVERHEAD","_getSizeEstimateLocal","source","lastArg","DisposeToBackgroundColor","getPalette","colorSet","iter","next","sort","DisposeToAnything","DisposeNothing","DisposeToPrevious","fs","ImageQ","INVALID_SUFFIXES","defaultCodec","_quantize","imageOrImages","method","maxColorIndexes","modifier","dither","images","ditherAlgorithm","serpentine","minimumColorDistanceToDither","calculateErrorLikeGIMP","distCalculator","distance","Euclidean","quantizer","imageMaker","ErrorDiffusionArray","ErrorDiffusionArrayKernel","NearestColor","inputContainers","imageBuf","inputBuf","inputArray","Uint32Array","ai","inputContainer","utils","PointContainer","fromUint32Array","sample","limitedPalette","quantizeSync","outputArray","toUint32Array","cloneFrames","clones","maxGlobalIndex","globalColorSet","copyAsJimp","jimp","bitmapImageToCopy","shareAsJimp","quantizeDekker","quantizeSorokin","histogram","histogramID","quantizeWu","significantBits","decoder","readFile","then","bitmapImageToShare","jimpImage","encoder","matches","match","gif","writeFile","_writeBinary","win","window","fnToStr","constructorRegex","isES6ClassFn","fnStr","test","hasToStringTag","toStringTag","tryFunctionObject","strClass","fn","setTimeout","alert","confirm","prompt","fetch","JpegImage","dctZigZag","dctCos1","dctSin1","dctCos3","dctSin3","dctCos6","dctSin6","dctSqrt2","dctSqrt1d2","buildHuffmanTable","codeLengths","q","decodeScan","resetInterval","spectralStart","spectralEnd","successivePrev","successive","precision","samplesPerLine","scanLines","mcusPerLine","progressive","startOffset","maxH","maxV","bitsData","bitsCount","readBit","nextByte","decodeHuffman","tree","bit","node","receive","receiveAndExtend","successiveACNextValue","eobrun","successiveACState","decodeMcu","component","mcu","row","col","mcuCol","blockRow","blockCol","blocks","tolerantDecoding","decodeBlock","blocksPerLine","decodeFn","componentsLength","zz","huffmanTableDC","diff","pred","rs","huffmanTableAC","z","direction","mcuExpected","blocksPerColumn","mcusPerColumn","buildComponentData","quantizeAndInverse","dataOut","dataIn","v0","v1","v2","v3","v4","v5","v6","v7","qt","quantizationTable","requestMemoryAllocation","scanLine","clampTo8bit","load","xhr","XMLHttpRequest","open","responseType","onload","response","mozResponseArrayBuffer","send","maxResolutionInPixels","maxResolutionInMP","readUint16","prepareComponents","componentId","blocksPerLineForMcu","blocksPerColumnForMcu","jfif","adobe","quantizationTables","huffmanTablesAC","huffmanTablesDC","fileMarker","malformedDataOffset","comments","appData","comment","version","major","minor","densityUnits","xDensity","yDensity","thumbWidth","thumbHeight","thumbData","exifBuffer","flags0","flags1","transformCode","quantizationTablesEnd","quantizationTableSpec","tableData","extended","componentsOrder","pixelsInFrame","exceededAmount","componentsCount","qId","quantizationIdx","huffmanLength","huffmanTableSpec","codeLengthSum","huffmanValues","selectorsCount","tableSpec","successiveApproximation","processed","nextOffset","cp","scaleX","scaleY","component1","component2","component3","component4","component1Line","component2Line","component3Line","component4Line","Y","Cb","Cr","K","C","M","Ye","G","colorTransform","dataLength","copyToImageData","imageData","formatAsRGBA","imageDataArray","totalBytesAllocated","maxMemoryUsageBytes","increaseAmount","totalMemoryImpactBytes","resetMaxMemoryUsage","maxMemoryUsageBytes_","getBytesAllocated","jpegData","userOpts","useTArray","maxMemoryUsageInMB","channels","bytesNeeded","ReferenceError","JPEGEncoder","YDC_HT","UVDC_HT","YAC_HT","UVAC_HT","currentQuality","ffloor","YTable","UVTable","fdtbl_Y","fdtbl_UV","bitcode","category","outputfDCTQuant","DU","byteout","bytenew","bytepos","YDU","UDU","VDU","clt","RGB_YUV_TABLE","ZigZag","std_dc_luminance_nrcodes","std_dc_luminance_values","std_ac_luminance_nrcodes","std_ac_luminance_values","std_dc_chrominance_nrcodes","std_dc_chrominance_values","std_ac_chrominance_nrcodes","std_ac_chrominance_values","computeHuffmanTbl","nrcodes","std_table","codevalue","pos_in_table","HT","writeBits","bs","posval","writeByte","writeWord","processDU","CDU","fdtbl","DC","HTDC","HTAC","EOB","M16zeroes","DU_DCT","d0","d1","d2","d3","d4","d5","d6","d7","fDCTQuant","dataOff","tmp0","tmp7","tmp1","tmp6","tmp2","tmp5","tmp3","tmp4","tmp10","tmp13","tmp11","tmp12","z1","z5","z2","z4","z3","z11","z13","tmp0p2","tmp7p2","tmp1p2","tmp6p2","tmp2p2","tmp5p2","tmp3p2","tmp4p2","tmp10p2","tmp13p2","tmp11p2","tmp12p2","z1p2","z5p2","z2p2","z4p2","z3p2","z11p2","z13p2","Diff","end0pos","lng","startpos","nrzeroes","nrmarker","setQuality","sf","YQT","UVQT","u","aasf","initQuantTables","getTime","l","writeAPP1","writeDQT","writeSOF0","o","writeDHT","DCY","DCU","DCV","displayName","quadWidth","fillbits","sfcc","initCharLookupTable","nrlower","nrupper","cat","nr","nrneg","initCategoryNumber","initRGBYUVTable","qu","noop","parseASCII","parseXML","readBinary","isBinaryFormat","xtend","xml2","opt","cb","uri","binary","req","overrideMimeType","getBinaryOpts","body","statusCode","equal","HEADER","substring","pako","zlib_deflate","strings","msg","ZStream","Z_OK","Z_DEFAULT_COMPRESSION","Z_DEFAULT_STRATEGY","Z_DEFLATED","Deflate","chunkSize","windowBits","memLevel","strategy","to","raw","gzip","chunks","strm","avail_out","status","deflateInit2","deflateSetHeader","dictionary","dict","string2buf","deflateSetDictionary","_dict_set","deflate","deflator","_mode","next_in","avail_in","Buf8","next_out","onEnd","onData","buf2binstring","shrinkBuf","deflateEnd","flattenChunks","deflateRaw","zlib_inflate","GZheader","Inflate","inflateInit2","inflateGetHeader","inflateSetDictionary","inflate","inflator","next_out_utf8","tail","utf8str","allowBufError","Z_FINISH","Z_NO_FLUSH","binstring2buf","Z_NEED_DICT","Z_BUF_ERROR","Z_STREAM_END","Z_SYNC_FLUSH","utf8border","buf2string","arraySet","inflateEnd","inflateRaw","ungzip","TYPED_OK","Uint16Array","_has","sources","fnTyped","dest","src_offs","dest_offs","fnUntyped","setTyped","Buf16","Buf32","STR_APPLY_OK","STR_APPLY_UIA_OK","__","_utf8len","c2","m_pos","str_len","buf_len","c_len","utf16buf","adler","s1","s2","Z_PARTIAL_FLUSH","Z_FULL_FLUSH","Z_BLOCK","Z_TREES","Z_ERRNO","Z_STREAM_ERROR","Z_DATA_ERROR","Z_NO_COMPRESSION","Z_BEST_SPEED","Z_BEST_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_BINARY","Z_TEXT","Z_UNKNOWN","crcTable","table","makeTable","crc","configuration_table","trees","adler32","crc32","MAX_MEM_LEVEL","L_CODES","LITERALS","D_CODES","BL_CODES","HEAP_SIZE","MAX_BITS","MIN_MATCH","MAX_MATCH","MIN_LOOKAHEAD","INIT_STATE","HCRC_STATE","BUSY_STATE","FINISH_STATE","BS_NEED_MORE","BS_BLOCK_DONE","BS_FINISH_STARTED","BS_FINISH_DONE","errorCode","rank","f","zero","flush_pending","pending","pending_buf","pending_out","total_out","flush_block_only","last","_tr_flush_block","block_start","strstart","put_byte","putShortMSB","longest_match","cur_match","chain_length","max_chain_length","best_len","prev_length","nice_match","w_size","_win","wmask","w_mask","prev","strend","scan_end1","scan_end","good_match","lookahead","match_start","fill_window","more","_w_size","window_size","hash_size","head","wrap","total_in","insert","ins_h","hash_shift","hash_mask","deflate_fast","flush","hash_head","bflush","match_length","_tr_tally","max_lazy_match","last_lit","deflate_slow","max_insert","prev_match","match_available","Config","good_length","max_lazy","nice_length","max_chain","func","DeflateState","pending_buf_size","gzhead","gzindex","last_flush","w_bits","hash_bits","dyn_ltree","dyn_dtree","bl_tree","l_desc","d_desc","bl_desc","bl_count","heap","heap_len","heap_max","depth","l_buf","lit_bufsize","d_buf","opt_len","static_len","bi_buf","bi_valid","deflateResetKeep","data_type","_tr_init","deflateReset","max_block_size","max_start","deflateInit","old_flush","beg","text","hcrc","extra","time","os","bstate","deflate_huff","deflate_rle","_tr_align","_tr_stored_block","avail","tmpDict","dictLength","deflateInfo","xflags","extra_len","done","_in","_out","dmax","wsize","whave","wnext","s_window","hold","bits","lcode","dcode","lmask","dmask","here","dist","from_source","lencode","distcode","lenbits","distbits","top","dolen","dodist","sane","inflate_fast","inflate_table","LENS","DISTS","HEAD","TYPE","BAD","ENOUGH_LENS","ENOUGH_DISTS","zswap32","InflateState","havedict","total","wbits","ncode","nlen","ndist","have","work","lendyn","distdyn","back","was","inflateResetKeep","inflateReset","inflateReset2","lenfix","distfix","virgin","fixedtables","sym","updatewindow","inflateInit","put","left","here_bits","here_op","here_val","last_bits","last_op","last_val","hbuf","order","inf_leave","inflateInfo","lbase","lext","dbase","dext","lens_index","codes","table_index","incr","low","root","curr","drop","used","huff","base","base_index","MAXBITS","offs","extra_index","STORED_BLOCK","Buf_size","END_BLOCK","REP_3_6","REPZ_3_10","REPZ_11_138","extra_lbits","extra_dbits","extra_blbits","bl_order","static_ltree","static_dtree","_dist_code","_length_code","base_length","static_l_desc","static_d_desc","static_bl_desc","base_dist","StaticTreeDesc","static_tree","extra_bits","extra_base","elems","max_length","has_stree","TreeDesc","dyn_tree","stat_desc","max_code","d_code","put_short","send_bits","send_code","bi_reverse","gen_codes","init_block","bi_windup","smaller","_n2","_m2","pqdownheap","compress_block","ltree","dtree","lc","lx","build_tree","desc","stree","xbits","overflow","gen_bitlen","scan_tree","curlen","prevlen","nextlen","max_count","min_count","send_tree","static_init_done","stored_len","copy_block","LENGTH_CODES","tr_static_init","opt_lenb","static_lenb","max_blindex","black_mask","detect_data_type","build_bl_tree","lcodes","dcodes","blcodes","send_all_trees","STATIC_TREES","bi_flush","splitLine","space","dt","parseData","parseIntList","pages","chars","kernings","lineData","file","readBlock","blockID","blockSize","bitField","smooth","unicode","italic","bold","fixedHeight","charset","stretchH","aa","padding","spacing","outline","face","readNameNT","readStringNT","readInfo","common","lineHeight","scaleW","scaleH","packed","alphaChnl","redChnl","greenChnl","blueChnl","readCommon","readPages","char","xoffset","yoffset","xadvance","page","chnl","readChars","kern","first","second","readKernings","every","byte","parseAttributes","parseFromString","NAME_MAP","scaleh","scalew","stretchh","lineheight","alphachnl","redchnl","greenchnl","bluechnl","getAttribs","element","attribs","attributes","getAttribList","reduce","attrib","nodeName","nodeValue","xmlRoot","getElementsByTagName","pageRoot","getAttribute","childTag","child","GLYPH_DESIGNER_ERROR","assertPath","stringify","normalizeStringPosix","allowAboveRoot","lastSegmentLength","lastSlash","dots","lastSlashIndex","posix","cwd","resolvedPath","resolvedAbsolute","process","normalize","isAbsolute","trailingSeparator","joined","relative","fromStart","fromEnd","fromLen","toStart","toLen","lastCommonSep","fromCode","_makeLong","dirname","hasRoot","matchedSlash","basename","extIdx","firstNonSlashEnd","extname","startDot","startPart","preDotState","pathObject","sep","_format","delimiter","win32","Deferred","promise","defaultMessages","StreamReader","EndOfFileStream_1","Deferred_1","EndOfFileStream_2","deferred","endOfStream","peekQueue","uint8Array","bytesRead","peekData","lenCopy","reqLen","chunkLen","readFromStream","request","readDeferred","StreamReader_1","antialiased","img","x1","y1","img2","minX","minY","maxX","maxY","x0","y0","x2","y2","zeroes","positives","negatives","delta","colorDelta","img1","yOnly","a1","a2","r1","blend","g1","b1","r2","g2","b2","rgb2y","rgb2i","rgb2q","drawPixel","threshold","maxDelta","includeAA","require","interlaceUtils","pixelBppMapper","pxData","pxPos","rawPos","pixel","pixelBppCustomMapper","pixelData","maxBit","mapImage8Bit","getPxPos","bpp","imageWidth","imageHeight","imagePass","mapImageCustomBit","resetAfterLine","dataToBitMap","bitmapInfo","interlace","leftOver","byte8","byte7","byte6","byte5","byte4","byte3","byte2","byte1","returner","bitRetriever","getImagePasses","getInterlaceIterator","nonInterlacedPxPos","imageIndex","constants","outHasAlpha","COLORTYPE_COLOR_ALPHA","COLORTYPE_ALPHA","colorType","inputColorType","setInt16","Int16Array","bitDepth","maxValue","inBpp","COLORTYPE_TO_BPP_MAP","inputHasAlpha","outBpp","outData","inIndex","outIndex","bgColor","COLORTYPE_COLOR","COLORTYPE_GRAYSCALE","grayscale","util","Stream","ChunkStream","_buffers","_buffered","_reads","_paused","_encoding","inherits","callback","allowLess","nextTick","_process","dataBuffer","_end","destroySoon","destroy","_processReadAllowingLess","smallerBuf","_processRead","splice","ex","PNG_SIGNATURE","TYPE_IHDR","TYPE_IEND","TYPE_IDAT","TYPE_PLTE","TYPE_tRNS","TYPE_gAMA","COLORTYPE_PALETTE","COLORTYPE_PALETTE_COLOR","GAMMA_DIVISION","currentCrc","CrcCalculator","_crc","paethPredictor","filters","byteWidth","rawData","up","upleft","filterSums","filterTypes","filterType","sel","Filter","FilterAsync","buffers","_filter","complete","SyncReader","inBuffer","outBuffers","bufferPart","getByteWidth","dependencies","_imageIndex","_images","passes","lineIndex","_xComparison","_reverseFilterLine","_unFilterType1","unfilteredLine","xComparison","xBiggerThan","rawByte","f1Left","_unFilterType2","lastLine","_lastLine","f2Up","_unFilterType3","f3Up","f3Left","f3Add","_unFilterType4","f4Up","f4Left","f4UpLeft","f4Add","filter","currentImage","indata","skipRescale","transColor","outdata","dePalette","makeTrans","replaceTransparentColor","maxInSample","scaleDepth","imagePasses","xLeftOver","yLeftOver","xRepeats","yRepeats","passWidth","passHeight","outerXLeftOver","outerX","outerYLeftOver","Packer","PackerAsync","_packer","_deflate","createDeflate","readable","pack","gamma","packIHDR","packGAMA","filteredData","filterData","compressedData","packIDAT","packIEND","hasSyncZlib","zlib","deflateSync","metaData","packer","getDeflateOptions","CrcStream","bitPacker","_options","deflateChunkSize","deflateLevel","deflateStrategy","deflateFactory","packedData","_packChunk","above","upLeft","paeth","pLeft","pAbove","pUpLeft","bitmapper","formatNormaliser","ParserAsync","_parser","_handleError","metadata","_handleMetaData","_handlePalette","_handleTransColor","finished","_finished","inflateData","_inflateData","simpleTransparency","_simpleTransparency","headersFinished","_headersFinished","_inflate","errord","_bitmapInfo","createInflate","_complete","Z_MIN_CHUNK","leftToInflate","emitError","filterWrite","_metaData","normalisedBitmapData","bitmapData","inflateSync","FilterSync","inflateDataList","_err_","_metaData_","_gamma_","inflatedData","maxLength","unfilteredData","checkCRC","_hasIHDR","_hasIEND","_emittedHeadersFinished","_palette","_colorType","_chunks","_handleIHDR","_handleIEND","_handleIDAT","_handlePLTE","_handleTRNS","_handleGAMA","_parseSignature","signature","_parseChunkBegin","ancillary","Boolean","_skipChunk","_handleChunkEnd","_parseChunkEnd","fileCrc","calcCrc","_parseIHDR","compr","_parsePLTE","_parseTRNS","_parseGAMA","_parseIDAT","leftOverLength","_parseIEND","png","PNGSync","PNG","_handleClose","_metadata","_gamma","sync","onParsed","onError","parsedData","bitblt","srcX","srcY","deltaX","deltaY","adjustGamma","assert","ok","kMaxLength","_offset","_outOffset","_buffer","_outBuffer","_maxLength","_close","engine","_handle","flushFlag","_finishFlushFlag","_processChunk","zlibBufferSync","asyncCb","availInBefore","availOutBefore","_chunkSize","inOff","nread","handleChunk","availInAfter","availOutAfter","_hadError","writeSync","_writeState","hasOwn","pSlice","functionsHaveNames","pToString","arrbuf","regex","getName","isFunction","truncate","something","rawname","fail","expected","operator","stackStartFunction","AssertionError","_deepEqual","strict","memos","isDate","isRegExp","multiline","lastIndex","ignoreCase","Float32Array","Float64Array","actualIndex","actualVisitedObjects","isPrimitive","aIsArgs","isArguments","bIsArgs","ka","objectKeys","kb","objEquiv","expectedException","isPrototypeOf","_throws","shouldThrow","block","_tryBlock","userProvidedMessage","isUnexpectedException","isError","generatedMessage","getMessage","captureStackTrace","fn_name","next_line","notEqual","deepEqual","deepStrictEqual","notDeepEqual","notDeepStrictEqual","strictEqual","notStrictEqual","throws","doesNotThrow","ifError","ctor","superCtor","super_","TempCtor","formatRegExp","isString","objects","isNull","isObject","deprecate","isUndefined","noDeprecation","throwDeprecation","traceDeprecation","trace","debugEnviron","debugs","ctx","seen","stylize","stylizeNoColor","isBoolean","showHidden","_extend","customInspect","stylizeWithColor","formatValue","styleType","style","styles","recurseTimes","primitive","simple","isNumber","formatPrimitive","visibleKeys","hash","arrayToHash","formatError","RegExp","braces","toUTCString","formatProperty","formatArray","reduceToSingleString","getOwnPropertyDescriptor","ar","objectToString","pad","debuglog","env","NODE_DEBUG","toUpperCase","pid","isNullOrUndefined","isSymbol","months","prop","getHours","getMinutes","getSeconds","getDate","getMonth","origin","typedArray","Zstream","NONE","DEFLATE","INFLATE","GZIP","GUNZIP","DEFLATERAW","INFLATERAW","UNZIP","Zlib","init_done","write_in_progress","pending_close","gzip_id_bytes_read","in_off","in_len","out_off","out_len","_write","_checkError","_afterSync","_after","next_expected_header_byte","reset","_error","onerror","_init","_setDictionary","params","_reset","Transform","binding","kRangeErrorMessage","Z_MIN_WINDOWBITS","Z_MAX_WINDOWBITS","Z_DEFAULT_WINDOWBITS","Z_MAX_CHUNK","Z_DEFAULT_CHUNK","Z_MIN_MEMLEVEL","Z_MAX_MEMLEVEL","Z_DEFAULT_MEMLEVEL","Z_MIN_LEVEL","Z_MAX_LEVEL","Z_DEFAULT_LEVEL","bkeys","bk","bkey","Z_MEM_ERROR","Z_VERSION_ERROR","ckeys","ck","ckey","zlibBuffer","flow","Gzip","Gunzip","DeflateRaw","InflateRaw","Unzip","isValidFlushFlag","_this","_opts","finishFlush","_flushFlag","errno","_level","_strategy","emitCloseNT","freeze","createDeflateRaw","createInflateRaw","createGzip","createGunzip","createUnzip","gzipSync","deflateRawSync","unzip","unzipSync","gunzip","gunzipSync","inflateRawSync","_flush","_transform","kind","_this2","ws","_writableState","ending","needDrain","newReq","SlowBuffer","INSPECT_MAX_BYTES","$TypeError","$gOPD","throwTypeError","ThrowTypeError","calleeThrows","gOPDthrows","hasSymbols","getProto","generatorFunction","asyncFunction","asyncGenFunction","asyncGenIterator","TypedArray","INTRINSICS","asyncIterator","Atomics","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","EvalError","Int8Array","Map","parseFloat","all","Proxy","SharedArrayBuffer","SyntaxError","Uint8ClampedArray","URIError","WeakMap","WeakSet","$replace","rePropName","reEscapeChar","stringToPath","quote","subString","getBaseIntrinsic","allowMissing","$Function","GetIntrinsic","$apply","$call","callBind","$indexOf","intrinsic","eventListener","ERROR_MESSAGE","funcType","bound","boundLength","boundArgs","Empty","implementation","origSymbol","hasSymbolSham","symObj","syms","propertyIsEnumerable","descriptor","isStandardArguments","isLegacyArguments","callee","supportsStandardArguments","isFnRegex","generatorFunc","getGeneratorFunc","GeneratorFunction","availableTypedArrays","callBound","$toString","typedArrays","$slice","toStrTags","gOPD","proto","superProto","anyTrue","getter","tryTypedArrays","MAX_WBITS","DEF_MEM_LEVEL","PRESET_DICT","EXTRA_STATE","NAME_STATE","COMMENT_STATE","OS_CODE","CODES","FLAGS","TIME","OS","EXLEN","EXTRA","NAME","COMMENT","HCRC","DICTID","DICT","TYPEDO","STORED","COPY_","COPY","TABLE","LENLENS","CODELENS","LEN_","LEN","LENEXT","DIST","DISTEXT","MATCH","LIT","CHECK","LENGTH","DONE","MEM","DEF_WBITS","DYN_TREES","MAX_BL_BITS","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","timeout","run","runClearTimeout","Item","title","browser","argv","versions","chdir","umask","EE","Readable","Writable","Duplex","ondata","pause","ondrain","resume","_isStdio","onend","onclose","didOnEnd","cleanup","createErrorType","Base","NodeError","_Base","arg1","arg2","arg3","superClass","subClass","oneOf","thing","determiner","search","this_len","allowHalfOpen","onEndNT","highWaterMark","getBuffer","_readableState","destroyed","ReadableState","EElistenerCount","OurUint8Array","debug","debugUtil","StringDecoder","createReadableStreamAsyncIterator","BufferList","destroyImpl","getHighWaterMark","_require$codes","ERR_INVALID_ARG_TYPE","ERR_STREAM_PUSH_AFTER_EOF","ERR_METHOD_NOT_IMPLEMENTED","ERR_STREAM_UNSHIFT_AFTER_END_EVENT","errorOrDestroy","kProxyEvents","isDuplex","objectMode","readableObjectMode","pipes","pipesCount","flowing","endEmitted","reading","needReadable","emittedReadable","readableListening","resumeScheduled","paused","emitClose","autoDestroy","defaultEncoding","awaitDrain","readingMore","_read","_destroy","readableAddChunk","addToFront","skipChunkCheck","emitReadable","emitReadable_","onEofChunk","chunkInvalid","_uint8ArrayToBuffer","addChunk","maybeReadMore","_undestroy","undestroy","isPaused","setEncoding","enc","content","clear","MAX_HWM","howMuchToRead","computeNewHighWaterMark","maybeReadMore_","updateReadableListening","nReadingNextTick","resume_","fromList","consume","endReadable","endReadableNT","wState","xs","nOrig","doRead","pipeOpts","endFn","stdout","stderr","unpipe","onunpipe","unpipeInfo","hasUnpiped","onfinish","cleanedUp","pipeOnDrain","event","dests","ev","_fromList","iterable","ERR_MULTIPLE_CALLBACK","ERR_TRANSFORM_ALREADY_TRANSFORMING","ERR_TRANSFORM_WITH_LENGTH_0","afterTransform","ts","_transformState","transforming","writecb","writechunk","needTransform","writeencoding","transform","prefinish","err2","CorkedRequest","entry","finish","corkReq","pendingcb","corkedRequestsFree","onCorkedFinish","WritableState","internalUtil","realHasInstance","ERR_STREAM_CANNOT_PIPE","ERR_STREAM_DESTROYED","ERR_STREAM_NULL_VALUES","ERR_STREAM_WRITE_AFTER_END","ERR_UNKNOWN_ENCODING","nop","writableObjectMode","finalCalled","noDecode","decodeStrings","writing","corked","bufferProcessing","onwrite","writelen","onwriteStateUpdate","finishMaybe","errorEmitted","onwriteError","needFinish","bufferedRequest","clearBuffer","afterWrite","lastBufferedRequest","prefinished","bufferedRequestCount","writev","_writev","final","_final","writeOrBuffer","isBuf","newChunk","decodeChunk","doWrite","onwriteDrain","holder","allBuffers","callFinal","need","rState","current","hasInstance","writeAfterEnd","validChunk","cork","uncork","setDefaultEncoding","endWritable","_Object$setPrototypeO","_defineProperty","kLastResolve","kLastReject","kError","kEnded","kLastPromise","kHandlePromise","kStream","createIterResult","readAndResolve","onReadable","AsyncIteratorPrototype","ReadableStreamAsyncIteratorPrototype","setPrototypeOf","lastPromise","wrapForNext","_Object$create","enumerableOnly","symbols","_defineProperties","props","custom","instance","Constructor","_classCallCheck","protoProps","hasStrings","_getString","_getBuffer","nb","getOwnPropertyDescriptors","defineProperties","_objectSpread","staticProps","emitErrorAndCloseNT","emitErrorNT","readableDestroyed","writableDestroyed","ERR_STREAM_PREMATURE_CLOSE","eos","called","_len","_key","onlegacyfinish","writableEnded","readableEnded","onrequest","setHeader","abort","isRequest","ERR_MISSING_ARGS","streams","popCallback","destroys","closed","destroyer","ERR_INVALID_OPT_VALUE","duplexKey","hwm","highWaterMarkFrom","nenc","retried","_normalizeEncoding","normalizeEncoding","utf16Text","utf16End","fillLast","utf8FillLast","base64Text","base64End","simpleWrite","simpleEnd","lastNeed","lastTotal","lastChar","utf8CheckByte","utf8CheckExtraBytes","utf8CheckIncomplete","copyProps","SafeBuffer","config","localStorage","isArgumentsObject","isGeneratorFunction","whichTypedArray","isTypedArray","uncurryThis","BigIntSupported","BigInt","SymbolSupported","ObjectToString","numberValue","stringValue","booleanValue","bigIntValue","symbolValue","checkBoxedPrimitive","prototypeValueOf","isMapToString","isSetToString","isWeakMapToString","isWeakSetToString","isArrayBufferToString","isArrayBuffer","working","isDataViewToString","isDataView","isSharedArrayBufferToString","isSharedArrayBuffer","isNumberObject","isStringObject","isBooleanObject","isBigIntObject","isSymbolObject","isPromise","catch","isArrayBufferView","isUint8Array","isUint8ClampedArray","isUint16Array","isUint32Array","isInt8Array","isInt16Array","isInt32Array","isFloat32Array","isFloat64Array","isBigInt64Array","isBigUint64Array","isMap","isSet","isWeakMap","isWeakSet","isAsyncFunction","isMapIterator","isSetIterator","isGeneratorObject","isWebAssemblyCompiledModule","isBoxedPrimitive","isAnyArrayBuffer","descriptors","debugEnvRegex","debugEnv","types","isNativeError","kCustomPromisifiedSymbol","callbackifyOnRejected","reason","newReason","promisify","original","promiseResolve","promiseReject","callbackify","callbackified","maybeCb","rej","foundName","canSetImmediate","setImmediate","canPost","postMessage","stopPropagation","AbstractTokenizer","peek_readable_1","numBuffer","token","bytesLeft","normalizeOptions","BufferTokenizer","AbstractTokenizer_1","normOptions","bytes2read","FileTokenizer","fd","sourceFilePath","stat","isFile","writeFileSync","createReadStream","pathExists","existsSync","stats","ReadStreamTokenizer","streamReader","skipBytes","skipBuffer","peek","bufSize","totBytesRead","ReadStreamTokenizer_1","BufferTokenizer_1","FileTokenizer_1","core_1","_typeof","_len3","rest","_key3","doMerge","INVALID_ARGS","throwStr","getKeysAndSymbols","clone","fAddDefaults","fDeep","fChanged","nextVal","AnsiStringType","BufferType","Uint8ArrayType","IgnoreType","Float80_LE","Float80_BE","Float64_LE","Float64_BE","Float32_LE","Float32_BE","Float16_LE","Float16_BE","INT64_BE","UINT64_BE","INT64_LE","INT32_LE","INT24_BE","INT24_LE","INT16_LE","INT16_BE","INT8","UINT32_BE","UINT32_LE","UINT24_BE","UINT24_LE","UINT16_BE","UINT16_LE","dv","setUint8","setUint16","dataView","setUint32","setInt8","unsigned","setInt32","getBigUint64","setBigUint64","getBigInt64","setBigInt64","setFloat32","setFloat64","static","until","codePointToString","singleByteDecoder","bite","inRange","windows1252","right","UTIF","U","Z","V","N","O","D","L","main","W","ak","ac","ah","ao","ad","Q","a5","E","F","P","a7","a8","X","T","J","I","DNLMarkerError","EOIMarkerError","H","A","S","an","al","$","a0","ab","af","ap","ae","markerLoop","a4","a6","forceRGB","isSourcePDF","JpegDecoder","encodeImage","idf","prfx","ifds","bin","_binBE","writeUshort","ifdo","writeUint","noffs","_writeIFD","_types","basic","buff","prm","parseMN","readASCII","_binLE","readUshort","readUint","cnt","typ","_readIFD","decodeImage","bipp","cmpr","fo","bipl","soff","bcnt","bilen","tw","th","tx","ty","tbuff","_decompress","_copyTile","rps","tgt","toff","_decodeG2","_decodeG3","_decodeG4","_decodeLZW","_decodeOldJPEG","_decodeNewJPEG","_decodeVC5","_decodeARW","_decodePackBits","_decodeThunder","_decodeNikon","_decodeLogLuv32","bps","noc","bpl","roff","ntoff","nv","aj","now","readShort","aF","sign","az","aC","aq","aE","as","ay","at","aD","aB","av","a9","ag","qw","io","oo","_ljpeg_diff","getbithuff","_getbithuff","inp","src_length","raw_width","tiff_bps","imax","imin","sh","dp","pix","clr","_putsF","b0","tab","ljpeg_diff","lim","imgs","nikon_tree","make_decoder","_make_decoder","mn","exifIFD","makerNote","md","mdo","ver0","ver1","vpred","shl","step","csize","hpred","bti","nbits","_get_byte","bitbuf","vbits","tables","tlen","boff","LosslessJpegDecode","olen","rst","parser","decoded","_decodeOldJPEGInit","sosMarker","SOI","joff","isTiled","jpgIchgFmt","jifoff","jpgIchgFmtLen","jiflen","soffTag","ycbcrss","ssx","ssy","spp","jpgresint","jpegOffset","ooff","qtables","htables","nc","sofpos","tmptab","tmpoff","soslen","sosoff","sofPosition","dlen","buffoff","SOS","EOI","sa","ta","qoff","px","msk","_dmap","_lens","addKeys","i0","inc","termW","termB","makeW","makeB","makeA","lensW","lensB","slen","wrd","pline","_makeDiff","toRead","_findDiff","dl","_addNtimes","_writeBits","twoDim","is1D","ifd","repeat","voff","o0","ri","readInt","readFloat","readDouble","oarr","subfd","subIFD","gpsiIFD","dngPrvt","fujiIFD","subsub","knum","eoff","ki","writeASCII","wr","writeInt","nu","de","toRGBA8","scl","area","qarea","intp","qi","smpls","ndt","cn","mi","dof","gotAlpha","UDOC","cmykToRgb","sX","sY","replaceIMG","document","sufs","suff","_xhrs","_imgs","_imgLoaded","ind","setAttribute","bufferToURI","vsns","ma","cnv","createElement","getContext","imgd","ImageData","putImageData","toDataURL","nextZero","ui8","i16","i32","ui32","fl32","fl64","tb","xoff","yoff","xlim","ylim","tof","sof","a3","_decompressRAF","log2","globalThis","support","searchParams","blob","Blob","formData","viewClasses","normalizeName","normalizeValue","iteratorFor","items","Headers","append","consumed","bodyUsed","fileReaderReady","readBlobAsArrayBuffer","FileReader","readAsArrayBuffer","bufferClone","Body","_initBody","_bodyInit","_bodyText","_bodyBlob","FormData","_bodyFormData","URLSearchParams","_bodyArrayBuffer","rejected","readAsText","readArrayBufferAsText","json","oldValue","has","methods","Request","upcased","url","credentials","signal","referrer","cache","reParamSearch","form","Response","bodyInit","statusText","redirectStatuses","redirect","DOMException","aborted","abortXhr","rawHeaders","getAllResponseHeaders","responseURL","responseText","ontimeout","onabort","href","fixUrl","withCredentials","setRequestHeader","onreadystatechange","readyState","polyfill","parseHeaders","initParams","createXHR","_createXHR","getBody","responseXML","firefoxBugTakenEffect","documentElement","getXml","isJson","errorFunc","evt","timeoutTimer","failureResponse","loadFunc","useXDR","rawRequest","cors","XDomainRequest","onprogress","username","password","isEmpty","beforeSend","DOMParser","ActiveXObject","xmlDoc","loadXML","div","innerHTML","__defProp","__getOwnPropDesc","__getOwnPropNames","__hasOwnProp","__export","__toCommonJS","module2","temp","copyDefault","__reExport","__publicField","__defNormalProp","src_exports","applyPalette","applyPaletteSync","buildPalette","buildPaletteSync","constants_exports","conversion","conversion_exports","distance_exports","image_exports","palette_exports","quality_exports","utils_exports","bt709","bt709_exports","Y2","correctGamma","rgb2xyz","lab2rgb","lab2xyz","rgb2hsl","rgb2lab","xyz2lab","xyz2rgb","arithmetic_exports","degrees2radians","PI","max3","min3","intInRange","high","inRange0to255Rounded","inRange0to255","stableSort","arrayToSort","sorted","ord","ord2","refX","refY","refZ","pivot","xyz","refX2","refY2","refZ2","pivot2","correctGamma2","AbstractDistanceCalculator","AbstractEuclidean","AbstractManhattan","CIE94GraphicArts","CIE94Textiles","CIEDE2000","CMetric","EuclideanBT709","EuclideanBT709NoAlpha","Manhattan","ManhattanBT709","ManhattanNommyde","PNGQuant","_setDefaults","setWhitePoint","_whitePoint","_maxDistance","calculateRaw","calculateNormalized","colorA","colorB","AbstractCIE94","lab1","lab2","dL","dA","dB","c1","sqrt","dC","deltaH","dAlpha","_kA","_Kl","_K1","_K2","_CIEDE2000","hp","atan2","_deg360InRad","ahp","aCp","aCp_to_7","R_C","_pow25to7","delta_theta","_deg30InRad","exp","_deg275InRad","_deg25InRad","sin","cos","_deg6InRad","_deg63InRad","C1pC2p","h_bar","h1p","h2p","hpSum","_deg180InRad","dhp","dE2","calculateRawInLab","Lab1","Lab2","L1","L2","pow_a_C1_C2_to_7","a1p","a2p","C1p","C2p","_calculatehp","dLp","dCp","dHp","_calculate_dHp","_calculate_ahp","aLp_minus_50_square","dCpSC","dHpSH","_calculateT","_calculateRT","rmean","dE","dR","dG","_kR","_kG","_kB","alphas","_colordifferenceCh","black","white","AbstractPaletteQuantizer","ColorHistogram","NeuQuant","NeuQuantFloat","RGBQuant","WuColorCube","WuQuant","quantize","Point","uint32","quadruplet","point","_loadUINT32","_loadQuadruplet","_loadRGBA","getLuminosity","useAlphaChannel","_width","_height","_pointArray","getWidth","getHeight","setWidth","setHeight","getPointArray","createByUint32","uint32Array","toUint8Array","naturalWidth","naturalHeight","canvas","drawImage","fromHTMLCanvasElement","getImageData","fromImageData","fromUint8Array","container","BYTES_PER_ELEMENT","hueGroup","hue","segmentsNumber","seg","Palette","_pointContainer","getNearestColor","colorDistanceCalculator","_getNearestIndex","getPointContainer","_nearestPointFromCache","_i32idx","minimalDistance","MAX_VALUE","hslA","hslB","hueA","hueDiff","lA","lB","satDiff","HueStatistics","ProgressTracker","arithmetic","HueGroup","numGroups","minCols","_numGroups","_minCols","_stats","_groupsFull","hg","gr","cols","injectIntoDictionary","histG","injectIntoArray","_ProgressTracker","valueRange","progressRange","_range","_progressRange","_step","steps","_last","progress","shouldNotify","Neuron","defaultValue","toPoint","createByRGBA","subtract","_NeuQuant","_distance","_sampleFactor","_networkSize","pointContainer","_learn","_buildPalette","_freq","_bias","_radPower","_network","networkBiasShift","_initialBias","sampleFactor","pointsNumber","_minpicturebytes","alphadec","pointsToSample","_nCycles","_initAlpha","radius","_radiusBias","rad","_radiusBiasShift","_radBias","_prime1","_prime2","_prime3","_prime4","tracker","pointIndex","neuronIndex","_contest","_alterSingle","_alterNeighbour","_radiusDecrease","neuron","_alphaRadBias","bestd","bestbiasd","bestpos","bestbiaspos","biasdist","_initialBiasShift","betafreq","_betaShift","_gammaShift","_beta","_betaGamma","_alphaBiasShift","_radBiasShift","_alphaRadBiasShift","NeuronFloat","_NeuQuantFloat","networkBiasShift2","_ColorHistogram","_method","_minHueCols","_initColors","_hueStats","_hueGroups","_histogram","_colorStats1D","_colorStats2D","getImportanceSortedColorsIDXI32","idxi32","initialColorsLimit","freq","pointArray","boxW","_boxSize","boxH","boxes","_makeBoxes","box","effc","_boxPixels","histL","_iterateBox","bbox","wid","i1","stepX","stepY","wrem","hrem","xend","yend","boxesArray","RemovedColor","_colors","_initialDistance","_distanceIncrement","colorArray","usageArray","memDist","palLen","thold","pxi","pxj","colorIndex","createArray1D","dimension1","createArray4D","dimension2","dimension3","dimension4","createArray3D","fillArray3D","fillArray1D","_WuQuant","significantBitsPerChannel","_setQuality","_initialize","_addColor","_pixels","_preparePalette","paletteIndex","_sums","_reds","_greens","_blues","_alphas","_calculateMoments","volumeVariance","cubeIndex","_cut","_cubes","volume","_calculateVariance","lookupRed","lookupGreen","lookupBlue","lookupAlpha","weight","_volume","_weights","_momentsRed","_momentsGreen","_momentsBlue","_momentsAlpha","bestMatch","bestDistance","foundRed","foundGreen","foundBlue","foundAlpha","bitsToRemove","_significantBitsPerChannel","indexRed","indexGreen","indexBlue","indexAlpha","_moments","_table","areaRed","areaGreen","areaBlue","areaAlpha","area2","xarea","_sideSize","xareaRed","xareaGreen","xareaBlue","xareaAlpha","xarea2","trackerProgress","_alphaMaxSideIndex","_maxSideIndex","alphaIndex","redIndex","greenIndex","lineRed","lineGreen","lineBlue","lineAlpha","line2","blueIndex","cube","moment","alphaMaximum","redMaximum","greenMaximum","blueMaximum","greenMinimum","redMinimum","alphaMinimum","blueMinimum","_volumeFloat","_alpha","_red","_green","_blue","volumeRed","volumeGreen","volumeBlue","volumeAlpha","_maximize","wholeRed","wholeGreen","wholeBlue","wholeAlpha","wholeWeight","bottomRed","_bottom","bottomGreen","bottomBlue","bottomAlpha","bottomWeight","cutPosition","halfRed","_top","halfGreen","halfBlue","halfAlpha","halfWeight","halfDistance","_alphaSideSize","tableIndex","AbstractImageQuantizer","ErrorDiffusionRiemersma","ErrorDiffusionArrayKernel2","kernel","_setKernel","_minColorDistance","_serpentine","_calculateErrorLikeGIMP","originalPoint","errorLines","maxErrorLines","_kernel","kernelErrorLines","_fillErrorLine","lni","xStart","xEnd","errorLine","correctedPoint","palettePoint","eg","eb","ea","dStart","dEnd","hilbertCurve","maxBound","walkHilbert","visit","errorQueueSize","errorPropagation","_errorQueueSize","_createWeights","errorQueue","quantizedPoint","weights","multiplier","ssim","K1","K2","image1","image2","numWindows","mssim","windowWidth","windowHeight","lumaValues1","calculateLumaValuesForWindow","lumaValues2","calculateAverageLuma","iterate","averageLumaValue1","averageLumaValue2","sigxy","sigsqx","sigsqy","numPixelsInWin","lumaValues","counter","sumLuma","luma","setImmediateImpl","colorDistanceFormula","paletteQuantization","paletteQuantizer","paletteQuantizationToPaletteQuantizer","colorDistanceFormulaToColorDistance","onProgress","imageQuantization","imageQuantizationToImageQuantizer","outPointContainer","distanceCalculator","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","__esModule","definition","isNodePattern","throwError","_y","_x","trimLeft","trimRight","tinycolor","named","names","matchers","exec","hsl","hsla","hsv","hsva","hex8","parseIntFromHex","convertHexToDecimal","hex6","hex4","hex3","stringInputToObject","isValidCSSUnit","bound01","convertToPercentage","mod","hsvToRgb","hue2rgb","hslToRgb","boundAlpha","inputToRGB","_originalInput","_r","_g","_b","_a","_roundA","_gradientType","gradientType","_ok","rgbToHsl","rgbToHsv","rgbToHex","allow3Char","hex","pad2","rgbaToArgbHex","convertDecimalToHex","_desaturate","toHsl","clamp01","_saturate","_greyscale","desaturate","_lighten","_brighten","toRgb","_darken","_spin","_complement","polyad","_splitcomplement","_analogous","results","slices","part","_monochromatic","toHsv","modification","isDark","getBrightness","isLight","getOriginalInput","getFormat","getAlpha","getLuminance","RsRGB","GsRGB","BsRGB","setAlpha","toHsvString","toHslString","toHex","toHexString","toHex8","allow4Char","rgbaToHex","toHex8String","toRgbString","toPercentageRgb","toPercentageRgbString","toName","hexNames","toFilter","secondColor","hex8String","secondHex8String","formatSet","formattedString","hasAlpha","_applyModification","lighten","brighten","darken","saturate","spin","_applyCombination","analogous","complement","monochromatic","splitcomplement","triad","tetrad","fromRatio","newColor","color1","color2","random","mix","rgb1","rgb2","readability","isReadable","wcag2","wcag2Parms","parms","mostReadable","baseColor","colorList","includeFallbackColors","bestColor","bestScore","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","burntsienna","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","whitesmoke","yellow","yellowgreen","flipped","flip","isOnePointZero","processPercent","isPercentage","CSS_UNIT","PERMISSIVE_MATCH3","PERMISSIVE_MATCH4","ImagePHash","smallerSize","initCoefficients","intToRGBA","getHash","resize","vals","getPixelColor","dctVals","applyDCT","avg","_ref","AUTO","HORIZONTAL_ALIGN_LEFT","HORIZONTAL_ALIGN_CENTER","HORIZONTAL_ALIGN_RIGHT","VERTICAL_ALIGN_TOP","VERTICAL_ALIGN_MIDDLE","VERTICAL_ALIGN_BOTTOM","BLEND_SOURCE_OVER","BLEND_DESTINATION_OVER","BLEND_MULTIPLY","BLEND_ADD","BLEND_SCREEN","BLEND_OVERLAY","BLEND_DARKEN","BLEND_LIGHTEN","BLEND_HARDLIGHT","BLEND_DIFFERENCE","BLEND_EXCLUSION","EDGE_EXTEND","EDGE_WRAP","EDGE_CROP","srcOver","ops","dstOver","multiply","sra","sga","sba","dra","dga","dba","screen","overlay","hardLight","difference","exclusion","addType","getType","pathParts","extension","find","getExifOrientation","_exif","Orientation","parseBitmap","fileTypeFromBuffer","getMIMEFromBuffer","_originalMime","getMIME","decoders","transformation","getExifOrientationTransformation","swapDimensions","_data","_idx","transformBitmap","exifRotate","_rgba","Jimp","_background","composite","compositeBitmapOverBackground","encoders","getBufferAsync","hint","prim","_toPrimitive","_toPropertyKey","alphabet","maxHashLength","maxHash","bufferFromArrayBuffer","loadFromURL","emptyBitmap","MIME_PNG","getBase64","setPixelColor","jimpInstance","_len2","_key2","methodName","emitMulti","cssColorToHex","_quality","_deflateLevel","_deflateStrategy","_filterType","rgbaBuffer","makeRGBABufferFromRGB","loadBufferFromPath","extraConstructor","__extraConstructors","bool","eventName","getExtension","pathObj","recursive","pHash","distanceFromHash","compareHash","currentHash","getPixelIndex","edgeHandling","xi","yi","byteLen","scanIterator","addConstants","addJimpMethods","_ref2","jimpEvMethod","evName","evNameBefore","evNameAfter","wrappedCb","_len4","_key4","_len5","_key5","jimpEvChange","opacitySource","opacityDest","blendmode","baseImage","opacity","scanQuiet","sx","sy","dstIdx","blended","limit255","appendConstructorOption","rgbaToInt","cssColor","bmp1","bmp2","cloneQuiet","percent","phash","hash1","hash2","compareHashes","colorDiff","rgba1","rgba2","gl","MIME_TYPE","MIME_JPEG","class","PNG_FILTER_AUTO","PNG_FILTER_NONE","PNG_FILTER_SUB","PNG_FILTER_UP","PNG_FILTER_AVERAGE","PNG_FILTER_PATH","MIME_TYPE_SECOND","fromAGBR","toAGBR","mulTable","shgTable","applyKernel","im","kx","ky","isDef","clr2","colorFn","actions","action","colorModifier","LIGHTEN","BRIGHTEN","DARKEN","DESATURATE","SATURATE","GREYSCALE","SPIN","HUE","MIX","TINT","SHADE","XOR","RED","GREEN","BLUE","rgb565Matrix","flipFn","horizontal","vertical","getBounds","histogramChannel","findIndex","reverse","measureText","font","kerning","splitLines","words","currentLine","longestLine","word","measureTextHeight","drawCharacter","characterPage","printText","defaultCharWidth","fontChar","fontKerning","Resize","widthOriginal","heightOriginal","targetWidth","targetHeight","blendAlpha","interpolationPass","resizeCallback","colorChannels","targetWidthMultipliedByChannels","originalWidthMultipliedByChannels","originalHeightMultipliedByChannels","widthPassResultSize","finalResultSize","initialize","configurePasses","resizeWidth","bypassResizer","ratioWeightWidthPass","initializeFirstPassBuffers","resizeWidthInterpolatedRGBA","resizeWidthInterpolatedRGB","resizeWidthRGBA","resizeWidthRGB","resizeHeight","ratioWeightHeightPass","initializeSecondPassBuffers","resizeHeightInterpolated","resizeHeightRGBA","resizeHeightRGB","_resizeWidthInterpolatedRGBChannels","fourthChannel","channelsNum","ratioWeight","outputBuffer","widthBuffer","targetPosition","interpolationWidthSourceReadStop","finalOffset","pixelOffset","firstWeight","secondWeight","_resizeWidthRGBChannels","ratioWeightDivisor","nextLineOffsetOriginalWidth","nextLineOffsetTargetWidth","outputWidthWorkBench","trustworthyColorsCount","outputWidthWorkBenchOpaquePixelsCount","amountToNext","actualPosition","currentPosition","outputOffset","_resizeHeightRGBChannels","outputHeightWorkBench","heightBuffer","outputHeightWorkBenchOpaquePixelsCount","caret","interpolationHeightSourceReadStop","pixelOffsetAccumulated","pixelOffsetAccumulated2","BILINEARAlgo","generateFloatBuffer","generateFloat64Buffer","generateUint8Buffer","operations","nearestNeighbor","wSrc","hSrc","wDst","hDst","bufSrc","bufDst","posDst","posSrc","bilinearInterpolation","interpolate","kMin","vMin","kMax","vMax","xMin","xMax","yMin","yMax","posMin","posMax","_interpolate2D","wM","wDst2","hM","hDst2","buf1","xPos","srcPos","buf1Pos","kPos","x3","buf2","yPos","buf2Pos","y3","realColors","xyPos","pixelAlpha","bicubicInterpolation","hermiteInterpolation","c0","c3","bezierInterpolation","nt","matrixRotate","deg","angle","nW","nH","dstBuffer","createIdxTranslationFunction","srcIdxFunction","dstIdxFunction","srcIdx","pixelRGBA","advancedRotate","cosine","sine","bW","bH","createTranslationFunction","translate2Cartesian","translate2Screen","cartesian","crop","plugins","srcx","srcy","srcw","srch","blur","rsum","gsum","bsum","asum","p1","p2","yp","yw","pa","wm","hm","rad1","mulSum","shgSum","vmin","vmax","iterations","circle","center","curR","brightness","contrast","adjust","posterize","sepia","fade","convolution","newData","kRows","kCols","rowEnd","colEnd","rowIni","colIni","rSum","gSum","bSum","gi","idxi","opaque","pixelate","xx","yx","convolute","colour","contain","alignBits","hbits","alignH","alignV","cover","autocrop","leaveBorder","tolerance","cropOnlyFrames","cropSymmetric","ignoreSides","north","south","east","west","colorTarget","northPixelsToCrop","eastPixelsToCrop","southPixelsToCrop","westPixelsToCrop","colorXY","doCrop","widthOfRemainingPixels","heightOfRemainingPixels","displace","displacement","ids","dither565","dither16","fisheye","hx","hy","rn","cosA","sinA","mirror","gaussian","range","rr2","rr2pi","dsq","wsum","iy","ix","invert","destX","destY","bounds","FONT_SANS_8_BLACK","FONT_SANS_10_BLACK","FONT_SANS_12_BLACK","FONT_SANS_14_BLACK","FONT_SANS_16_BLACK","FONT_SANS_32_BLACK","FONT_SANS_64_BLACK","FONT_SANS_128_BLACK","FONT_SANS_8_WHITE","FONT_SANS_16_WHITE","FONT_SANS_32_WHITE","FONT_SANS_64_WHITE","FONT_SANS_128_WHITE","loadFont","firstString","newPages","loadPages","print","alignmentX","alignmentY","lineString","alignmentWidth","alignment","xOffsetBasedOnAlignment","RESIZE_NEAREST_NEIGHBOR","RESIZE_BILINEAR","RESIZE_BICUBIC","RESIZE_HERMITE","RESIZE_BEZIER","rotate","scaleToFit","shadow","orig","autoGreyscale","configuration","jimpConfig","addToConfig","newConfig","typeModule","mimeType","pluginModule","plugin","MIME_BMP","MIME_X_MS_BMP","MIME_TIFF","t256","t257","tiff","MIME_GIF","gifObj","gifData","newFrame","newGif","initializedPlugins"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/jimp/es/index.js b/node_modules/jimp/es/index.js new file mode 100644 index 00000000..f14cf14a --- /dev/null +++ b/node_modules/jimp/es/index.js @@ -0,0 +1,8 @@ +import configure from "@jimp/custom"; +import types from "@jimp/types"; +import plugins from "@jimp/plugins"; +export default configure({ + types: [types], + plugins: [plugins] +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/jimp/es/index.js.map b/node_modules/jimp/es/index.js.map new file mode 100644 index 00000000..7f9aa10a --- /dev/null +++ b/node_modules/jimp/es/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["configure","types","plugins"],"sources":["../src/index.js"],"sourcesContent":["import configure from \"@jimp/custom\";\n\nimport types from \"@jimp/types\";\nimport plugins from \"@jimp/plugins\";\n\nexport default configure({\n types: [types],\n plugins: [plugins],\n});\n"],"mappings":"AAAA,OAAOA,SAAS,MAAM,cAAc;AAEpC,OAAOC,KAAK,MAAM,aAAa;AAC/B,OAAOC,OAAO,MAAM,eAAe;AAEnC,eAAeF,SAAS,CAAC;EACvBC,KAAK,EAAE,CAACA,KAAK,CAAC;EACdC,OAAO,EAAE,CAACA,OAAO;AACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/Apache License.txt b/node_modules/jimp/fonts/open-sans/Apache License.txt new file mode 100644 index 00000000..989e2c59 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/Apache License.txt @@ -0,0 +1,201 @@ +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 [yyyy] [name of copyright owner] + + 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. \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt b/node_modules/jimp/fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt new file mode 100644 index 00000000..1e4c5db0 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-10-black/open-sans-10-black.png b/node_modules/jimp/fonts/open-sans/open-sans-10-black/open-sans-10-black.png new file mode 100644 index 00000000..a4592981 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-10-black/open-sans-10-black.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt b/node_modules/jimp/fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt new file mode 100644 index 00000000..5372da2a --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt @@ -0,0 +1,183 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-12-black/open-sans-12-black.png b/node_modules/jimp/fonts/open-sans/open-sans-12-black/open-sans-12-black.png new file mode 100644 index 00000000..b84a9d79 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-12-black/open-sans-12-black.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt b/node_modules/jimp/fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt new file mode 100644 index 00000000..2bb22b19 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-128-black/open-sans-128-black.png b/node_modules/jimp/fonts/open-sans/open-sans-128-black/open-sans-128-black.png new file mode 100644 index 00000000..7e9986e2 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-128-black/open-sans-128-black.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt b/node_modules/jimp/fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt new file mode 100644 index 00000000..5e8811e6 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-128-white/open-sans-128-white.png b/node_modules/jimp/fonts/open-sans/open-sans-128-white/open-sans-128-white.png new file mode 100644 index 00000000..64b949b1 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-128-white/open-sans-128-white.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt b/node_modules/jimp/fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt new file mode 100644 index 00000000..8df67a9b --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-14-black/open-sans-14-black.png b/node_modules/jimp/fonts/open-sans/open-sans-14-black/open-sans-14-black.png new file mode 100644 index 00000000..e66461fe Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-14-black/open-sans-14-black.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt b/node_modules/jimp/fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt new file mode 100644 index 00000000..afb29970 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-16-black/open-sans-16-black.png b/node_modules/jimp/fonts/open-sans/open-sans-16-black/open-sans-16-black.png new file mode 100644 index 00000000..99171bea Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-16-black/open-sans-16-black.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt b/node_modules/jimp/fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt new file mode 100644 index 00000000..2b6cbe79 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-16-white/open-sans-16-white.png b/node_modules/jimp/fonts/open-sans/open-sans-16-white/open-sans-16-white.png new file mode 100644 index 00000000..ccb1e3c9 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-16-white/open-sans-16-white.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt b/node_modules/jimp/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt new file mode 100644 index 00000000..f2d9bf4a --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-32-black/open-sans-32-black.png b/node_modules/jimp/fonts/open-sans/open-sans-32-black/open-sans-32-black.png new file mode 100644 index 00000000..50ff1b41 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-32-black/open-sans-32-black.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt b/node_modules/jimp/fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt new file mode 100644 index 00000000..35c3584d --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-32-white/open-sans-32-white.png b/node_modules/jimp/fonts/open-sans/open-sans-32-white/open-sans-32-white.png new file mode 100644 index 00000000..5900c354 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-32-white/open-sans-32-white.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt b/node_modules/jimp/fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt new file mode 100644 index 00000000..f4580f3c --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-64-black/open-sans-64-black.png b/node_modules/jimp/fonts/open-sans/open-sans-64-black/open-sans-64-black.png new file mode 100644 index 00000000..47af5238 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-64-black/open-sans-64-black.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt b/node_modules/jimp/fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt new file mode 100644 index 00000000..dca72ad3 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-64-white/open-sans-64-white.png b/node_modules/jimp/fonts/open-sans/open-sans-64-white/open-sans-64-white.png new file mode 100644 index 00000000..de9a88aa Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-64-white/open-sans-64-white.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt b/node_modules/jimp/fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt new file mode 100644 index 00000000..34f0e621 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-8-black/open-sans-8-black.png b/node_modules/jimp/fonts/open-sans/open-sans-8-black/open-sans-8-black.png new file mode 100644 index 00000000..b0579858 Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-8-black/open-sans-8-black.png differ diff --git a/node_modules/jimp/fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt b/node_modules/jimp/fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt new file mode 100644 index 00000000..6d437678 --- /dev/null +++ b/node_modules/jimp/fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/jimp/fonts/open-sans/open-sans-8-white/open-sans-8-white.png b/node_modules/jimp/fonts/open-sans/open-sans-8-white/open-sans-8-white.png new file mode 100644 index 00000000..435f6d5e Binary files /dev/null and b/node_modules/jimp/fonts/open-sans/open-sans-8-white/open-sans-8-white.png differ diff --git a/node_modules/jimp/package.json b/node_modules/jimp/package.json new file mode 100644 index 00000000..e648e3ce --- /dev/null +++ b/node_modules/jimp/package.json @@ -0,0 +1,76 @@ +{ + "name": "jimp", + "version": "0.22.12", + "description": "An image processing library written entirely in JavaScript (i.e. zero external or native dependencies)", + "main": "dist/index.js", + "module": "es/index.js", + "types": "types/index.d.ts", + "browser": "browser/lib/jimp.js", + "tonicExampleFilename": "example.js", + "files": [ + "browser", + "dist", + "es", + "index.d.ts", + "fonts", + "types" + ], + "repository": "jimp-dev/jimp", + "scripts": { + "test": "cross-env BABEL_ENV=test mocha --require @babel/register --recursive test --extension js", + "test:watch": "npm run test -- --reporter min --watch", + "test:coverage": "nyc npm run test", + "build": "npm run build:browser && npm run build:node:production && npm run build:module", + "build:watch": "npm run build:node:debug -- -- --watch --verbose", + "build:debug": "npm run build:browser:debug && npm run build:node:debug", + "build:module": "cross-env BABEL_ENV=module babel src -d es --source-maps --config-file ../../babel.config.js", + "build:node": "babel src -d dist --source-maps --config-file ../../babel.config.js", + "build:node:debug": "cross-env BABEL_ENV=development npm run build:node", + "build:node:production": "cross-env BABEL_ENV=production npm run build:node", + "build:browser": "cross-env NODE_ENV=production webpack", + "build:browser:debug": "cross-env NODE_ENV=development ENV=browser webpack" + }, + "keywords": [ + "image", + "image processing", + "image manipulation", + "png", + "jpg", + "jpeg", + "bmp", + "resize", + "scale", + "crop" + ], + "author": "Oliver Moran ", + "license": "MIT", + "dependencies": { + "@jimp/custom": "^0.22.12", + "@jimp/plugins": "^0.22.12", + "@jimp/types": "^0.22.12", + "regenerator-runtime": "^0.13.3" + }, + "devDependencies": { + "@jimp/test-utils": "^0.22.12", + "empty-module": "^0.0.2", + "express": "^4.17.1", + "path-browserify": "^1.0.1", + "webpack": "^5.75.0", + "webpack-cli": "^5.0.1" + }, + "nyc": { + "sourceMap": false, + "instrument": false, + "reporter": [ + "text", + "text-summary", + "lcov", + "html" + ], + "exclude": [ + "src/modules/*.js", + "test/*.js" + ] + }, + "gitHead": "a4a8d6364bbf97629749e196f3b0a4c94c9a7abc" +} diff --git a/node_modules/jimp/types/index.d.ts b/node_modules/jimp/types/index.d.ts new file mode 100644 index 00000000..5647fb12 --- /dev/null +++ b/node_modules/jimp/types/index.d.ts @@ -0,0 +1,53 @@ +// Minimum TypeScript Version: 3.1 + +/** + * While there is nothing in these typings that prevent it from running in TS 2.8 even, + * due to the complexity of the typings anything lower than TS 3.1 will only see + * Jimp as `any`. In order to test the strict versions of these types in our typing + * test suite, the version has been bumped to 3.1 + */ + +import { + Jimp as JimpType, + Bitmap, + RGB, + RGBA, + UnionToIntersection, + GetPluginVal, + GetPluginConst, + GetPluginEncoders, + GetPluginDecoders, + JimpConstructors, +} from "@jimp/core"; +import typeFn from "@jimp/types"; +import pluginFn from "@jimp/plugins"; + +type Types = ReturnType; +type Plugins = ReturnType; + +type IntersectedPluginTypes = UnionToIntersection< + GetPluginVal | GetPluginVal +>; + +type IntersectedPluginConsts = UnionToIntersection< + GetPluginConst | GetPluginConst +>; + +type IntersectedPluginEncoders = UnionToIntersection< + GetPluginEncoders | GetPluginEncoders +>; + +type IntersectedPluginDecoders = UnionToIntersection< + GetPluginDecoders | GetPluginDecoders +>; + +type Jimp = JimpType & IntersectedPluginTypes; + +declare const Jimp: JimpConstructors & + IntersectedPluginConsts & { + prototype: Jimp; + encoders: IntersectedPluginEncoders; + decoders: IntersectedPluginDecoders; + }; + +export = Jimp; diff --git a/node_modules/jimp/types/test.ts b/node_modules/jimp/types/test.ts new file mode 100644 index 00000000..89e29abb --- /dev/null +++ b/node_modules/jimp/types/test.ts @@ -0,0 +1,95 @@ +import * as Jimp from "jimp"; +import { ColorActionName } from "@jimp/plugin-color"; + +const jimpInst: Jimp = new Jimp("test"); + +// Main Jimp export should already have all of these already applied +// $ExpectError +jimpInst.read("Test"); +jimpInst.displace(jimpInst, 2); +jimpInst.resize(40, 40); +jimpInst.displace(jimpInst, 2); +jimpInst.shadow((err, val, coords) => {}); +jimpInst.fishEye({ r: 12 }); +jimpInst.circle({ radius: 12, x: 12, y: 12 }); +jimpInst.color([{ apply: ColorActionName.SATURATE, params: [90] }]); +// $ExpectError +jimpInst.PNG_FILTER_NONE; + +// $ExpectError +jimpInst.test; + +// $ExpectError +jimpInst.func(); + +// Main Jimp export should already have all of these already applied +Jimp.read("Test"); + +// $ExpectType 0 +Jimp.PNG_FILTER_NONE; + +// $ExpectError +Jimp.test; + +// $ExpectError +Jimp.func(); + +test("can clone properly", async () => { + const baseImage = await Jimp.read("filename"); + const cloneBaseImage = baseImage.clone(); + + // $ExpectType number + cloneBaseImage._deflateLevel; + + test("can handle `this` returns on the core type properly", () => { + // $ExpectType number + cloneBaseImage.posterize(3)._quality; + }); + + test("can handle `this` returns properly", () => { + cloneBaseImage + .resize(1, 1) + .crop(0, 0, 0, 0) + .mask(cloneBaseImage, 2, 2) + .print("a" as any, 2, 2, "a" as any) + .resize(1, 1) + .quality(1) + .deflateLevel(2)._filterType; + }); + + test("can handle imageCallbacks `this` properly", () => { + cloneBaseImage.rgba(false, (_, jimpCBIn) => { + // $ExpectError + jimpCBIn.read("Test"); + jimpCBIn.displace(jimpInst, 2); + jimpCBIn.resize(40, 40); + // $ExpectType number + jimpCBIn._filterType; + + // $ExpectError + jimpCBIn.test; + + // $ExpectError + jimpCBIn.func(); + }); + }); +}); + +test("Can handle callback with constructor", () => { + const myBmpBuffer: Buffer = {} as any; + + Jimp.read(myBmpBuffer, (err, cbJimpInst) => { + // $ExpectError + cbJimpInst.read("Test"); + cbJimpInst.displace(jimpInst, 2); + cbJimpInst.resize(40, 40); + // $ExpectType number + cbJimpInst._filterType; + + // $ExpectError + cbJimpInst.test; + + // $ExpectError + cbJimpInst.func(); + }); +}); diff --git a/node_modules/jimp/types/tsconfig.json b/node_modules/jimp/types/tsconfig.json new file mode 100644 index 00000000..eb1dd15b --- /dev/null +++ b/node_modules/jimp/types/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "skipLibCheck": true, + "noEmit": true, + + // If the library is an external module (uses `export`), this allows your test file to import "mylib" instead of "./index". + // If the library is global (cannot be imported via `import` or `require`), leave this out. + "baseUrl": "../test", + "paths": { + "mylib": ["."] + } + } +} diff --git a/node_modules/jpeg-js/.github/workflows/ci.yml b/node_modules/jpeg-js/.github/workflows/ci.yml new file mode 100644 index 00000000..0114b698 --- /dev/null +++ b/node_modules/jpeg-js/.github/workflows/ci.yml @@ -0,0 +1,19 @@ +name: CI +on: + push: + branches: [master] + pull_request: # run on all PRs, not just PRs to a particular branch +jobs: + test: + strategy: + fail-fast: true + matrix: + nodeversion: [8.x, 10.x, 12.x, 14.x] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.nodeversion }} + - run: npm install + - run: npm test diff --git a/node_modules/jpeg-js/CONTRIBUTING.md b/node_modules/jpeg-js/CONTRIBUTING.md new file mode 100644 index 00000000..1954cb56 --- /dev/null +++ b/node_modules/jpeg-js/CONTRIBUTING.md @@ -0,0 +1,27 @@ +# jpeg-js is an OPEN Open Source Project + +----------------------------------------- + +## What? + +Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project. + +## Rules + +There are a few basic ground-rules for contributors: + +1. **No `--force` pushes** or modifying the Git history in any way. +1. **Non-master branches** ought to be used for ongoing work. +1. **External API changes and significant modifications** ought to be subject to an **internal pull-request** to solicit feedback from other contributors. +1. Internal pull-requests to solicit feedback are *encouraged* for any other non-trivial contribution but left to the discretion of the contributor. +1. Contributors should attempt to adhere to the prevailing code-style. + +## Releases + +Declaring formal releases remains the prerogative of the project maintainer. + +## Changes to this arrangement + +This is an experiment and feedback is welcome! This document may also be subject to pull-requests or changes by contributors where you believe you have something valuable to add or change. + +----------------------------------------- diff --git a/node_modules/jpeg-js/LICENSE b/node_modules/jpeg-js/LICENSE new file mode 100644 index 00000000..5f122668 --- /dev/null +++ b/node_modules/jpeg-js/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2014, Eugene Ware +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 Eugene Ware 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 EUGENE WARE ''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 EUGENE WARE 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/jpeg-js/README.md b/node_modules/jpeg-js/README.md new file mode 100644 index 00000000..380176f0 --- /dev/null +++ b/node_modules/jpeg-js/README.md @@ -0,0 +1,176 @@ +# jpeg-js + +A pure javascript JPEG encoder and decoder for node.js + +**NOTE:** this is a _synchronous_ (i.e. CPU-blocking) library that is much slower than native alternatives. If you don't need a _pure javascript_ implementation, consider using async alternatives like [sharp](http://npmjs.com/package/sharp) in node or the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) in the browser. + +[![build status](https://secure.travis-ci.org/eugeneware/jpeg-js.png)](http://travis-ci.org/eugeneware/jpeg-js) + +## Installation + +This module is installed via npm: + +```bash +$ npm install jpeg-js +``` + +## Example Usage + +### Decoding JPEGs + +Will decode a buffer or typed array into a `Buffer`; + +```js +var jpeg = require('jpeg-js'); +var jpegData = fs.readFileSync('grumpycat.jpg'); +var rawImageData = jpeg.decode(jpegData); +console.log(rawImageData); +/* +{ width: 320, + height: 180, + data: } +*/ +``` + +To decode directly into a `Uint8Array`, pass `useTArray: true` in options +`decode`: + +```js +var jpeg = require('jpeg-js'); +var jpegData = fs.readFileSync('grumpycat.jpg'); +var rawImageData = jpeg.decode(jpegData, {useTArray: true}); // return as Uint8Array +console.log(rawImageData); +/* +{ width: 320, + height: 180, + data: { '0': 91, '1': 64, ... } } // typed array +*/ +``` + +#### Decode Options + +| Option | Description | Default | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| `colorTransform` | Transform alternate colorspaces like YCbCr. `undefined` means respect the default behavior encoded in metadata. | `undefined` | +| `useTArray` | Decode pixels into a typed `Uint8Array` instead of a `Buffer`. | `false` | +| `formatAsRGBA` | Decode pixels into RGBA vs. RGB. | `true` | +| `tolerantDecoding` | Be more tolerant when encountering technically invalid JPEGs. | `true` | +| `maxResolutionInMP` | The maximum resolution image that `jpeg-js` should attempt to decode in megapixels. Images larger than this resolution will throw an error instead of decoding. | `100` | +| `maxMemoryUsageInMB` | The (approximate) maximum memory that `jpeg-js` should allocate while attempting to decode the image in mebibyte. Images requiring more memory than this will throw an error instead of decoding. | `512` | + +### Encoding JPEGs + +```js +var jpeg = require('jpeg-js'); +var width = 320, + height = 180; +var frameData = new Buffer(width * height * 4); +var i = 0; +while (i < frameData.length) { + frameData[i++] = 0xff; // red + frameData[i++] = 0x00; // green + frameData[i++] = 0x00; // blue + frameData[i++] = 0xff; // alpha - ignored in JPEGs +} +var rawImageData = { + data: frameData, + width: width, + height: height, +}; +var jpegImageData = jpeg.encode(rawImageData, 50); +console.log(jpegImageData); +/* +{ width: 320, + height: 180, + data: } +*/ +// write to file +fs.writeFileSync('image.jpg', jpegImageData.data); +``` + +## License + +### Decoding + +This library builds on the work of two other JPEG javascript libraries, +namely [jpgjs](https://github.com/notmasteryet/jpgjs) for the decoding +which is licensed under the Apache 2.0 License below: + +Copyright 2011 notmasteryet + +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](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. + +### Encoding + +The encoding is based off a port of the JPEG encoder in [as3corelib](https://code.google.com/p/as3corelib/source/browse/trunk/src/com/adobe/images/JPGEncoder.as). + +The port to Javascript was done by by Andreas Ritter, www.bytestrom.eu, 11/2009. + +The Adobe License for the encoder is: + +**Adobe** + +Copyright (c) 2008, Adobe Systems Incorporated +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 Adobe Systems Incorporated nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +## Contributing + +jpeg-js is an **OPEN Open Source Project**. This means that: + +> Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project. + +See the [CONTRIBUTING.md](https://github.com/eugeneware/jpeg-js/blob/master/CONTRIBUTING.md) file for more details. + +### Contributors + +jpeg-js is only possible due to the excellent work of the following contributors: + + + + + + + + + + + + +
AdobeGitHub/adobe
Yury DelendikGitHub/notmasteryet
Eugene WareGitHub/eugeneware
Michael KellyGitHub/mrkelly
Peter LiljenbergGitHub/petli
XadillaXGitHub/XadillaX
strandedcityGitHub/strandedcity
wmossmanGitHub/wmossman
Patrick HulceGitHub/patrickhulce
Ben WileyGitHub/benwiley4000
diff --git a/node_modules/jpeg-js/index.d.ts b/node_modules/jpeg-js/index.d.ts new file mode 100644 index 00000000..adbdd4b4 --- /dev/null +++ b/node_modules/jpeg-js/index.d.ts @@ -0,0 +1,36 @@ +export interface RawImageData { + width: number; + height: number; + data: T; +} + +type BufferRet = RawImageData; +type UintArrRet = RawImageData; + +type ImageData = BufferRet | UintArrRet; +type BufferLike = Buffer | Uint8Array | ArrayLike | Iterable | ArrayBuffer; + +export declare function encode(imgData: RawImageData & {comments?: string[]}, quality?: number): BufferRet + +export declare function decode( + jpegData: BufferLike, + opts: { + useTArray: true; + colorTransform?: boolean; + formatAsRGBA?: boolean; + tolerantDecoding?: boolean; + maxResolutionInMP?: number; + maxMemoryUsageInMB?: number; + }, +): UintArrRet & {comments?: string[]}; +export declare function decode( + jpegData: BufferLike, + opts?: { + useTArray?: false; + colorTransform?: boolean; + formatAsRGBA?: boolean; + tolerantDecoding?: boolean; + maxResolutionInMP?: number; + maxMemoryUsageInMB?: number; + }, +): BufferRet & {comments?: string[]}; diff --git a/node_modules/jpeg-js/index.js b/node_modules/jpeg-js/index.js new file mode 100644 index 00000000..23734849 --- /dev/null +++ b/node_modules/jpeg-js/index.js @@ -0,0 +1,7 @@ +var encode = require('./lib/encoder'), + decode = require('./lib/decoder'); + +module.exports = { + encode: encode, + decode: decode +}; diff --git a/node_modules/jpeg-js/lib/decoder.js b/node_modules/jpeg-js/lib/decoder.js new file mode 100644 index 00000000..19824818 --- /dev/null +++ b/node_modules/jpeg-js/lib/decoder.js @@ -0,0 +1,1151 @@ +/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- / +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ +/* + Copyright 2011 notmasteryet + + 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. +*/ + +// - The JPEG specification can be found in the ITU CCITT Recommendation T.81 +// (www.w3.org/Graphics/JPEG/itu-t81.pdf) +// - The JFIF specification can be found in the JPEG File Interchange Format +// (www.w3.org/Graphics/JPEG/jfif3.pdf) +// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters +// in PostScript Level 2, Technical Note #5116 +// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf) + +var JpegImage = (function jpegImage() { + "use strict"; + var dctZigZag = new Int32Array([ + 0, + 1, 8, + 16, 9, 2, + 3, 10, 17, 24, + 32, 25, 18, 11, 4, + 5, 12, 19, 26, 33, 40, + 48, 41, 34, 27, 20, 13, 6, + 7, 14, 21, 28, 35, 42, 49, 56, + 57, 50, 43, 36, 29, 22, 15, + 23, 30, 37, 44, 51, 58, + 59, 52, 45, 38, 31, + 39, 46, 53, 60, + 61, 54, 47, + 55, 62, + 63 + ]); + + var dctCos1 = 4017 // cos(pi/16) + var dctSin1 = 799 // sin(pi/16) + var dctCos3 = 3406 // cos(3*pi/16) + var dctSin3 = 2276 // sin(3*pi/16) + var dctCos6 = 1567 // cos(6*pi/16) + var dctSin6 = 3784 // sin(6*pi/16) + var dctSqrt2 = 5793 // sqrt(2) + var dctSqrt1d2 = 2896 // sqrt(2) / 2 + + function constructor() { + } + + function buildHuffmanTable(codeLengths, values) { + var k = 0, code = [], i, j, length = 16; + while (length > 0 && !codeLengths[length - 1]) + length--; + code.push({children: [], index: 0}); + var p = code[0], q; + for (i = 0; i < length; i++) { + for (j = 0; j < codeLengths[i]; j++) { + p = code.pop(); + p.children[p.index] = values[k]; + while (p.index > 0) { + if (code.length === 0) + throw new Error('Could not recreate Huffman Table'); + p = code.pop(); + } + p.index++; + code.push(p); + while (code.length <= i) { + code.push(q = {children: [], index: 0}); + p.children[p.index] = q.children; + p = q; + } + k++; + } + if (i + 1 < length) { + // p here points to last code + code.push(q = {children: [], index: 0}); + p.children[p.index] = q.children; + p = q; + } + } + return code[0].children; + } + + function decodeScan(data, offset, + frame, components, resetInterval, + spectralStart, spectralEnd, + successivePrev, successive, opts) { + var precision = frame.precision; + var samplesPerLine = frame.samplesPerLine; + var scanLines = frame.scanLines; + var mcusPerLine = frame.mcusPerLine; + var progressive = frame.progressive; + var maxH = frame.maxH, maxV = frame.maxV; + + var startOffset = offset, bitsData = 0, bitsCount = 0; + function readBit() { + if (bitsCount > 0) { + bitsCount--; + return (bitsData >> bitsCount) & 1; + } + bitsData = data[offset++]; + if (bitsData == 0xFF) { + var nextByte = data[offset++]; + if (nextByte) { + throw new Error("unexpected marker: " + ((bitsData << 8) | nextByte).toString(16)); + } + // unstuff 0 + } + bitsCount = 7; + return bitsData >>> 7; + } + function decodeHuffman(tree) { + var node = tree, bit; + while ((bit = readBit()) !== null) { + node = node[bit]; + if (typeof node === 'number') + return node; + if (typeof node !== 'object') + throw new Error("invalid huffman sequence"); + } + return null; + } + function receive(length) { + var n = 0; + while (length > 0) { + var bit = readBit(); + if (bit === null) return; + n = (n << 1) | bit; + length--; + } + return n; + } + function receiveAndExtend(length) { + var n = receive(length); + if (n >= 1 << (length - 1)) + return n; + return n + (-1 << length) + 1; + } + function decodeBaseline(component, zz) { + var t = decodeHuffman(component.huffmanTableDC); + var diff = t === 0 ? 0 : receiveAndExtend(t); + zz[0]= (component.pred += diff); + var k = 1; + while (k < 64) { + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) + break; + k += 16; + continue; + } + k += r; + var z = dctZigZag[k]; + zz[z] = receiveAndExtend(s); + k++; + } + } + function decodeDCFirst(component, zz) { + var t = decodeHuffman(component.huffmanTableDC); + var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive); + zz[0] = (component.pred += diff); + } + function decodeDCSuccessive(component, zz) { + zz[0] |= readBit() << successive; + } + var eobrun = 0; + function decodeACFirst(component, zz) { + if (eobrun > 0) { + eobrun--; + return; + } + var k = spectralStart, e = spectralEnd; + while (k <= e) { + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) { + eobrun = receive(r) + (1 << r) - 1; + break; + } + k += 16; + continue; + } + k += r; + var z = dctZigZag[k]; + zz[z] = receiveAndExtend(s) * (1 << successive); + k++; + } + } + var successiveACState = 0, successiveACNextValue; + function decodeACSuccessive(component, zz) { + var k = spectralStart, e = spectralEnd, r = 0; + while (k <= e) { + var z = dctZigZag[k]; + var direction = zz[z] < 0 ? -1 : 1; + switch (successiveACState) { + case 0: // initial state + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) { + eobrun = receive(r) + (1 << r); + successiveACState = 4; + } else { + r = 16; + successiveACState = 1; + } + } else { + if (s !== 1) + throw new Error("invalid ACn encoding"); + successiveACNextValue = receiveAndExtend(s); + successiveACState = r ? 2 : 3; + } + continue; + case 1: // skipping r zero items + case 2: + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + else { + r--; + if (r === 0) + successiveACState = successiveACState == 2 ? 3 : 0; + } + break; + case 3: // set value for a zero item + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + else { + zz[z] = successiveACNextValue << successive; + successiveACState = 0; + } + break; + case 4: // eob + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + break; + } + k++; + } + if (successiveACState === 4) { + eobrun--; + if (eobrun === 0) + successiveACState = 0; + } + } + function decodeMcu(component, decode, mcu, row, col) { + var mcuRow = (mcu / mcusPerLine) | 0; + var mcuCol = mcu % mcusPerLine; + var blockRow = mcuRow * component.v + row; + var blockCol = mcuCol * component.h + col; + // If the block is missing and we're in tolerant mode, just skip it. + if (component.blocks[blockRow] === undefined && opts.tolerantDecoding) + return; + decode(component, component.blocks[blockRow][blockCol]); + } + function decodeBlock(component, decode, mcu) { + var blockRow = (mcu / component.blocksPerLine) | 0; + var blockCol = mcu % component.blocksPerLine; + // If the block is missing and we're in tolerant mode, just skip it. + if (component.blocks[blockRow] === undefined && opts.tolerantDecoding) + return; + decode(component, component.blocks[blockRow][blockCol]); + } + + var componentsLength = components.length; + var component, i, j, k, n; + var decodeFn; + if (progressive) { + if (spectralStart === 0) + decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive; + else + decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive; + } else { + decodeFn = decodeBaseline; + } + + var mcu = 0, marker; + var mcuExpected; + if (componentsLength == 1) { + mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn; + } else { + mcuExpected = mcusPerLine * frame.mcusPerColumn; + } + if (!resetInterval) resetInterval = mcuExpected; + + var h, v; + while (mcu < mcuExpected) { + // reset interval stuff + for (i = 0; i < componentsLength; i++) + components[i].pred = 0; + eobrun = 0; + + if (componentsLength == 1) { + component = components[0]; + for (n = 0; n < resetInterval; n++) { + decodeBlock(component, decodeFn, mcu); + mcu++; + } + } else { + for (n = 0; n < resetInterval; n++) { + for (i = 0; i < componentsLength; i++) { + component = components[i]; + h = component.h; + v = component.v; + for (j = 0; j < v; j++) { + for (k = 0; k < h; k++) { + decodeMcu(component, decodeFn, mcu, j, k); + } + } + } + mcu++; + + // If we've reached our expected MCU's, stop decoding + if (mcu === mcuExpected) break; + } + } + + if (mcu === mcuExpected) { + // Skip trailing bytes at the end of the scan - until we reach the next marker + do { + if (data[offset] === 0xFF) { + if (data[offset + 1] !== 0x00) { + break; + } + } + offset += 1; + } while (offset < data.length - 2); + } + + // find marker + bitsCount = 0; + marker = (data[offset] << 8) | data[offset + 1]; + if (marker < 0xFF00) { + throw new Error("marker was not found"); + } + + if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx + offset += 2; + } + else + break; + } + + return offset - startOffset; + } + + function buildComponentData(frame, component) { + var lines = []; + var blocksPerLine = component.blocksPerLine; + var blocksPerColumn = component.blocksPerColumn; + var samplesPerLine = blocksPerLine << 3; + // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint. + var R = new Int32Array(64), r = new Uint8Array(64); + + // A port of poppler's IDCT method which in turn is taken from: + // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz, + // "Practical Fast 1-D DCT Algorithms with 11 Multiplications", + // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989, + // 988-991. + function quantizeAndInverse(zz, dataOut, dataIn) { + var qt = component.quantizationTable; + var v0, v1, v2, v3, v4, v5, v6, v7, t; + var p = dataIn; + var i; + + // dequant + for (i = 0; i < 64; i++) + p[i] = zz[i] * qt[i]; + + // inverse DCT on rows + for (i = 0; i < 8; ++i) { + var row = 8 * i; + + // check for all-zero AC coefficients + if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && + p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && + p[7 + row] == 0) { + t = (dctSqrt2 * p[0 + row] + 512) >> 10; + p[0 + row] = t; + p[1 + row] = t; + p[2 + row] = t; + p[3 + row] = t; + p[4 + row] = t; + p[5 + row] = t; + p[6 + row] = t; + p[7 + row] = t; + continue; + } + + // stage 4 + v0 = (dctSqrt2 * p[0 + row] + 128) >> 8; + v1 = (dctSqrt2 * p[4 + row] + 128) >> 8; + v2 = p[2 + row]; + v3 = p[6 + row]; + v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8; + v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8; + v5 = p[3 + row] << 4; + v6 = p[5 + row] << 4; + + // stage 3 + t = (v0 - v1+ 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; + + // stage 2 + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + // stage 1 + p[0 + row] = v0 + v7; + p[7 + row] = v0 - v7; + p[1 + row] = v1 + v6; + p[6 + row] = v1 - v6; + p[2 + row] = v2 + v5; + p[5 + row] = v2 - v5; + p[3 + row] = v3 + v4; + p[4 + row] = v3 - v4; + } + + // inverse DCT on columns + for (i = 0; i < 8; ++i) { + var col = i; + + // check for all-zero AC coefficients + if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 && + p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 && + p[7*8 + col] == 0) { + t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14; + p[0*8 + col] = t; + p[1*8 + col] = t; + p[2*8 + col] = t; + p[3*8 + col] = t; + p[4*8 + col] = t; + p[5*8 + col] = t; + p[6*8 + col] = t; + p[7*8 + col] = t; + continue; + } + + // stage 4 + v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12; + v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12; + v2 = p[2*8 + col]; + v3 = p[6*8 + col]; + v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12; + v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12; + v5 = p[3*8 + col]; + v6 = p[5*8 + col]; + + // stage 3 + t = (v0 - v1 + 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; + + // stage 2 + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + // stage 1 + p[0*8 + col] = v0 + v7; + p[7*8 + col] = v0 - v7; + p[1*8 + col] = v1 + v6; + p[6*8 + col] = v1 - v6; + p[2*8 + col] = v2 + v5; + p[5*8 + col] = v2 - v5; + p[3*8 + col] = v3 + v4; + p[4*8 + col] = v3 - v4; + } + + // convert to 8-bit integers + for (i = 0; i < 64; ++i) { + var sample = 128 + ((p[i] + 8) >> 4); + dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample; + } + } + + requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8); + + var i, j; + for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { + var scanLine = blockRow << 3; + for (i = 0; i < 8; i++) + lines.push(new Uint8Array(samplesPerLine)); + for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { + quantizeAndInverse(component.blocks[blockRow][blockCol], r, R); + + var offset = 0, sample = blockCol << 3; + for (j = 0; j < 8; j++) { + var line = lines[scanLine + j]; + for (i = 0; i < 8; i++) + line[sample + i] = r[offset++]; + } + } + } + return lines; + } + + function clampTo8bit(a) { + return a < 0 ? 0 : a > 255 ? 255 : a; + } + + constructor.prototype = { + load: function load(path) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", path, true); + xhr.responseType = "arraybuffer"; + xhr.onload = (function() { + // TODO catch parse error + var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); + this.parse(data); + if (this.onload) + this.onload(); + }).bind(this); + xhr.send(null); + }, + parse: function parse(data) { + var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000; + var offset = 0, length = data.length; + function readUint16() { + var value = (data[offset] << 8) | data[offset + 1]; + offset += 2; + return value; + } + function readDataBlock() { + var length = readUint16(); + var array = data.subarray(offset, offset + length - 2); + offset += array.length; + return array; + } + function prepareComponents(frame) { + // According to the JPEG standard, the sampling factor must be between 1 and 4 + // See https://github.com/libjpeg-turbo/libjpeg-turbo/blob/9abeff46d87bd201a952e276f3e4339556a403a3/libjpeg.txt#L1138-L1146 + var maxH = 1, maxV = 1; + var component, componentId; + for (componentId in frame.components) { + if (frame.components.hasOwnProperty(componentId)) { + component = frame.components[componentId]; + if (maxH < component.h) maxH = component.h; + if (maxV < component.v) maxV = component.v; + } + } + var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH); + var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV); + for (componentId in frame.components) { + if (frame.components.hasOwnProperty(componentId)) { + component = frame.components[componentId]; + var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH); + var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV); + var blocksPerLineForMcu = mcusPerLine * component.h; + var blocksPerColumnForMcu = mcusPerColumn * component.v; + var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu; + var blocks = []; + + // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes) + requestMemoryAllocation(blocksToAllocate * 256); + + for (var i = 0; i < blocksPerColumnForMcu; i++) { + var row = []; + for (var j = 0; j < blocksPerLineForMcu; j++) + row.push(new Int32Array(64)); + blocks.push(row); + } + component.blocksPerLine = blocksPerLine; + component.blocksPerColumn = blocksPerColumn; + component.blocks = blocks; + } + } + frame.maxH = maxH; + frame.maxV = maxV; + frame.mcusPerLine = mcusPerLine; + frame.mcusPerColumn = mcusPerColumn; + } + var jfif = null; + var adobe = null; + var pixels = null; + var frame, resetInterval; + var quantizationTables = [], frames = []; + var huffmanTablesAC = [], huffmanTablesDC = []; + var fileMarker = readUint16(); + var malformedDataOffset = -1; + this.comments = []; + if (fileMarker != 0xFFD8) { // SOI (Start of Image) + throw new Error("SOI not found"); + } + + fileMarker = readUint16(); + while (fileMarker != 0xFFD9) { // EOI (End of image) + var i, j, l; + switch(fileMarker) { + case 0xFF00: break; + case 0xFFE0: // APP0 (Application Specific) + case 0xFFE1: // APP1 + case 0xFFE2: // APP2 + case 0xFFE3: // APP3 + case 0xFFE4: // APP4 + case 0xFFE5: // APP5 + case 0xFFE6: // APP6 + case 0xFFE7: // APP7 + case 0xFFE8: // APP8 + case 0xFFE9: // APP9 + case 0xFFEA: // APP10 + case 0xFFEB: // APP11 + case 0xFFEC: // APP12 + case 0xFFED: // APP13 + case 0xFFEE: // APP14 + case 0xFFEF: // APP15 + case 0xFFFE: // COM (Comment) + var appData = readDataBlock(); + + if (fileMarker === 0xFFFE) { + var comment = String.fromCharCode.apply(null, appData); + this.comments.push(comment); + } + + if (fileMarker === 0xFFE0) { + if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 && + appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00' + jfif = { + version: { major: appData[5], minor: appData[6] }, + densityUnits: appData[7], + xDensity: (appData[8] << 8) | appData[9], + yDensity: (appData[10] << 8) | appData[11], + thumbWidth: appData[12], + thumbHeight: appData[13], + thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13]) + }; + } + } + // TODO APP1 - Exif + if (fileMarker === 0xFFE1) { + if (appData[0] === 0x45 && + appData[1] === 0x78 && + appData[2] === 0x69 && + appData[3] === 0x66 && + appData[4] === 0) { // 'EXIF\x00' + this.exifBuffer = appData.subarray(5, appData.length); + } + } + + if (fileMarker === 0xFFEE) { + if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F && + appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00' + adobe = { + version: appData[6], + flags0: (appData[7] << 8) | appData[8], + flags1: (appData[9] << 8) | appData[10], + transformCode: appData[11] + }; + } + } + break; + + case 0xFFDB: // DQT (Define Quantization Tables) + var quantizationTablesLength = readUint16(); + var quantizationTablesEnd = quantizationTablesLength + offset - 2; + while (offset < quantizationTablesEnd) { + var quantizationTableSpec = data[offset++]; + requestMemoryAllocation(64 * 4); + var tableData = new Int32Array(64); + if ((quantizationTableSpec >> 4) === 0) { // 8 bit values + for (j = 0; j < 64; j++) { + var z = dctZigZag[j]; + tableData[z] = data[offset++]; + } + } else if ((quantizationTableSpec >> 4) === 1) { //16 bit + for (j = 0; j < 64; j++) { + var z = dctZigZag[j]; + tableData[z] = readUint16(); + } + } else + throw new Error("DQT: invalid table spec"); + quantizationTables[quantizationTableSpec & 15] = tableData; + } + break; + + case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT) + case 0xFFC1: // SOF1 (Start of Frame, Extended DCT) + case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT) + readUint16(); // skip data length + frame = {}; + frame.extended = (fileMarker === 0xFFC1); + frame.progressive = (fileMarker === 0xFFC2); + frame.precision = data[offset++]; + frame.scanLines = readUint16(); + frame.samplesPerLine = readUint16(); + frame.components = {}; + frame.componentsOrder = []; + + var pixelsInFrame = frame.scanLines * frame.samplesPerLine; + if (pixelsInFrame > maxResolutionInPixels) { + var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6); + throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`); + } + + var componentsCount = data[offset++], componentId; + var maxH = 0, maxV = 0; + for (i = 0; i < componentsCount; i++) { + componentId = data[offset]; + var h = data[offset + 1] >> 4; + var v = data[offset + 1] & 15; + var qId = data[offset + 2]; + + if ( h <= 0 || v <= 0 ) { + throw new Error('Invalid sampling factor, expected values above 0'); + } + + frame.componentsOrder.push(componentId); + frame.components[componentId] = { + h: h, + v: v, + quantizationIdx: qId + }; + offset += 3; + } + prepareComponents(frame); + frames.push(frame); + break; + + case 0xFFC4: // DHT (Define Huffman Tables) + var huffmanLength = readUint16(); + for (i = 2; i < huffmanLength;) { + var huffmanTableSpec = data[offset++]; + var codeLengths = new Uint8Array(16); + var codeLengthSum = 0; + for (j = 0; j < 16; j++, offset++) { + codeLengthSum += (codeLengths[j] = data[offset]); + } + requestMemoryAllocation(16 + codeLengthSum); + var huffmanValues = new Uint8Array(codeLengthSum); + for (j = 0; j < codeLengthSum; j++, offset++) + huffmanValues[j] = data[offset]; + i += 17 + codeLengthSum; + + ((huffmanTableSpec >> 4) === 0 ? + huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = + buildHuffmanTable(codeLengths, huffmanValues); + } + break; + + case 0xFFDD: // DRI (Define Restart Interval) + readUint16(); // skip data length + resetInterval = readUint16(); + break; + + case 0xFFDC: // Number of Lines marker + readUint16() // skip data length + readUint16() // Ignore this data since it represents the image height + break; + + case 0xFFDA: // SOS (Start of Scan) + var scanLength = readUint16(); + var selectorsCount = data[offset++]; + var components = [], component; + for (i = 0; i < selectorsCount; i++) { + component = frame.components[data[offset++]]; + var tableSpec = data[offset++]; + component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4]; + component.huffmanTableAC = huffmanTablesAC[tableSpec & 15]; + components.push(component); + } + var spectralStart = data[offset++]; + var spectralEnd = data[offset++]; + var successiveApproximation = data[offset++]; + var processed = decodeScan(data, offset, + frame, components, resetInterval, + spectralStart, spectralEnd, + successiveApproximation >> 4, successiveApproximation & 15, this.opts); + offset += processed; + break; + + case 0xFFFF: // Fill bytes + if (data[offset] !== 0xFF) { // Avoid skipping a valid marker. + offset--; + } + break; + default: + if (data[offset - 3] == 0xFF && + data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) { + // could be incorrect encoding -- last 0xFF byte of the previous + // block was eaten by the encoder + offset -= 3; + break; + } + else if (fileMarker === 0xE0 || fileMarker == 0xE1) { + // Recover from malformed APP1 markers popular in some phone models. + // See https://github.com/eugeneware/jpeg-js/issues/82 + if (malformedDataOffset !== -1) { + throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`); + } + malformedDataOffset = offset - 1; + const nextOffset = readUint16(); + if (data[offset + nextOffset - 2] === 0xFF) { + offset += nextOffset - 2; + break; + } + } + throw new Error("unknown JPEG marker " + fileMarker.toString(16)); + } + fileMarker = readUint16(); + } + if (frames.length != 1) + throw new Error("only single frame JPEGs supported"); + + // set each frame's components quantization table + for (var i = 0; i < frames.length; i++) { + var cp = frames[i].components; + for (var j in cp) { + cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx]; + delete cp[j].quantizationIdx; + } + } + + this.width = frame.samplesPerLine; + this.height = frame.scanLines; + this.jfif = jfif; + this.adobe = adobe; + this.components = []; + for (var i = 0; i < frame.componentsOrder.length; i++) { + var component = frame.components[frame.componentsOrder[i]]; + this.components.push({ + lines: buildComponentData(frame, component), + scaleX: component.h / frame.maxH, + scaleY: component.v / frame.maxV + }); + } + }, + getData: function getData(width, height) { + var scaleX = this.width / width, scaleY = this.height / height; + + var component1, component2, component3, component4; + var component1Line, component2Line, component3Line, component4Line; + var x, y; + var offset = 0; + var Y, Cb, Cr, K, C, M, Ye, R, G, B; + var colorTransform; + var dataLength = width * height * this.components.length; + requestMemoryAllocation(dataLength); + var data = new Uint8Array(dataLength); + switch (this.components.length) { + case 1: + component1 = this.components[0]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + + data[offset++] = Y; + } + } + break; + case 2: + // PDF might compress two component data in custom colorspace + component1 = this.components[0]; + component2 = this.components[1]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + data[offset++] = Y; + Y = component2Line[0 | (x * component2.scaleX * scaleX)]; + data[offset++] = Y; + } + } + break; + case 3: + // The default transform for three components is true + colorTransform = true; + // The adobe transform marker overrides any previous setting + if (this.adobe && this.adobe.transformCode) + colorTransform = true; + else if (typeof this.opts.colorTransform !== 'undefined') + colorTransform = !!this.opts.colorTransform; + + component1 = this.components[0]; + component2 = this.components[1]; + component3 = this.components[2]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; + component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + if (!colorTransform) { + R = component1Line[0 | (x * component1.scaleX * scaleX)]; + G = component2Line[0 | (x * component2.scaleX * scaleX)]; + B = component3Line[0 | (x * component3.scaleX * scaleX)]; + } else { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + Cb = component2Line[0 | (x * component2.scaleX * scaleX)]; + Cr = component3Line[0 | (x * component3.scaleX * scaleX)]; + + R = clampTo8bit(Y + 1.402 * (Cr - 128)); + G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); + B = clampTo8bit(Y + 1.772 * (Cb - 128)); + } + + data[offset++] = R; + data[offset++] = G; + data[offset++] = B; + } + } + break; + case 4: + if (!this.adobe) + throw new Error('Unsupported color mode (4 components)'); + // The default transform for four components is false + colorTransform = false; + // The adobe transform marker overrides any previous setting + if (this.adobe && this.adobe.transformCode) + colorTransform = true; + else if (typeof this.opts.colorTransform !== 'undefined') + colorTransform = !!this.opts.colorTransform; + + component1 = this.components[0]; + component2 = this.components[1]; + component3 = this.components[2]; + component4 = this.components[3]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; + component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)]; + component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + if (!colorTransform) { + C = component1Line[0 | (x * component1.scaleX * scaleX)]; + M = component2Line[0 | (x * component2.scaleX * scaleX)]; + Ye = component3Line[0 | (x * component3.scaleX * scaleX)]; + K = component4Line[0 | (x * component4.scaleX * scaleX)]; + } else { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + Cb = component2Line[0 | (x * component2.scaleX * scaleX)]; + Cr = component3Line[0 | (x * component3.scaleX * scaleX)]; + K = component4Line[0 | (x * component4.scaleX * scaleX)]; + + C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128)); + M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); + Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128)); + } + data[offset++] = 255-C; + data[offset++] = 255-M; + data[offset++] = 255-Ye; + data[offset++] = 255-K; + } + } + break; + default: + throw new Error('Unsupported color mode'); + } + return data; + }, + copyToImageData: function copyToImageData(imageData, formatAsRGBA) { + var width = imageData.width, height = imageData.height; + var imageDataArray = imageData.data; + var data = this.getData(width, height); + var i = 0, j = 0, x, y; + var Y, K, C, M, R, G, B; + switch (this.components.length) { + case 1: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + Y = data[i++]; + + imageDataArray[j++] = Y; + imageDataArray[j++] = Y; + imageDataArray[j++] = Y; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + case 3: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + R = data[i++]; + G = data[i++]; + B = data[i++]; + + imageDataArray[j++] = R; + imageDataArray[j++] = G; + imageDataArray[j++] = B; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + case 4: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + C = data[i++]; + M = data[i++]; + Y = data[i++]; + K = data[i++]; + + R = 255 - clampTo8bit(C * (1 - K / 255) + K); + G = 255 - clampTo8bit(M * (1 - K / 255) + K); + B = 255 - clampTo8bit(Y * (1 - K / 255) + K); + + imageDataArray[j++] = R; + imageDataArray[j++] = G; + imageDataArray[j++] = B; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + default: + throw new Error('Unsupported color mode'); + } + } + }; + + + // We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content. + var totalBytesAllocated = 0; + var maxMemoryUsageBytes = 0; + function requestMemoryAllocation(increaseAmount = 0) { + var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount; + if (totalMemoryImpactBytes > maxMemoryUsageBytes) { + var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024); + throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`); + } + + totalBytesAllocated = totalMemoryImpactBytes; + } + + constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) { + totalBytesAllocated = 0; + maxMemoryUsageBytes = maxMemoryUsageBytes_; + }; + + constructor.getBytesAllocated = function () { + return totalBytesAllocated; + }; + + constructor.requestMemoryAllocation = requestMemoryAllocation; + + return constructor; +})(); + +if (typeof module !== 'undefined') { + module.exports = decode; +} else if (typeof window !== 'undefined') { + window['jpeg-js'] = window['jpeg-js'] || {}; + window['jpeg-js'].decode = decode; +} + +function decode(jpegData, userOpts = {}) { + var defaultOpts = { + // "undefined" means "Choose whether to transform colors based on the image’s color model." + colorTransform: undefined, + useTArray: false, + formatAsRGBA: true, + tolerantDecoding: true, + maxResolutionInMP: 100, // Don't decode more than 100 megapixels + maxMemoryUsageInMB: 512, // Don't decode if memory footprint is more than 512MB + }; + + var opts = {...defaultOpts, ...userOpts}; + var arr = new Uint8Array(jpegData); + var decoder = new JpegImage(); + decoder.opts = opts; + // If this constructor ever supports async decoding this will need to be done differently. + // Until then, treating as singleton limit is fine. + JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024); + decoder.parse(arr); + + var channels = (opts.formatAsRGBA) ? 4 : 3; + var bytesNeeded = decoder.width * decoder.height * channels; + try { + JpegImage.requestMemoryAllocation(bytesNeeded); + var image = { + width: decoder.width, + height: decoder.height, + exifBuffer: decoder.exifBuffer, + data: opts.useTArray ? + new Uint8Array(bytesNeeded) : + Buffer.alloc(bytesNeeded) + }; + if(decoder.comments.length > 0) { + image["comments"] = decoder.comments; + } + } catch (err) { + if (err instanceof RangeError) { + throw new Error("Could not allocate enough memory for the image. " + + "Required: " + bytesNeeded); + } + + if (err instanceof ReferenceError) { + if (err.message === "Buffer is not defined") { + throw new Error("Buffer is not globally defined in this environment. " + + "Consider setting useTArray to true"); + } + } + throw err; + } + + decoder.copyToImageData(image, opts.formatAsRGBA); + + return image; +} diff --git a/node_modules/jpeg-js/lib/encoder.js b/node_modules/jpeg-js/lib/encoder.js new file mode 100644 index 00000000..fdbc1843 --- /dev/null +++ b/node_modules/jpeg-js/lib/encoder.js @@ -0,0 +1,814 @@ +/* + Copyright (c) 2008, Adobe Systems Incorporated + 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 Adobe Systems Incorporated nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* +JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009 + +Basic GUI blocking jpeg encoder +*/ + +var btoa = btoa || function(buf) { + return Buffer.from(buf).toString('base64'); +}; + +function JPEGEncoder(quality) { + var self = this; + var fround = Math.round; + var ffloor = Math.floor; + var YTable = new Array(64); + var UVTable = new Array(64); + var fdtbl_Y = new Array(64); + var fdtbl_UV = new Array(64); + var YDC_HT; + var UVDC_HT; + var YAC_HT; + var UVAC_HT; + + var bitcode = new Array(65535); + var category = new Array(65535); + var outputfDCTQuant = new Array(64); + var DU = new Array(64); + var byteout = []; + var bytenew = 0; + var bytepos = 7; + + var YDU = new Array(64); + var UDU = new Array(64); + var VDU = new Array(64); + var clt = new Array(256); + var RGB_YUV_TABLE = new Array(2048); + var currentQuality; + + var ZigZag = [ + 0, 1, 5, 6,14,15,27,28, + 2, 4, 7,13,16,26,29,42, + 3, 8,12,17,25,30,41,43, + 9,11,18,24,31,40,44,53, + 10,19,23,32,39,45,52,54, + 20,22,33,38,46,51,55,60, + 21,34,37,47,50,56,59,61, + 35,36,48,49,57,58,62,63 + ]; + + var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0]; + var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11]; + var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d]; + var std_ac_luminance_values = [ + 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12, + 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07, + 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, + 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0, + 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16, + 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, + 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39, + 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49, + 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, + 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69, + 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79, + 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, + 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98, + 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7, + 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, + 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5, + 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4, + 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, + 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea, + 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8, + 0xf9,0xfa + ]; + + var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0]; + var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11]; + var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77]; + var std_ac_chrominance_values = [ + 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21, + 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71, + 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, + 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0, + 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34, + 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, + 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38, + 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48, + 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, + 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68, + 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78, + 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, + 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96, + 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5, + 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, + 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3, + 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2, + 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, + 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9, + 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8, + 0xf9,0xfa + ]; + + function initQuantTables(sf){ + var YQT = [ + 16, 11, 10, 16, 24, 40, 51, 61, + 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, + 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68,109,103, 77, + 24, 35, 55, 64, 81,104,113, 92, + 49, 64, 78, 87,103,121,120,101, + 72, 92, 95, 98,112,100,103, 99 + ]; + + for (var i = 0; i < 64; i++) { + var t = ffloor((YQT[i]*sf+50)/100); + if (t < 1) { + t = 1; + } else if (t > 255) { + t = 255; + } + YTable[ZigZag[i]] = t; + } + var UVQT = [ + 17, 18, 24, 47, 99, 99, 99, 99, + 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, + 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99 + ]; + for (var j = 0; j < 64; j++) { + var u = ffloor((UVQT[j]*sf+50)/100); + if (u < 1) { + u = 1; + } else if (u > 255) { + u = 255; + } + UVTable[ZigZag[j]] = u; + } + var aasf = [ + 1.0, 1.387039845, 1.306562965, 1.175875602, + 1.0, 0.785694958, 0.541196100, 0.275899379 + ]; + var k = 0; + for (var row = 0; row < 8; row++) + { + for (var col = 0; col < 8; col++) + { + fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); + fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); + k++; + } + } + } + + function computeHuffmanTbl(nrcodes, std_table){ + var codevalue = 0; + var pos_in_table = 0; + var HT = new Array(); + for (var k = 1; k <= 16; k++) { + for (var j = 1; j <= nrcodes[k]; j++) { + HT[std_table[pos_in_table]] = []; + HT[std_table[pos_in_table]][0] = codevalue; + HT[std_table[pos_in_table]][1] = k; + pos_in_table++; + codevalue++; + } + codevalue*=2; + } + return HT; + } + + function initHuffmanTbl() + { + YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values); + UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values); + YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values); + UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values); + } + + function initCategoryNumber() + { + var nrlower = 1; + var nrupper = 2; + for (var cat = 1; cat <= 15; cat++) { + //Positive numbers + for (var nr = nrlower; nr>0] = 38470 * i; + RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000; + RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i; + RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i; + RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF; + RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i; + RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i; + } + } + + // IO functions + function writeBits(bs) + { + var value = bs[0]; + var posval = bs[1]-1; + while ( posval >= 0 ) { + if (value & (1 << posval) ) { + bytenew |= (1 << bytepos); + } + posval--; + bytepos--; + if (bytepos < 0) { + if (bytenew == 0xFF) { + writeByte(0xFF); + writeByte(0); + } + else { + writeByte(bytenew); + } + bytepos=7; + bytenew=0; + } + } + } + + function writeByte(value) + { + //byteout.push(clt[value]); // write char directly instead of converting later + byteout.push(value); + } + + function writeWord(value) + { + writeByte((value>>8)&0xFF); + writeByte((value )&0xFF); + } + + // DCT & quantization core + function fDCTQuant(data, fdtbl) + { + var d0, d1, d2, d3, d4, d5, d6, d7; + /* Pass 1: process rows. */ + var dataOff=0; + var i; + var I8 = 8; + var I64 = 64; + for (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0); + //outputfDCTQuant[i] = fround(fDCTQuant); + + } + return outputfDCTQuant; + } + + function writeAPP0() + { + writeWord(0xFFE0); // marker + writeWord(16); // length + writeByte(0x4A); // J + writeByte(0x46); // F + writeByte(0x49); // I + writeByte(0x46); // F + writeByte(0); // = "JFIF",'\0' + writeByte(1); // versionhi + writeByte(1); // versionlo + writeByte(0); // xyunits + writeWord(1); // xdensity + writeWord(1); // ydensity + writeByte(0); // thumbnwidth + writeByte(0); // thumbnheight + } + + function writeAPP1(exifBuffer) { + if (!exifBuffer) return; + + writeWord(0xFFE1); // APP1 marker + + if (exifBuffer[0] === 0x45 && + exifBuffer[1] === 0x78 && + exifBuffer[2] === 0x69 && + exifBuffer[3] === 0x66) { + // Buffer already starts with EXIF, just use it directly + writeWord(exifBuffer.length + 2); // length is buffer + length itself! + } else { + // Buffer doesn't start with EXIF, write it for them + writeWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\0 + length itself! + writeByte(0x45); // E + writeByte(0x78); // X + writeByte(0x69); // I + writeByte(0x66); // F + writeByte(0); // = "EXIF",'\0' + } + + for (var i = 0; i < exifBuffer.length; i++) { + writeByte(exifBuffer[i]); + } + } + + function writeSOF0(width, height) + { + writeWord(0xFFC0); // marker + writeWord(17); // length, truecolor YUV JPG + writeByte(8); // precision + writeWord(height); + writeWord(width); + writeByte(3); // nrofcomponents + writeByte(1); // IdY + writeByte(0x11); // HVY + writeByte(0); // QTY + writeByte(2); // IdU + writeByte(0x11); // HVU + writeByte(1); // QTU + writeByte(3); // IdV + writeByte(0x11); // HVV + writeByte(1); // QTV + } + + function writeDQT() + { + writeWord(0xFFDB); // marker + writeWord(132); // length + writeByte(0); + for (var i=0; i<64; i++) { + writeByte(YTable[i]); + } + writeByte(1); + for (var j=0; j<64; j++) { + writeByte(UVTable[j]); + } + } + + function writeDHT() + { + writeWord(0xFFC4); // marker + writeWord(0x01A2); // length + + writeByte(0); // HTYDCinfo + for (var i=0; i<16; i++) { + writeByte(std_dc_luminance_nrcodes[i+1]); + } + for (var j=0; j<=11; j++) { + writeByte(std_dc_luminance_values[j]); + } + + writeByte(0x10); // HTYACinfo + for (var k=0; k<16; k++) { + writeByte(std_ac_luminance_nrcodes[k+1]); + } + for (var l=0; l<=161; l++) { + writeByte(std_ac_luminance_values[l]); + } + + writeByte(1); // HTUDCinfo + for (var m=0; m<16; m++) { + writeByte(std_dc_chrominance_nrcodes[m+1]); + } + for (var n=0; n<=11; n++) { + writeByte(std_dc_chrominance_values[n]); + } + + writeByte(0x11); // HTUACinfo + for (var o=0; o<16; o++) { + writeByte(std_ac_chrominance_nrcodes[o+1]); + } + for (var p=0; p<=161; p++) { + writeByte(std_ac_chrominance_values[p]); + } + } + + function writeCOM(comments) + { + if (typeof comments === "undefined" || comments.constructor !== Array) return; + comments.forEach(e => { + if (typeof e !== "string") return; + writeWord(0xFFFE); // marker + var l = e.length; + writeWord(l + 2); // length itself as well + var i; + for (i = 0; i < l; i++) + writeByte(e.charCodeAt(i)); + }); + } + + function writeSOS() + { + writeWord(0xFFDA); // marker + writeWord(12); // length + writeByte(3); // nrofcomponents + writeByte(1); // IdY + writeByte(0); // HTY + writeByte(2); // IdU + writeByte(0x11); // HTU + writeByte(3); // IdV + writeByte(0x11); // HTV + writeByte(0); // Ss + writeByte(0x3f); // Se + writeByte(0); // Bf + } + + function processDU(CDU, fdtbl, DC, HTDC, HTAC){ + var EOB = HTAC[0x00]; + var M16zeroes = HTAC[0xF0]; + var pos; + var I16 = 16; + var I63 = 63; + var I64 = 64; + var DU_DCT = fDCTQuant(CDU, fdtbl); + //ZigZag reorder + for (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {}; + //end0pos = first element in reverse order !=0 + if ( end0pos == 0) { + writeBits(EOB); + return DC; + } + var i = 1; + var lng; + while ( i <= end0pos ) { + var startpos = i; + for (; (DU[i]==0) && (i<=end0pos); ++i) {} + var nrzeroes = i-startpos; + if ( nrzeroes >= I16 ) { + lng = nrzeroes>>4; + for (var nrmarker=1; nrmarker <= lng; ++nrmarker) + writeBits(M16zeroes); + nrzeroes = nrzeroes&0xF; + } + pos = 32767+DU[i]; + writeBits(HTAC[(nrzeroes<<4)+category[pos]]); + writeBits(bitcode[pos]); + i++; + } + if ( end0pos != I63 ) { + writeBits(EOB); + } + return DC; + } + + function initCharLookupTable(){ + var sfcc = String.fromCharCode; + for(var i=0; i < 256; i++){ ///// ACHTUNG // 255 + clt[i] = sfcc(i); + } + } + + this.encode = function(image,quality) // image data object + { + var time_start = new Date().getTime(); + + if(quality) setQuality(quality); + + // Initialize bit writer + byteout = new Array(); + bytenew=0; + bytepos=7; + + // Add JPEG headers + writeWord(0xFFD8); // SOI + writeAPP0(); + writeCOM(image.comments); + writeAPP1(image.exifBuffer); + writeDQT(); + writeSOF0(image.width,image.height); + writeDHT(); + writeSOS(); + + + // Encode 8x8 macroblocks + var DCY=0; + var DCU=0; + var DCV=0; + + bytenew=0; + bytepos=7; + + + this.encode.displayName = "_encode_"; + + var imageData = image.data; + var width = image.width; + var height = image.height; + + var quadWidth = width*4; + var tripleWidth = width*3; + + var x, y = 0; + var r, g, b; + var start,p, col,row,pos; + while(y < height){ + x = 0; + while(x < quadWidth){ + start = quadWidth * y + x; + p = start; + col = -1; + row = 0; + + for(pos=0; pos < 64; pos++){ + row = pos >> 3;// /8 + col = ( pos & 7 ) * 4; // %8 + p = start + ( row * quadWidth ) + col; + + if(y+row >= height){ // padding bottom + p-= (quadWidth*(y+1+row-height)); + } + + if(x+col >= quadWidth){ // padding right + p-= ((x+col) - quadWidth +4) + } + + r = imageData[ p++ ]; + g = imageData[ p++ ]; + b = imageData[ p++ ]; + + + /* // calculate YUV values dynamically + YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80 + UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b)); + VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b)); + */ + + // use lookup table (slightly faster) + YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128; + UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128; + VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128; + + } + + DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + x+=32; + } + y+=8; + } + + + //////////////////////////////////////////////////////////////// + + // Do the bit alignment of the EOI marker + if ( bytepos >= 0 ) { + var fillbits = []; + fillbits[1] = bytepos+1; + fillbits[0] = (1<<(bytepos+1))-1; + writeBits(fillbits); + } + + writeWord(0xFFD9); //EOI + + if (typeof module === 'undefined') return new Uint8Array(byteout); + return Buffer.from(byteout); + + var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join('')); + + byteout = []; + + // benchmarking + var duration = new Date().getTime() - time_start; + //console.log('Encoding time: '+ duration + 'ms'); + // + + return jpegDataUri + } + + function setQuality(quality){ + if (quality <= 0) { + quality = 1; + } + if (quality > 100) { + quality = 100; + } + + if(currentQuality == quality) return // don't recalc if unchanged + + var sf = 0; + if (quality < 50) { + sf = Math.floor(5000 / quality); + } else { + sf = Math.floor(200 - quality*2); + } + + initQuantTables(sf); + currentQuality = quality; + //console.log('Quality set to: '+quality +'%'); + } + + function init(){ + var time_start = new Date().getTime(); + if(!quality) quality = 50; + // Create tables + initCharLookupTable() + initHuffmanTbl(); + initCategoryNumber(); + initRGBYUVTable(); + + setQuality(quality); + var duration = new Date().getTime() - time_start; + //console.log('Initialization '+ duration + 'ms'); + } + + init(); + +}; + +if (typeof module !== 'undefined') { + module.exports = encode; +} else if (typeof window !== 'undefined') { + window['jpeg-js'] = window['jpeg-js'] || {}; + window['jpeg-js'].encode = encode; +} + +function encode(imgData, qu) { + if (typeof qu === 'undefined') qu = 50; + var encoder = new JPEGEncoder(qu); + var data = encoder.encode(imgData, qu); + return { + data: data, + width: imgData.width, + height: imgData.height, + }; +} + +// helper function to get the imageData of an existing image on the current page. +function getImageDataFromImage(idOrElement){ + var theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement; + var cvs = document.createElement('canvas'); + cvs.width = theImg.width; + cvs.height = theImg.height; + var ctx = cvs.getContext("2d"); + ctx.drawImage(theImg,0,0); + + return (ctx.getImageData(0, 0, cvs.width, cvs.height)); +} diff --git a/node_modules/jpeg-js/package.json b/node_modules/jpeg-js/package.json new file mode 100644 index 00000000..c19658cc --- /dev/null +++ b/node_modules/jpeg-js/package.json @@ -0,0 +1,32 @@ +{ + "name": "jpeg-js", + "version": "0.4.4", + "description": "A pure javascript JPEG encoder and decoder", + "main": "index.js", + "scripts": { + "test": "jest --testMatch=**/test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/eugeneware/jpeg-js" + }, + "keywords": [ + "jpeg", + "jpg", + "encoder", + "decoder", + "codec", + "image", + "javascript", + "js" + ], + "author": "Eugene Ware ", + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/eugeneware/jpeg-js/issues" + }, + "dependencies": {}, + "devDependencies": { + "jest": "^25.4.0" + } +} \ No newline at end of file diff --git a/node_modules/load-bmfont/LICENSE.md b/node_modules/load-bmfont/LICENSE.md new file mode 100644 index 00000000..9b10ce2a --- /dev/null +++ b/node_modules/load-bmfont/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) +Copyright (c) 2015 Jam3 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/load-bmfont/README.md b/node_modules/load-bmfont/README.md new file mode 100644 index 00000000..d424dffc --- /dev/null +++ b/node_modules/load-bmfont/README.md @@ -0,0 +1,61 @@ +# load-bmfont + +[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) + +Loads an [AngelCode BMFont](http://www.angelcode.com/products/bmfont/) file in browser (with XHR) and node (with fs and [phin](https://github.com/ethanent/phin)), returning a [JSON representation](json-spec.md). + +```js +var load = require("load-bmfont"); + +load("fonts/Arial-32.fnt", function (err, font) { + if (err) throw err; + + //The BMFont spec in JSON form + console.log(font.common.lineHeight); + console.log(font.info); + console.log(font.chars); + console.log(font.kernings); +}); +``` + +Currently supported BMFont formats: + +- ASCII (text) +- JSON +- XML +- binary + +## See Also + +See [text-modules](https://github.com/mattdesl/text-modules) for related modules. + +## Usage + +[![NPM](https://nodei.co/npm/load-bmfont.png)](https://www.npmjs.com/package/load-bmfont) + +#### `load(opt, cb)` + +Loads a BMFont file with the `opt` settings and fires the callback with `(err, font)` params once finished. If `opt` is a string, it is used as the URI. Otherwise the options can be: + +- `uri` or `url` the path (in Node) or URI +- `binary` boolean, whether the data should be read as binary, default false +- (in node) options for `fs.readFile` or [phin](https://www.npmjs.com/package/phin) +- (in browser) options for [xhr](https://github.com/Raynos/xhr) + +To support binary files in the browser and Node, you should use `binary: true`. Otherwise the XHR request might come in the form of a UTF8 string, which will not work with binary files. This also sets up the XHR object to override mime type in older browsers. + +```js +load( + { + uri: "fonts/Arial.bin", + binary: true, + }, + function (err, font) { + console.log(font); + } +); +``` + +## License + +MIT, see [LICENSE.md](http://github.com/Jam3/load-bmfont/blob/master/LICENSE.md) for details. diff --git a/node_modules/load-bmfont/browser.js b/node_modules/load-bmfont/browser.js new file mode 100644 index 00000000..57e8f323 --- /dev/null +++ b/node_modules/load-bmfont/browser.js @@ -0,0 +1,97 @@ +var xhr = require('xhr') +var noop = function(){} +var parseASCII = require('parse-bmfont-ascii') +var parseXML = require('parse-bmfont-xml') +var readBinary = require('parse-bmfont-binary') +var isBinaryFormat = require('./lib/is-binary') +var xtend = require('xtend') + +var xml2 = (function hasXML2() { + return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest +})() + +module.exports = function(opt, cb) { + cb = typeof cb === 'function' ? cb : noop + + if (typeof opt === 'string') + opt = { uri: opt } + else if (!opt) + opt = {} + + var expectBinary = opt.binary + if (expectBinary) + opt = getBinaryOpts(opt) + + xhr(opt, function(err, res, body) { + if (err) + return cb(err) + if (!/^2/.test(res.statusCode)) + return cb(new Error('http status code: '+res.statusCode)) + if (!body) + return cb(new Error('no body result')) + + var binary = false + + //if the response type is an array buffer, + //we need to convert it into a regular Buffer object + if (isArrayBuffer(body)) { + var array = new Uint8Array(body) + body = Buffer.from(array, 'binary') + } + + //now check the string/Buffer response + //and see if it has a binary BMF header + if (isBinaryFormat(body)) { + binary = true + //if we have a string, turn it into a Buffer + if (typeof body === 'string') + body = Buffer.from(body, 'binary') + } + + //we are not parsing a binary format, just ASCII/XML/etc + if (!binary) { + //might still be a buffer if responseType is 'arraybuffer' + if (Buffer.isBuffer(body)) + body = body.toString(opt.encoding) + body = body.trim() + } + + var result + try { + var type = res.headers['content-type'] + if (binary) + result = readBinary(body) + else if (/json/.test(type) || body.charAt(0) === '{') + result = JSON.parse(body) + else if (/xml/.test(type) || body.charAt(0) === '<') + result = parseXML(body) + else + result = parseASCII(body) + } catch (e) { + cb(new Error('error parsing font '+e.message)) + cb = noop + } + cb(null, result) + }) +} + +function isArrayBuffer(arr) { + var str = Object.prototype.toString + return str.call(arr) === '[object ArrayBuffer]' +} + +function getBinaryOpts(opt) { + //IE10+ and other modern browsers support array buffers + if (xml2) + return xtend(opt, { responseType: 'arraybuffer' }) + + if (typeof self.XMLHttpRequest === 'undefined') + throw new Error('your browser does not support XHR loading') + + //IE9 and XML1 browsers could still use an override + var req = new self.XMLHttpRequest() + req.overrideMimeType('text/plain; charset=x-user-defined') + return xtend({ + xhr: req + }, opt) +} diff --git a/node_modules/load-bmfont/index.js b/node_modules/load-bmfont/index.js new file mode 100644 index 00000000..f40ceacb --- /dev/null +++ b/node_modules/load-bmfont/index.js @@ -0,0 +1,57 @@ +var fs = require('fs') +var url = require('url') +var path = require('path') +var request = require('phin') +var parseASCII = require('parse-bmfont-ascii') +var parseXML = require('parse-bmfont-xml') +var readBinary = require('parse-bmfont-binary') +var mime = require('mime') +var noop = function() {} +var isBinary = require('./lib/is-binary') + +function parseFont(file, data, cb) { + var result, binary + + if (isBinary(data)) { + if (typeof data === 'string') data = Buffer.from(data, 'binary') + binary = true + } else data = data.toString().trim() + + try { + if (binary) result = readBinary(data) + else if (/json/.test(mime.lookup(file)) || data.charAt(0) === '{') + result = JSON.parse(data) + else if (/xml/.test(mime.lookup(file)) || data.charAt(0) === '<') + result = parseXML(data) + else result = parseASCII(data) + } catch (e) { + cb(e) + cb = noop + } + + cb(null, result) +} + +module.exports = function loadFont(opt, cb) { + cb = typeof cb === 'function' ? cb : noop + + if (typeof opt === 'string') opt = { uri: opt, url: opt } + else if (!opt) opt = {} + + var file = opt.uri || opt.url + + function handleData(err, data) { + if (err) return cb(err) + parseFont(file, data.body || data, cb) + } + + if (url.parse(file).host) { + request(opt).then(function (res) { + handleData(null, res) + }).catch(function (err) { + handleData(err) + }) + } else { + fs.readFile(file, opt, handleData) + } +} diff --git a/node_modules/load-bmfont/json-spec.md b/node_modules/load-bmfont/json-spec.md new file mode 100644 index 00000000..f33412fd --- /dev/null +++ b/node_modules/load-bmfont/json-spec.md @@ -0,0 +1,84 @@ +The spec for the JSON output is consistent with the rest of the [BMFont file spec](http://www.angelcode.com/products/bmfont/doc/file_format.html). + +Here is what a typical output looks like, omitting the full list of glyphs/kernings for brevity. + +```json +{ + "pages": [ + "sheet.png" + ], + "chars": [ + { + "id": 10, + "x": 281, + "y": 9, + "width": 0, + "height": 0, + "xoffset": 0, + "yoffset": 24, + "xadvance": 8, + "page": 0, + "chnl": 0 + }, + { + "id": 32, + "x": 0, + "y": 0, + "width": 0, + "height": 0, + "xoffset": 0, + "yoffset": 0, + "xadvance": 9, + "page": 0, + "chnl": 0 + }, + ... + ], + "kernings": [ + { + "first": 34, + "second": 65, + "amount": -2 + }, + { + "first": 34, + "second": 67, + "amount": 1 + }, + ... + ], + "info": { + "face": "Nexa Light", + "size": 32, + "bold": 0, + "italic": 0, + "charset": "", + "unicode": 1, + "stretchH": 100, + "smooth": 1, + "aa": 2, + "padding": [ + 0, + 0, + 0, + 0 + ], + "spacing": [ + 0, + 0 + ] + }, + "common": { + "lineHeight": 32, + "base": 24, + "scaleW": 1024, + "scaleH": 2048, + "pages": 1, + "packed": 0, + "alphaChnl": 0, + "redChnl": 0, + "greenChnl": 0, + "blueChnl": 0 + } +} +``` \ No newline at end of file diff --git a/node_modules/load-bmfont/lib/is-binary.js b/node_modules/load-bmfont/lib/is-binary.js new file mode 100644 index 00000000..5eb67904 --- /dev/null +++ b/node_modules/load-bmfont/lib/is-binary.js @@ -0,0 +1,8 @@ +var equal = require('buffer-equal') +var HEADER = Buffer.from([66, 77, 70, 3]) + +module.exports = function(buf) { + if (typeof buf === 'string') + return buf.substring(0, 3) === 'BMF' + return buf.length > 4 && equal(buf.slice(0, 4), HEADER) +} \ No newline at end of file diff --git a/node_modules/load-bmfont/package.json b/node_modules/load-bmfont/package.json new file mode 100644 index 00000000..270eaa45 --- /dev/null +++ b/node_modules/load-bmfont/package.json @@ -0,0 +1,55 @@ +{ + "name": "load-bmfont", + "version": "1.4.2", + "description": "loads a BMFont file in Node and the browser", + "main": "index.js", + "browser": "browser.js", + "license": "MIT", + "author": { + "name": "Matt DesLauriers", + "email": "dave.des@gmail.com", + "url": "https://github.com/mattdesl" + }, + "dependencies": { + "buffer-equal": "0.0.1", + "mime": "^1.3.4", + "parse-bmfont-ascii": "^1.0.3", + "parse-bmfont-binary": "^1.0.5", + "parse-bmfont-xml": "^1.1.4", + "phin": "^3.7.1", + "xhr": "^2.0.1", + "xtend": "^4.0.0" + }, + "devDependencies": { + "browserify": "^9.0.3", + "tap-spec": "^2.2.2", + "tape": "^3.5.0", + "testling": "^1.7.1" + }, + "scripts": { + "test-node": "(node test.js; node test-server.js) | tap-spec", + "test-browser": "browserify test.js | testling | tap-spec", + "test": "npm run test-node && npm run test-browser" + }, + "keywords": [ + "bmfont", + "bitmap", + "font", + "angel", + "code", + "angelcode", + "parse", + "ascii", + "xml", + "text", + "json" + ], + "repository": { + "type": "git", + "url": "git://github.com/Jam3/load-bmfont.git" + }, + "homepage": "https://github.com/Jam3/load-bmfont", + "bugs": { + "url": "https://github.com/Jam3/load-bmfont/issues" + } +} diff --git a/node_modules/load-bmfont/test-server.js b/node_modules/load-bmfont/test-server.js new file mode 100644 index 00000000..8510f6e7 --- /dev/null +++ b/node_modules/load-bmfont/test-server.js @@ -0,0 +1,26 @@ +var test = require('tape') +var load = require('./') +var expectedArial = require('./fnt/Arial.json') +var fs = require('fs') +var http = require('http') + +var arialBin = fs.readFileSync('fnt/Arial.bin') + +test('should load from server URL', function (t) { + t.plan(1) + + const server = http.createServer((req,res) => { + res.end(arialBin) + }) + + server.listen(8003, () => { + load({ + url: 'http://localhost:8003', + binary: true + }, (err, res) => { + if (err) t.fail(err) + else t.deepEqual(res, expectedArial) + server.close() + }) + }) +}) diff --git a/node_modules/min-document/.jshintrc b/node_modules/min-document/.jshintrc new file mode 100644 index 00000000..77887b5f --- /dev/null +++ b/node_modules/min-document/.jshintrc @@ -0,0 +1,30 @@ +{ + "maxdepth": 4, + "maxstatements": 200, + "maxcomplexity": 12, + "maxlen": 80, + "maxparams": 5, + + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": false, + "noarg": true, + "noempty": true, + "nonew": true, + "undef": true, + "unused": "vars", + "trailing": true, + + "quotmark": true, + "expr": true, + "asi": true, + + "browser": false, + "esnext": true, + "devel": false, + "node": false, + "nonstandard": false, + + "predef": ["require", "module", "__dirname", "__filename"] +} diff --git a/node_modules/min-document/.testem.json b/node_modules/min-document/.testem.json new file mode 100644 index 00000000..41ab90e6 --- /dev/null +++ b/node_modules/min-document/.testem.json @@ -0,0 +1,14 @@ +{ + "launchers": { + "node": { + "command": "node ./test" + } + }, + "src_files": [ + "./**/*.js" + ], + "before_tests": "npm run build-test", + "on_exit": "rm test/static/bundle.js", + "test_page": "test/static/index.html", + "launch_in_dev": ["node", "phantomjs"] +} diff --git a/node_modules/min-document/.travis.yml b/node_modules/min-document/.travis.yml new file mode 100644 index 00000000..52424f8d --- /dev/null +++ b/node_modules/min-document/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - 0.8 + - 0.9 + - 0.10 +script: node ./test/index.js diff --git a/node_modules/min-document/CONTRIBUTION.md b/node_modules/min-document/CONTRIBUTION.md new file mode 100644 index 00000000..4e78bdf7 --- /dev/null +++ b/node_modules/min-document/CONTRIBUTION.md @@ -0,0 +1,48 @@ +# This is an OPEN Open Source Project + +## What? + +Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project. + +## Rules + +There are a few basic ground-rules for contributors: + + - No --force pushes or modifying the Git history in any way. + - Non-master branches ought to be used for ongoing work. + - External API changes and significant modifications ought to be subject to an internal pull-request to solicit feedback from other contributors. + - Internal pull-requests to solicit feedback are encouraged for any other non-trivial contribution but left to the discretion of the contributor. + - For significant changes wait a full 24 hours before merging so that active contributors who are distributed throughout the world have a chance to weigh in. + - Contributors should attempt to adhere to the prevailing code-style. +Releases + +Declaring formal releases requires peer review. + + - A reviewer of a pull request should recommend a new version number (patch, minor or major). + - Once your change is merged feel free to bump the version as recommended by the reviewer. + - A new version number should not be cut without peer review unless done by the project maintainer. + +## Want to contribute? + +Even though collaborators may contribute as they see fit, if you are not sure what to do, here's a suggested process: + +## Cutting a new version + + - Get your branch merged on master + - Run `npm version major` or `npm version minor` or `npm version patch` + - `git push origin master --tags` + - If you are a project owner, then `npm publish` + +## If you want to have a bug fixed or a feature added: + + - Check open issues for what you want. + - If there is an open issue, comment on it, otherwise open an issue describing your bug or feature with use cases. + - Discussion happens on the issue about how to solve your problem. + - You or a core contributor opens a pull request solving the issue with tests and documentation. + - The pull requests gets reviewed and then merged. + - A new release version get's cut. + - (Disclaimer: Your feature might get rejected.) + +### Changes to this arrangement + +This is an experiment and feedback is welcome! This document may also be subject to pull-requests or changes by contributors where you believe you have something valuable to add or change. diff --git a/node_modules/min-document/LICENCE b/node_modules/min-document/LICENCE new file mode 100644 index 00000000..72d356c1 --- /dev/null +++ b/node_modules/min-document/LICENCE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Colingo. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/min-document/README.md b/node_modules/min-document/README.md new file mode 100644 index 00000000..970b47d2 --- /dev/null +++ b/node_modules/min-document/README.md @@ -0,0 +1,43 @@ +# min-document + +[![build status][1]][2] [![dependency status][3]][4] + + + +A minimal DOM implementation + +## Example + +```js +var document = require("min-document") + +var div = document.createElement("div") +div.className = "foo bar" + +var span = document.createElement("span") +div.appendChild(span) +span.textContent = "Hello!" + +/*
+ Hello! +
+*/ +var html = String(div) +``` + +## Installation + +`npm install min-document` + +## Contributors + + - Raynos + +## MIT Licenced + + [1]: https://secure.travis-ci.org/Raynos/min-document.png + [2]: https://travis-ci.org/Raynos/min-document + [3]: https://david-dm.org/Raynos/min-document.png + [4]: https://david-dm.org/Raynos/min-document + [5]: https://ci.testling.com/Raynos/min-document.png + [6]: https://ci.testling.com/Raynos/min-document diff --git a/node_modules/min-document/docs.mli b/node_modules/min-document/docs.mli new file mode 100644 index 00000000..ad17b4ae --- /dev/null +++ b/node_modules/min-document/docs.mli @@ -0,0 +1,156 @@ +type Comment := { + data: String, + length: Number, + nodeName: "#comment", + nodeType: 8, + nodeValue: String, + ownerDoucment: null | Document, + + toString: (this: Comment) => String +} + +type DOMText := { + data: String, + type: "DOMTextNode", + length: Number, + nodeType: 3, + + toString: (this: DOMText) => String, + replaceChild: ( + this: DOMText, + index: Number, + length: Number, + value: String + ) => void +} + +type DOMNode := DOMText | DOMElement | DocumentFragment +type DOMChild := DOMText | DOMElement + +type DOMElement := { + tagName: String, + className: String, + dataset: Object, + childNodes: Array, + parentNode: null | DOMElement, + style: Object, + type: "DOMElement", + nodeType: 1, + ownerDoucment: null | Document, + namespaceURI: null | String, + + appendChild: (this: DOMElement, child: DOMChild) => DOMChild, + replaceChild:( + this: DOMElement, + elem: DOMChild, + needle: DOMChild + ) => DOMChild, + removeChild: (this: DOMElement, child: DOMChild) => DOMChild, + insertBefore: ( + this: DOMElement, + elem: DOMChild, + needle: DOMChild | null | undefined + ) => DOMChild, + addEventListener: addEventListener, + dispatchEvent: dispatchEvent, + focus: () => void, + toString: (this: DOMElement) => String, + getElementsByClassName: ( + this: DOMElement, + className: String + ) => Array, + getElementsByTagName: ( + this: DOMElement, + tagName: String + ) => Array, +} + +type DocumentFragment := { + childNodes: Array, + parentNode: null | DOMElement, + type: "DocumentFragment", + nodeType: 11, + nodeName: "#document-fragment", + ownerDoucment: Document | null, + + appendChild: (this: DocumentFragment, child: DOMChild), + replaceChild: + (this: DocumentFragment, elem: DOMChild, needle: DOMChild), + removeChild: (this: DocumentFragment, child: DOMChild), + toString: (this: DocumentFragment) => String +} + +type Document := { + body: DOMElement, + childNodes: Array, + documentElement: DOMElement, + nodeType: 9, + + createComment: (this: Document, data: String) => Commment, + createTextNode: (this: Document, value: String) => DOMText, + createElement: (this: Document, tagName: String) => DOMElement, + createElementNS: ( + this: Document, + namespace: String | null, + tagName: String + ) => DOMElement, + createDocumentFragment: (this: Document) => DocumentFragment, + createEvent: () => Event, + getElementById: ( + this: Document, + id: String, + ) => null | DOMElement, + getElementsByClassName: ( + this: Document, + className: String + ) => Array, + getElementsByTagName: ( + this: Document, + tagName: String + ) => Array +} + +type Event := { + type: String, + bubbles: Boolean, + cancelable: Boolean, + + initEvent: ( + this: Event, + type: String, + bubbles: Boolean, + cancelable: Boolean + ) => void +} + +type addEventListener := ( + this: DOMElement, + type: String, + listener: Listener +) => void + +type dispatchEvent := ( + this: DOMElement, + ev: Event +) + +min-document/event/add-event-listener := addEventListener + +min-document/event/dispatch-event := dispatchEvent + +min-document/document := () => Document + +min-document/dom-element := + (tagName: String, owner?: Document, namespace?: String | null) => DOMElement + +min-document/dom-fragment := + (owner?: Document) => DocumentFragment + +min-document/dom-text := + (value: String, owner?: Document) => DOMText + +min-document/event := () => Event + +min-document/serialize := (DOMElement) => String + +min-document := Document diff --git a/node_modules/min-document/document.js b/node_modules/min-document/document.js new file mode 100644 index 00000000..d929cbd5 --- /dev/null +++ b/node_modules/min-document/document.js @@ -0,0 +1,72 @@ +var domWalk = require("dom-walk") + +var Comment = require("./dom-comment.js") +var DOMText = require("./dom-text.js") +var DOMElement = require("./dom-element.js") +var DocumentFragment = require("./dom-fragment.js") +var Event = require("./event.js") +var dispatchEvent = require("./event/dispatch-event.js") +var addEventListener = require("./event/add-event-listener.js") +var removeEventListener = require("./event/remove-event-listener.js") + +module.exports = Document; + +function Document() { + if (!(this instanceof Document)) { + return new Document(); + } + + this.head = this.createElement("head") + this.body = this.createElement("body") + this.documentElement = this.createElement("html") + this.documentElement.appendChild(this.head) + this.documentElement.appendChild(this.body) + this.childNodes = [this.documentElement] + this.nodeType = 9 +} + +var proto = Document.prototype; +proto.createTextNode = function createTextNode(value) { + return new DOMText(value, this) +} + +proto.createElementNS = function createElementNS(namespace, tagName) { + var ns = namespace === null ? null : String(namespace) + return new DOMElement(tagName, this, ns) +} + +proto.createElement = function createElement(tagName) { + return new DOMElement(tagName, this) +} + +proto.createDocumentFragment = function createDocumentFragment() { + return new DocumentFragment(this) +} + +proto.createEvent = function createEvent(family) { + return new Event(family) +} + +proto.createComment = function createComment(data) { + return new Comment(data, this) +} + +proto.getElementById = function getElementById(id) { + id = String(id) + + var result = domWalk(this.childNodes, function (node) { + if (String(node.id) === id) { + return node + } + }) + + return result || null +} + +proto.getElementsByClassName = DOMElement.prototype.getElementsByClassName +proto.getElementsByTagName = DOMElement.prototype.getElementsByTagName +proto.contains = DOMElement.prototype.contains + +proto.removeEventListener = removeEventListener +proto.addEventListener = addEventListener +proto.dispatchEvent = dispatchEvent diff --git a/node_modules/min-document/dom-comment.js b/node_modules/min-document/dom-comment.js new file mode 100644 index 00000000..132ea373 --- /dev/null +++ b/node_modules/min-document/dom-comment.js @@ -0,0 +1,19 @@ +module.exports = Comment + +function Comment(data, owner) { + if (!(this instanceof Comment)) { + return new Comment(data, owner) + } + + this.data = data + this.nodeValue = data + this.length = data.length + this.ownerDocument = owner || null +} + +Comment.prototype.nodeType = 8 +Comment.prototype.nodeName = "#comment" + +Comment.prototype.toString = function _Comment_toString() { + return "[object Comment]" +} diff --git a/node_modules/min-document/dom-element.js b/node_modules/min-document/dom-element.js new file mode 100644 index 00000000..48783264 --- /dev/null +++ b/node_modules/min-document/dom-element.js @@ -0,0 +1,213 @@ +var domWalk = require("dom-walk") +var dispatchEvent = require("./event/dispatch-event.js") +var addEventListener = require("./event/add-event-listener.js") +var removeEventListener = require("./event/remove-event-listener.js") +var serializeNode = require("./serialize.js") + +var htmlns = "http://www.w3.org/1999/xhtml" + +module.exports = DOMElement + +function DOMElement(tagName, owner, namespace) { + if (!(this instanceof DOMElement)) { + return new DOMElement(tagName) + } + + var ns = namespace === undefined ? htmlns : (namespace || null) + + this.tagName = ns === htmlns ? String(tagName).toUpperCase() : tagName + this.nodeName = this.tagName + this.className = "" + this.dataset = {} + this.childNodes = [] + this.parentNode = null + this.style = {} + this.ownerDocument = owner || null + this.namespaceURI = ns + this._attributes = {} + + if (this.tagName === 'INPUT') { + this.type = 'text' + } +} + +DOMElement.prototype.type = "DOMElement" +DOMElement.prototype.nodeType = 1 + +DOMElement.prototype.appendChild = function _Element_appendChild(child) { + if (child.parentNode) { + child.parentNode.removeChild(child) + } + + this.childNodes.push(child) + child.parentNode = this + + return child +} + +DOMElement.prototype.replaceChild = + function _Element_replaceChild(elem, needle) { + // TODO: Throw NotFoundError if needle.parentNode !== this + + if (elem.parentNode) { + elem.parentNode.removeChild(elem) + } + + var index = this.childNodes.indexOf(needle) + + needle.parentNode = null + this.childNodes[index] = elem + elem.parentNode = this + + return needle + } + +DOMElement.prototype.removeChild = function _Element_removeChild(elem) { + // TODO: Throw NotFoundError if elem.parentNode !== this + + var index = this.childNodes.indexOf(elem) + this.childNodes.splice(index, 1) + + elem.parentNode = null + return elem +} + +DOMElement.prototype.insertBefore = + function _Element_insertBefore(elem, needle) { + // TODO: Throw NotFoundError if referenceElement is a dom node + // and parentNode !== this + + if (elem.parentNode) { + elem.parentNode.removeChild(elem) + } + + var index = needle === null || needle === undefined ? + -1 : + this.childNodes.indexOf(needle) + + if (index > -1) { + this.childNodes.splice(index, 0, elem) + } else { + this.childNodes.push(elem) + } + + elem.parentNode = this + return elem + } + +DOMElement.prototype.setAttributeNS = + function _Element_setAttributeNS(namespace, name, value) { + var prefix = null + var localName = name + var colonPosition = name.indexOf(":") + if (colonPosition > -1) { + prefix = name.substr(0, colonPosition) + localName = name.substr(colonPosition + 1) + } + if (this.tagName === 'INPUT' && name === 'type') { + this.type = value; + } + else { + var attributes = this._attributes[namespace] || (this._attributes[namespace] = {}) + attributes[localName] = {value: value, prefix: prefix} + } + } + +DOMElement.prototype.getAttributeNS = + function _Element_getAttributeNS(namespace, name) { + var attributes = this._attributes[namespace]; + var value = attributes && attributes[name] && attributes[name].value + if (this.tagName === 'INPUT' && name === 'type') { + return this.type; + } + if (typeof value !== "string") { + return null + } + return value + } + +DOMElement.prototype.removeAttributeNS = + function _Element_removeAttributeNS(namespace, name) { + // Prevent prototype pollution by checking if namespace is a direct property + if (!Object.prototype.hasOwnProperty.call(this._attributes, namespace)) { + return; + } + var attributes = this._attributes[namespace]; + if (attributes && Object.prototype.hasOwnProperty.call(attributes, name)) { + delete attributes[name]; + } + } + +DOMElement.prototype.hasAttributeNS = + function _Element_hasAttributeNS(namespace, name) { + var attributes = this._attributes[namespace] + return !!attributes && name in attributes; + } + +DOMElement.prototype.setAttribute = function _Element_setAttribute(name, value) { + return this.setAttributeNS(null, name, value) +} + +DOMElement.prototype.getAttribute = function _Element_getAttribute(name) { + return this.getAttributeNS(null, name) +} + +DOMElement.prototype.removeAttribute = function _Element_removeAttribute(name) { + return this.removeAttributeNS(null, name) +} + +DOMElement.prototype.hasAttribute = function _Element_hasAttribute(name) { + return this.hasAttributeNS(null, name) +} + +DOMElement.prototype.removeEventListener = removeEventListener +DOMElement.prototype.addEventListener = addEventListener +DOMElement.prototype.dispatchEvent = dispatchEvent + +// Un-implemented +DOMElement.prototype.focus = function _Element_focus() { + return void 0 +} + +DOMElement.prototype.toString = function _Element_toString() { + return serializeNode(this) +} + +DOMElement.prototype.getElementsByClassName = function _Element_getElementsByClassName(classNames) { + var classes = classNames.split(" "); + var elems = [] + + domWalk(this, function (node) { + if (node.nodeType === 1) { + var nodeClassName = node.className || "" + var nodeClasses = nodeClassName.split(" ") + + if (classes.every(function (item) { + return nodeClasses.indexOf(item) !== -1 + })) { + elems.push(node) + } + } + }) + + return elems +} + +DOMElement.prototype.getElementsByTagName = function _Element_getElementsByTagName(tagName) { + tagName = tagName.toLowerCase() + var elems = [] + + domWalk(this.childNodes, function (node) { + if (node.nodeType === 1 && (tagName === '*' || node.tagName.toLowerCase() === tagName)) { + elems.push(node) + } + }) + + return elems +} + +DOMElement.prototype.contains = function _Element_contains(element) { + return domWalk(this, function (node) { + return element === node + }) || false +} diff --git a/node_modules/min-document/dom-fragment.js b/node_modules/min-document/dom-fragment.js new file mode 100644 index 00000000..d4bac92f --- /dev/null +++ b/node_modules/min-document/dom-fragment.js @@ -0,0 +1,28 @@ +var DOMElement = require("./dom-element.js") + +module.exports = DocumentFragment + +function DocumentFragment(owner) { + if (!(this instanceof DocumentFragment)) { + return new DocumentFragment() + } + + this.childNodes = [] + this.parentNode = null + this.ownerDocument = owner || null +} + +DocumentFragment.prototype.type = "DocumentFragment" +DocumentFragment.prototype.nodeType = 11 +DocumentFragment.prototype.nodeName = "#document-fragment" + +DocumentFragment.prototype.appendChild = DOMElement.prototype.appendChild +DocumentFragment.prototype.replaceChild = DOMElement.prototype.replaceChild +DocumentFragment.prototype.removeChild = DOMElement.prototype.removeChild + +DocumentFragment.prototype.toString = + function _DocumentFragment_toString() { + return this.childNodes.map(function (node) { + return String(node) + }).join("") + } diff --git a/node_modules/min-document/dom-text.js b/node_modules/min-document/dom-text.js new file mode 100644 index 00000000..4a6c6b92 --- /dev/null +++ b/node_modules/min-document/dom-text.js @@ -0,0 +1,27 @@ +module.exports = DOMText + +function DOMText(value, owner) { + if (!(this instanceof DOMText)) { + return new DOMText(value) + } + + this.data = value || "" + this.length = this.data.length + this.ownerDocument = owner || null +} + +DOMText.prototype.type = "DOMTextNode" +DOMText.prototype.nodeType = 3 +DOMText.prototype.nodeName = "#text" + +DOMText.prototype.toString = function _Text_toString() { + return this.data +} + +DOMText.prototype.replaceData = function replaceData(index, length, value) { + var current = this.data + var left = current.substring(0, index) + var right = current.substring(index + length, current.length) + this.data = left + value + right + this.length = this.data.length +} diff --git a/node_modules/min-document/event.js b/node_modules/min-document/event.js new file mode 100644 index 00000000..0a989c3d --- /dev/null +++ b/node_modules/min-document/event.js @@ -0,0 +1,13 @@ +module.exports = Event + +function Event(family) {} + +Event.prototype.initEvent = function _Event_initEvent(type, bubbles, cancelable) { + this.type = type + this.bubbles = bubbles + this.cancelable = cancelable +} + +Event.prototype.preventDefault = function _Event_preventDefault() { + +} diff --git a/node_modules/min-document/event/add-event-listener.js b/node_modules/min-document/event/add-event-listener.js new file mode 100644 index 00000000..022c7ef4 --- /dev/null +++ b/node_modules/min-document/event/add-event-listener.js @@ -0,0 +1,17 @@ +module.exports = addEventListener + +function addEventListener(type, listener) { + var elem = this + + if (!elem.listeners) { + elem.listeners = {} + } + + if (!elem.listeners[type]) { + elem.listeners[type] = [] + } + + if (elem.listeners[type].indexOf(listener) === -1) { + elem.listeners[type].push(listener) + } +} diff --git a/node_modules/min-document/event/dispatch-event.js b/node_modules/min-document/event/dispatch-event.js new file mode 100644 index 00000000..8febc990 --- /dev/null +++ b/node_modules/min-document/event/dispatch-event.js @@ -0,0 +1,31 @@ +module.exports = dispatchEvent + +function dispatchEvent(ev) { + var elem = this + var type = ev.type + + if (!ev.target) { + ev.target = elem + } + + if (!elem.listeners) { + elem.listeners = {} + } + + var listeners = elem.listeners[type] + + if (listeners) { + return listeners.forEach(function (listener) { + ev.currentTarget = elem + if (typeof listener === 'function') { + listener(ev) + } else { + listener.handleEvent(ev) + } + }) + } + + if (elem.parentNode) { + elem.parentNode.dispatchEvent(ev) + } +} diff --git a/node_modules/min-document/event/remove-event-listener.js b/node_modules/min-document/event/remove-event-listener.js new file mode 100644 index 00000000..d96091bc --- /dev/null +++ b/node_modules/min-document/event/remove-event-listener.js @@ -0,0 +1,19 @@ +module.exports = removeEventListener + +function removeEventListener(type, listener) { + var elem = this + + if (!elem.listeners) { + return + } + + if (!elem.listeners[type]) { + return + } + + var list = elem.listeners[type] + var index = list.indexOf(listener) + if (index !== -1) { + list.splice(index, 1) + } +} diff --git a/node_modules/min-document/index.js b/node_modules/min-document/index.js new file mode 100644 index 00000000..0d97e8ef --- /dev/null +++ b/node_modules/min-document/index.js @@ -0,0 +1,3 @@ +var Document = require('./document.js'); + +module.exports = new Document(); diff --git a/node_modules/min-document/package.json b/node_modules/min-document/package.json new file mode 100644 index 00000000..6b95b360 --- /dev/null +++ b/node_modules/min-document/package.json @@ -0,0 +1,53 @@ +{ + "name": "min-document", + "version": "2.19.2", + "description": "A minimal DOM implementation", + "keywords": [], + "author": "Raynos ", + "repository": "git://github.com/Raynos/min-document.git", + "main": "index.js", + "homepage": "https://github.com/Raynos/min-document", + "contributors": [ + { + "name": "Raynos" + } + ], + "bugs": { + "url": "https://github.com/Raynos/min-document/issues", + "email": "raynos2@gmail.com" + }, + "dependencies": { + "dom-walk": "^0.1.0" + }, + "devDependencies": { + "run-browser": "git://github.com/Raynos/run-browser", + "tap-dot": "^0.2.1", + "tap-spec": "^0.1.8", + "tape": "^2.12.3" + }, + "license": "MIT", + "scripts": { + "test": "node ./test/index.js | tap-spec", + "dot": "node ./test/index.js | tap-dot", + "cover": "istanbul cover --report none --print detail ./test/index.js", + "view-cover": "istanbul report html && google-chrome ./coverage/index.html", + "browser": "run-browser test/index.js", + "phantom": "run-browser test/index.js -b | tap-spec" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/min-document/serialize.js b/node_modules/min-document/serialize.js new file mode 100644 index 00000000..4411d3c3 --- /dev/null +++ b/node_modules/min-document/serialize.js @@ -0,0 +1,139 @@ +module.exports = serializeNode + +var voidElements = ["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"]; + +function serializeNode(node) { + switch (node.nodeType) { + case 3: + return escapeText(node.data) + case 8: + return "" + default: + return serializeElement(node) + } +} + +function serializeElement(elem) { + var strings = [] + + var tagname = elem.tagName + + if (elem.namespaceURI === "http://www.w3.org/1999/xhtml") { + tagname = tagname.toLowerCase() + } + + strings.push("<" + tagname + properties(elem) + datasetify(elem)) + + if (voidElements.indexOf(tagname) > -1) { + strings.push(" />") + } else { + strings.push(">") + + if (elem.childNodes.length) { + strings.push.apply(strings, elem.childNodes.map(serializeNode)) + } else if (elem.textContent || elem.innerText) { + strings.push(escapeText(elem.textContent || elem.innerText)) + } else if (elem.innerHTML) { + strings.push(elem.innerHTML) + } + + strings.push("") + } + + return strings.join("") +} + +function isProperty(elem, key) { + var type = typeof elem[key] + + if (key === "style" && Object.keys(elem.style).length > 0) { + return true + } + + return elem.hasOwnProperty(key) && + (type === "string" || type === "boolean" || type === "number") && + key !== "nodeName" && key !== "className" && key !== "tagName" && + key !== "textContent" && key !== "innerText" && key !== "namespaceURI" && key !== "innerHTML" +} + +function stylify(styles) { + if (typeof styles === 'string') return styles + var attr = "" + Object.keys(styles).forEach(function (key) { + var value = styles[key] + key = key.replace(/[A-Z]/g, function(c) { + return "-" + c.toLowerCase(); + }) + attr += key + ":" + value + ";" + }) + return attr +} + +function datasetify(elem) { + var ds = elem.dataset + var props = [] + + for (var key in ds) { + props.push({ name: "data-" + key, value: ds[key] }) + } + + return props.length ? stringify(props) : "" +} + +function stringify(list) { + var attributes = [] + list.forEach(function (tuple) { + var name = tuple.name + var value = tuple.value + + if (name === "style") { + value = stylify(value) + } + + attributes.push(name + "=" + "\"" + escapeAttributeValue(value) + "\"") + }) + + return attributes.length ? " " + attributes.join(" ") : "" +} + +function properties(elem) { + var props = [] + for (var key in elem) { + if (isProperty(elem, key)) { + props.push({ name: key, value: elem[key] }) + } + } + + for (var ns in elem._attributes) { + for (var attribute in elem._attributes[ns]) { + var prop = elem._attributes[ns][attribute] + var name = (prop.prefix ? prop.prefix + ":" : "") + attribute + props.push({ name: name, value: prop.value }) + } + } + + if (elem.className) { + props.push({ name: "class", value: elem.className }) + } + + return props.length ? stringify(props) : "" +} + +function escapeText(s) { + var str = ''; + + if (typeof(s) === 'string') { + str = s; + } else if (s) { + str = s.toString(); + } + + return str + .replace(/&/g, "&") + .replace(//g, ">") +} + +function escapeAttributeValue(str) { + return escapeText(str).replace(/"/g, """) +} diff --git a/node_modules/min-document/test/cleanup.js b/node_modules/min-document/test/cleanup.js new file mode 100644 index 00000000..d3ae66ab --- /dev/null +++ b/node_modules/min-document/test/cleanup.js @@ -0,0 +1,13 @@ +module.exports = Cleanup + +function Cleanup (document) { + + return cleanup + + function cleanup () { + var childNodes = document.body.childNodes + for (var i = 0; i < childNodes.length; i++) { + document.body.removeChild(childNodes[i]) + } + } +} diff --git a/node_modules/min-document/test/index.js b/node_modules/min-document/test/index.js new file mode 100644 index 00000000..14b736a1 --- /dev/null +++ b/node_modules/min-document/test/index.js @@ -0,0 +1,14 @@ +var testDocument = require("./test-document") +var testDomElement = require("./test-dom-element") +var testDomComment = require("./test-dom-comment") +var document = require("../index") + +testDocument(document) +testDomElement(document) +testDomComment(document) + +if (typeof window !== "undefined" && window.document) { + testDocument(window.document) + testDomElement(window.document) + testDomComment(window.document) +} diff --git a/node_modules/min-document/test/static/index.html b/node_modules/min-document/test/static/index.html new file mode 100644 index 00000000..60f6ef8b --- /dev/null +++ b/node_modules/min-document/test/static/index.html @@ -0,0 +1,11 @@ + + + + TAPE Example + + + + + + + diff --git a/node_modules/min-document/test/static/test-adapter.js b/node_modules/min-document/test/static/test-adapter.js new file mode 100644 index 00000000..c5127925 --- /dev/null +++ b/node_modules/min-document/test/static/test-adapter.js @@ -0,0 +1,49 @@ +(function () { + var Testem = window.Testem + var regex = /^((?:not )?ok) (\d+) (.+)$/ + + Testem.useCustomAdapter(tapAdapter) + + function tapAdapter(socket){ + var results = { + failed: 0 + , passed: 0 + , total: 0 + , tests: [] + } + + socket.emit('tests-start') + + Testem.handleConsoleMessage = function(msg){ + var m = msg.match(regex) + if (m) { + var passed = m[1] === 'ok' + var test = { + passed: passed ? 1 : 0, + failed: passed ? 0 : 1, + total: 1, + id: m[2], + name: m[3], + items: [] + } + + if (passed) { + results.passed++ + } else { + results.failed++ + } + + results.total++ + + socket.emit('test-result', test) + results.tests.push(test) + } else if (msg === '# ok' || msg.match(/^# tests \d+/)){ + socket.emit('all-test-results', results) + } + + // return false if you want to prevent the console message from + // going to the console + // return false + } + } +}()) diff --git a/node_modules/min-document/test/test-document.js b/node_modules/min-document/test/test-document.js new file mode 100644 index 00000000..282d9df7 --- /dev/null +++ b/node_modules/min-document/test/test-document.js @@ -0,0 +1,564 @@ +var test = require("tape") + +module.exports = testDocument + +function testDocument(document) { + var cleanup = require('./cleanup')(document) + var Event = require('../event'); + + test("document is a Document", function (assert) { + assert.equal(typeof document.createTextNode, "function") + assert.equal(typeof document.createElement, "function") + assert.equal(typeof document.createDocumentFragment, "function") + + assert.end() + }) + + test("document has a head property", function(assert) { + assert.equal(document.head.tagName, "HEAD") + assert.end() + }) + + test("document has nodeType 9", function (assert) { + assert.equal(document.nodeType, 9) + assert.end() + }) + + test("can do stuff", function (assert) { + var div = document.createElement("div") + div.className = "foo bar" + + var span = document.createElement("span") + div.appendChild(span) + span.textContent = "Hello! <&>" + + var html = String(div.outerHTML || div) + + assert.equal(html, "
" + + "Hello! <&>
") + + cleanup() + assert.end() + }) + + test("can createDocumentFragment", function (assert) { + var frag = document.createDocumentFragment() + + assert.equal(frag.nodeType, 11) + + var h1 = document.createElement("h1") + var h2 = document.createElement("h2") + + assert.equal(h1.nodeType, 1) + assert.equal(h1.nodeType, 1) + + frag.appendChild(h1) + assert.equal(fragString(frag), "

") + + frag.appendChild(h2) + assert.equal(fragString(frag), "

") + + frag.removeChild(h1) + assert.equal(fragString(frag), "

") + + frag.replaceChild(h1, h2) + assert.equal(fragString(frag), "

") + + cleanup() + assert.end() + }) + + test("can getElementById", function (assert) { + + function append_div(id, parent) { + var div = document.createElement("div") + div.id = id + parent.appendChild(div) + return div + } + + var div1 = append_div(1, document.body) + var div2 = append_div(2, document.body) + var div3 = append_div(3, document.body) + + var div11 = append_div(11, div1) + var div12 = append_div(12, div1) + var div21 = append_div(21, div2) + var div22 = append_div(22, div2) + var div221 = append_div(221, div22) + var div222 = append_div(222, div22) + + assert.equal(document.getElementById(1), div1) + assert.equal(document.getElementById("2"), div2) + assert.equal(document.getElementById(3), div3) + assert.equal(document.getElementById(11), div11) + assert.equal(document.getElementById(12), div12) + assert.equal(document.getElementById(21), div21) + assert.equal(document.getElementById(22), div22) + assert.equal(document.getElementById(221), div221) + assert.equal(document.getElementById(222), div222) + + cleanup() + assert.end() + }) + + test("can getElementsByClassName for a single class", function(assert) { + function append_div(className, parent) { + var div = document.createElement("div") + div.className = className + parent.appendChild(div) + return div + } + + function assertSingleMatch(className, expectedElement) { + var result = document.getElementsByClassName(className) + assert.equal(result.length, 1) + assert.equal(result[0], expectedElement) + } + + var divA = append_div("A", document.body) + var divB = append_div("B", document.body) + var divC = append_div("C", document.body) + + var divA1 = append_div("A1", divA) + var divA2 = append_div("A2", divA) + var divB1 = append_div("B1", divB) + var divB2 = append_div("B2", divB) + var divB2a = append_div("B2a", divB2) + var divB2b = append_div("B2b", divB2) + + assertSingleMatch("A", divA) + assertSingleMatch("B", divB) + assertSingleMatch("C", divC) + assertSingleMatch("A1", divA1) + assertSingleMatch("A2", divA2) + assertSingleMatch("B1", divB1) + assertSingleMatch("B2", divB2) + assertSingleMatch("B2a", divB2a) + assertSingleMatch("B2b", divB2b) + + cleanup() + assert.end() + }) + + test("can getElementsByClassName for many elements", function (assert) { + function h(className) { + var div = document.createElement("div") + div.className = className + return div + } + + document.body.appendChild(h("multi-class-bar")) + document.body.appendChild(h("multi-class-bar")) + + var elems = document.getElementsByClassName("multi-class-bar") + assert.equal(elems.length, 2) + + cleanup() + assert.end() + }) + + test("can getElementsByClassName for many classes", function(assert) { + function append_div(classNames, parent) { + var div = document.createElement("div") + div.className = classNames + parent.appendChild(div) + return div + } + + function assertMatch(classNames, expectedElements) { + var result = document.getElementsByClassName(classNames) + assert.equal(result.length, expectedElements.length) + for (var i = 0; i < expectedElements.length; i++) { + assert.notEqual(expectedElements.indexOf(result[i]), -1) + } + } + + var divXYZ = append_div("X Y Z", document.body) + var divYZ = append_div("Y Z", document.body) + var divZX = append_div("Z X", document.body) + + var divX1X2 = append_div("X1 X2", divXYZ) + var divX1X2Y1 = append_div("X1 X2 Y1", divXYZ) + + + assertMatch("X", [divXYZ, divZX]) + assertMatch("Y Z", [divXYZ, divYZ]) + assertMatch("X Y Z", [divXYZ]) + assertMatch("X1 X2", [divX1X2, divX1X2Y1]) + + cleanup() + assert.end() + }) + + test("can create/manipulate textnodes", function (assert) { + var textnode = document.createTextNode("hello") + + assert.equal(textnode.nodeType, 3) + assert.equal(textnode.data, "hello") + assert.equal(typeof textnode.replaceData, "function") + + textnode.replaceData(0, 7, "nightly") + assert.equal(textnode.nodeType, 3) + assert.equal(textnode.data, "nightly") + assert.equal(typeof textnode.replaceData, "function") + + textnode.replaceData(1, 1, "ou") + assert.equal(textnode.nodeType, 3) + assert.equal(textnode.data, "noughtly") + + assert.end() + }) + + test("owner document is set", function (assert) { + var textnode = document.createTextNode("hello") + var domnode = document.createElement("div") + var fragment = document.createDocumentFragment() + + assert.equal(textnode.ownerDocument, document) + assert.equal(domnode.ownerDocument, document) + assert.equal(fragment.ownerDocument, document) + + assert.end() + }) + + test("Create namespaced nodes", function (assert) { + var svgURI = "http://www.w3.org/2000/svg" + var htmlURI = "http://www.w3.org/1999/xhtml" + + var noNS = document.createElement("div") + var svgNS = document.createElementNS(svgURI, "svg") + var emptyNS = document.createElementNS("", "div") + var nullNS = document.createElementNS(null, "div") + var undefNS = document.createElementNS(undefined, "div") + var caseNS = document.createElementNS("Oops", "AbC") + var htmlNS = document.createElement("div") + + assert.equal(noNS.tagName, "DIV") + assert.equal(noNS.namespaceURI, htmlURI) + assert.equal(elemString(noNS), "
") + + assert.equal(svgNS.tagName, "svg") + assert.equal(svgNS.namespaceURI, svgURI) + assert.equal(elemString(svgNS), "") + + assert.equal(emptyNS.tagName, "div") + assert.equal(emptyNS.namespaceURI, null) + assert.equal(elemString(emptyNS), "
") + + assert.equal(nullNS.tagName, "div") + assert.equal(nullNS.namespaceURI, null) + assert.equal(elemString(nullNS), "
") + + assert.equal(undefNS.tagName, "div") + assert.equal(undefNS.namespaceURI, "undefined") + assert.equal(elemString(undefNS), "
") + + assert.equal(caseNS.tagName, "AbC") + assert.equal(caseNS.namespaceURI, "Oops") + assert.equal(elemString(caseNS), "") + + assert.equal(htmlNS.tagName, "DIV") + assert.equal(htmlNS.namespaceURI, htmlURI) + assert.equal(elemString(htmlNS), "
") + + assert.end() + }) + + test("Can insert before", function (assert) { + var rootNode = document.createElement("div") + var child = document.createElement("div") + var newElement = document.createElement("div") + rootNode.appendChild(child) + var el = rootNode.insertBefore(newElement, child) + assert.equal(el, newElement) + assert.equal(rootNode.childNodes.length, 2) + assert.equal(rootNode.childNodes[0], newElement) + assert.equal(rootNode.childNodes[1], child) + cleanup() + assert.end() + }) + + test("Insert before null appends to end", function (assert) { + var rootNode = document.createElement("div") + var child = document.createElement("div") + var newElement = document.createElement("div") + rootNode.appendChild(child) + var el = rootNode.insertBefore(newElement, null) + assert.equal(el, newElement) + assert.equal(rootNode.childNodes.length, 2) + assert.equal(rootNode.childNodes[0], child) + assert.equal(rootNode.childNodes[1], newElement) + cleanup() + assert.end() + }) + + test("Node insertions remove node from parent", function (assert) { + var parent = document.createElement("div") + var c1 = document.createElement("div") + var c2 = document.createElement("div") + var c3 = document.createElement("div") + parent.appendChild(c1) + parent.appendChild(c2) + parent.appendChild(c3) + + var rootNode = document.createElement("div") + + var node1 = rootNode.appendChild(c1) + assert.equal(node1, c1) + assert.equal(parent.childNodes.length, 2) + assert.equal(c1.parentNode, rootNode) + + var node2 = rootNode.insertBefore(c2, c1) + assert.equal(node2, c2) + assert.equal(parent.childNodes.length, 1) + assert.equal(c2.parentNode, rootNode) + + var node3 = rootNode.replaceChild(c3, c2) + assert.equal(node3, c2) + assert.equal(parent.childNodes.length, 0) + assert.equal(c3.parentNode, rootNode) + assert.equal(c2.parentNode, null) + + cleanup() + assert.end() + }) + + test("input has type=text by default", function (assert) { + var elem = document.createElement("input") + assert.equal(elem.getAttribute("type"), "text"); + assert.equal(elemString(elem), "") + assert.end() + }) + + test("input type=text can be overridden", function (assert) { + var elem = document.createElement("input") + elem.setAttribute("type", "hidden") + assert.equal(elem.getAttribute("type"), "hidden"); + assert.equal(elemString(elem), "") + assert.end() + }) + + test("can set and get attributes", function (assert) { + var elem = document.createElement("div") + assert.equal(elem.getAttribute("foo"), null) + assert.equal(elemString(elem), "
") + assert.notOk(elem.hasAttribute('foo')) + + elem.setAttribute("foo", "bar") + assert.equal(elem.getAttribute("foo"), "bar") + assert.equal(elemString(elem), "
") + assert.ok(elem.hasAttribute('foo')) + + elem.removeAttribute("foo") + assert.equal(elem.getAttribute("foo"), null) + assert.equal(elemString(elem), "
") + assert.notOk(elem.hasAttribute('foo')) + + assert.end() + }) + + test("can set and set style properties", function(assert) { + var elem = document.createElement("div") + assert.equal(elemString(elem), "
") + + elem.style.color = "red"; + assert.equal(elem.style.color, "red") + assert.equal(elemString(elem), "
") + + elem.style.background = "blue"; + assert.equal(elem.style.color, "red") + assert.equal(elem.style.background, "blue") + assert.equal(elemString(elem), + "
") + + assert.end() + }) + + test("can set and get namespaced attributes", function(assert) { + var elem = document.createElement("div") + + var ns = "http://ns.com/my" + assert.equal(elem.getAttributeNS(ns, "myattr"), blankAttributeNS()) + elem.setAttributeNS(ns, "myns:myattr", "the value") + assert.equal(elem.getAttributeNS(ns, "myattr"), "the value") + assert.equal(elemString(elem), '
') + elem.removeAttributeNS(ns, "myattr") + assert.equal(elem.getAttributeNS(ns, "myattr"), blankAttributeNS()) + + // Should work much like get/setAttribute when namespace is null. + assert.equal(elem.getAttributeNS(null, "foo"), blankAttributeNS()) + assert.equal(elem.getAttribute("foo"), null) + elem.setAttributeNS(null, "foo", "bar") + assert.equal(elem.getAttributeNS(null, "foo"), "bar") + assert.equal(elem.getAttribute("foo"), "bar") + elem.removeAttributeNS(null, "foo") + assert.equal(elem.getAttributeNS(null, "foo"), blankAttributeNS()) + assert.equal(elem.getAttribute("foo"), null) + assert.end() + }) + + test("can getElementsByTagName", function(assert) { + var parent = document.createElement("div") + var child1 = document.createElement("span") + var child2 = document.createElement("span") + + child1.id = "foo" + child2.id = "bar" + + child1.appendChild(child2) + parent.appendChild(child1) + document.body.appendChild(parent) + + var elems = document.getElementsByTagName("SPAN") + + assert.equal(elems.length, 2) + assert.equal(elems[0].id, "foo") + assert.equal(elems[1].id, "bar") + + cleanup() + assert.end() + }) + + test("can getElementsByTagName with *", function(assert) { + document.body.appendChild(document.createElement("div")) + + var elems = document.getElementsByTagName("*") + + assert.equal(elems.length, 4) + assert.equal(elems[0].tagName, "HTML") + assert.equal(elems[1].tagName, "HEAD") + assert.equal(elems[2].tagName, "BODY") + assert.equal(elems[3].tagName, "DIV") + + cleanup() + assert.end() + }) + + test("getElement* methods search outside the body", function(assert) { + var html = document.documentElement; + assert.equal(document.getElementsByTagName("html")[0], html) + + html.id = "foo" + assert.equal(document.getElementById("foo"), html) + + html.className = "bar" + assert.equal(document.getElementsByClassName("bar")[0], html) + + // cleanup + html.id = "" + html.className = "" + + cleanup() + assert.end() + }) + + test("getElement* methods can be passed to map()", function(assert) { + var e1 = document.createElement("div") + var e2 = document.createElement("span") + + document.body.appendChild(e1) + document.body.appendChild(e2) + + assert.deepEqual( + ["div", "span"].map(document.getElementsByTagName.bind(document)), + [[e1], [e2]] + ) + + e1.id = "1" + e2.id = "2" + + assert.deepEqual( + ["1", "2"].map(document.getElementById.bind(document)), + [e1, e2] + ) + + e1.className = "foo" + e2.className = "bar" + + assert.deepEqual( + ["foo", "bar"].map(document.getElementsByClassName.bind(document)), + [[e1], [e2]] + ) + + cleanup() + assert.end() + }) + + test("can check if it contains an element", function(assert) { + var el = document.createElement("div") + document.body.appendChild(el) + + assert.equals(document.contains(document.body), true) + assert.equals(document.contains(el), true) + + cleanup() + assert.end() + }) + + test("can do events", function (assert) { + var x = 1 + function incx() { x++ } + + var ev = new Event(); + ev.initEvent("click"); + document.addEventListener("click", incx) + document.dispatchEvent(ev) + + assert.equal(x, 2) + + document.removeEventListener("click", incx) + document.dispatchEvent(ev) + + assert.equal(x, 2) + assert.end() + }) + + function blankAttributeNS() { + // Most browsers conform to the latest version of the DOM spec, + // which requires `getAttributeNS` to return `null` when the attribute + // doesn't exist, but some browsers (including phantomjs) implement the + // old version of the spec and return an empty string instead, see: + // https://developer.mozilla.org/en-US/docs/Web/API/element.getAttributeNS#Return_value + var div = document.createElement("div") + var blank = div.getAttributeNS(null, "foo") + if (!(blank === null || blank === "")) { + throw "Expected blank attribute to be either null or empty string" + } + return blank; + } + + function elemString(element) { + var html = String(element) || "[]" + + if (html.charAt(0) === "[") { + html = element.outerHTML + if (!html && !element.parentNode) { + var div = document.createElement("div") + div.appendChild(element) + html = div.innerHTML + div.removeChild(element) + } + } + + return html + } + + function fragString(fragment) { + var html = String(fragment) + + + if (html === "[object DocumentFragment]") { + var innerHTML = [] + for (var i = 0; i < fragment.childNodes.length; i++) { + var node = fragment.childNodes[i] + innerHTML.push(String(node.outerHTML || node)) + } + html = innerHTML.join("") + } + + return html + } +} + + diff --git a/node_modules/min-document/test/test-dom-comment.js b/node_modules/min-document/test/test-dom-comment.js new file mode 100644 index 00000000..7ecf175e --- /dev/null +++ b/node_modules/min-document/test/test-dom-comment.js @@ -0,0 +1,20 @@ +var test = require("tape") + +module.exports = testDomComment + +function testDomComment(document) { + var cleanup = require('./cleanup')(document) + + test("can createComment", function(assert) { + var comment = document.createComment("test") + assert.equal(comment.data, "test") + assert.equal(comment.length, 4) + assert.equal(comment.nodeName, "#comment") + assert.equal(comment.nodeType, 8) + assert.equal(comment.nodeValue, "test") + assert.equal(comment.ownerDocument, document) + assert.equal(comment.toString(), "[object Comment]") + cleanup() + assert.end() + }) +} diff --git a/node_modules/min-document/test/test-dom-element.js b/node_modules/min-document/test/test-dom-element.js new file mode 100644 index 00000000..b7f2baab --- /dev/null +++ b/node_modules/min-document/test/test-dom-element.js @@ -0,0 +1,219 @@ +var test = require("tape") + +module.exports = testDomElement + +function testDomElement(document) { + + var cleanup = require('./cleanup')(document) + + test("can getElementsByClassName", function(assert) { + function append_div(classNames, parent) { + var div = document.createElement("div") + div.className = classNames + parent.appendChild(div) + return div + } + + function assertMatch(classNames, expectedElements, parent) { + var parent = parent || document + var result = parent.getElementsByClassName(classNames) + assert.equal(result.length, expectedElements.length) + for (var i = 0; i < expectedElements.length; i++) { + assert.notEqual(expectedElements.indexOf(result[i]), -1) + } + } + + var divA = append_div("A", document.body) + var divB = append_div("B", document.body) + var divC = append_div("C", document.body) + + var divA1 = append_div("A1", divA) + var divA2 = append_div("A2", divA) + var divB1 = append_div("B1", divB) + var divB2 = append_div("B2", divB) + var divB2a = append_div("B2a", divB2) + var divB2b = append_div("B2b", divB2) + + assertMatch("A", [divA]) + assertMatch("B", [divB]) + assertMatch("C", [divC]) + assertMatch("A1", [divA1]) + assertMatch("A2", [divA2]) + assertMatch("B1", [divB1]) + assertMatch("B2", [divB2]) + assertMatch("B2a", [divB2a]) + assertMatch("B2b", [divB2b]) + + assertMatch("A1", [divA1], divA) + assertMatch("A2", [divA2], divA) + assertMatch("A1", [], divB) + assertMatch("A2", [], divC) + assertMatch("B1", [divB1], divB) + assertMatch("B2", [divB2], divB) + assertMatch("B2a", [divB2a], divB) + assertMatch("B2a", [divB2a], divB2) + assertMatch("B2b", [], divA) + + cleanup() + assert.end() + }) + + test("does not serialize innerText as an attribute", function(assert) { + var div = document.createElement("div") + div.innerText = "Test <&>" + assert.equal(div.toString(), "
Test <&>
") + cleanup() + assert.end() + }) + + test("does not serialize innerHTML as an attribute", function(assert) { + var div = document.createElement("div") + div.innerHTML = "Test " + assert.equal(div.toString(), "
Test
") + cleanup() + assert.end() + }) + + test("can getElementsByTagName", function(assert) { + var parent = document.createElement("div") + var child1 = document.createElement("span") + var child2 = document.createElement("span") + + child1.id = "foo" + child2.id = "bar" + + child1.appendChild(child2) + parent.appendChild(child1) + + var elems = parent.getElementsByTagName("SPAN") + + assert.equal(elems.length, 2) + assert.equal(elems[0].id, "foo") + assert.equal(elems[1].id, "bar") + + cleanup() + assert.end() + }) + + test("can getElementsByTagName with *", function(assert) { + var e1 = document.createElement("div") + var e2 = document.createElement("p") + var e3 = document.createElement("span") + + e1.appendChild(e2) + e2.appendChild(e3) + // non-elements should be ignored + e3.appendChild(document.createTextNode('foo')) + e3.appendChild(document.createComment('bar')) + + var elems = e1.getElementsByTagName("*") + + assert.equal(elems.length, 2) + assert.equal(elems[0].tagName, "P") + assert.equal(elems[1].tagName, "SPAN") + + cleanup() + assert.end() + }) + + test("getElement* methods can be passed to map()", function(assert) { + var container = document.createElement("div") + var e1 = document.createElement("div") + var e2 = document.createElement("span") + container.appendChild(e1) + container.appendChild(e2) + + assert.deepEqual( + ["div", "span"].map(container.getElementsByTagName.bind(container)), + [[e1], [e2]] + ) + + e1.className = "foo" + e2.className = "bar" + + assert.deepEqual( + ["foo", "bar"].map(container.getElementsByClassName.bind(container)), + [[e1], [e2]] + ) + + cleanup() + assert.end() + }) + + test("can serialize comment nodes", function(assert) { + var div = document.createElement("div") + div.appendChild(document.createComment("test")) + assert.equal(div.toString(), "
") + cleanup() + assert.end() + }) + + test("can serialize style property", function(assert) { + var div = document.createElement("div") + div.style.fontSize = "16px" + assert.equal(div.toString(), "
") + cleanup(); + assert.end() + }) + + test("can serialize style as a string", function(assert) { + var div = document.createElement("div") + div.setAttribute('style', 'display: none') + assert.equal(div.toString(), "
") + cleanup() + assert.end() + }) + + test("can serialize text nodes", function(assert) { + var div = document.createElement("div") + div.appendChild(document.createTextNode(' "&')) + assert.equal(div.toString(), '
<test> "&
') + cleanup() + assert.end() + }) + + test("escapes serialized attribute values", function(assert) { + var div = document.createElement("div") + div.setAttribute("data-foo", '

"&') + assert.equal(div.toString(), '

') + cleanup() + assert.end() + }) + + test("can check if an element contains another", function(assert) { + var parent = document.createElement("div") + var sibling = document.createElement("div") + var child1 = document.createElement("div") + var child2 = document.createElement("div") + + child1.appendChild(child2) + parent.appendChild(child1) + + assert.equal(parent.contains(parent), true) + assert.equal(parent.contains(sibling), false) + assert.equal(parent.contains(child1), true) + assert.equal(parent.contains(child2), true) + + cleanup() + assert.end() + }) + + test("can handle non string attribute values", function(assert) { + var div = document.createElement("div") + div.setAttribute("data-number", 100) + div.setAttribute("data-boolean", true) + div.setAttribute("data-null", null) + assert.equal(div.toString(), '
') + cleanup() + assert.end() + }) + + test("can serialize textarea correctly", function(assert) { + var input = document.createElement("textarea") + input.setAttribute("name", "comment") + input.innerHTML = "user input here" + assert.equal(input.toString(), '') + cleanup() + assert.end() + }) +} diff --git a/node_modules/node-fetch/LICENSE.md b/node_modules/node-fetch/LICENSE.md new file mode 100644 index 00000000..660ffecb --- /dev/null +++ b/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/node-fetch/README.md b/node_modules/node-fetch/README.md new file mode 100644 index 00000000..55f09b7f --- /dev/null +++ b/node_modules/node-fetch/README.md @@ -0,0 +1,634 @@ +node-fetch +========== + +[![npm version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] +[![Discord][discord-image]][discord-url] + +A light-weight module that brings `window.fetch` to Node.js + +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) + +[![Backers][opencollective-image]][opencollective-url] + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Buffer](#buffer) + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file stream](#post-data-using-a-file-stream) + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Class: Request](#class-request) + - [Class: Response](#class-response) + - [Class: Headers](#class-headers) + - [Interface: Body](#interface-body) + - [Class: FetchError](#class-fetcherror) +- [License](#license) +- [Acknowledgement](#acknowledgement) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise but allow substituting it with [insert your favorite promise library]. +- Use native Node streams for body on both request and response. +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. + +## Difference from client-side fetch + +- See [Known Differences](LIMITS.md) for details. +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`2.x`) + +```sh +$ npm install node-fetch +``` + +## Loading and configuring the module +We suggest you load the module via `require` until the stabilization of ES modules in node: +```js +const fetch = require('node-fetch'); +``` + +If you are using a Promise library other than native, set it through `fetch.Promise`: +```js +const Bluebird = require('bluebird'); + +fetch.Promise = Bluebird; +``` + +## Common Usage + +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. + +#### Plain text or HTML +```js +fetch('https://github.com/') + .then(res => res.text()) + .then(body => console.log(body)); +``` + +#### JSON + +```js + +fetch('https://api.github.com/users/github') + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Simple Post +```js +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); +``` + +#### Post with JSON + +```js +const body = { a: 1 }; + +fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form parameters +`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: params }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Handling exceptions +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. + +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. + +```js +fetch('https://domain.invalid/') + .catch(err => console.error(err)); +``` + +#### Handling client and server errors +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +function checkStatus(res) { + if (res.ok) { // res.status >= 200 && res.status < 300 + return res; + } else { + throw MyCustomError(res.statusText); + } +} + +fetch('https://httpbin.org/status/400') + .then(checkStatus) + .then(res => console.log('will not get here...')) +``` + +## Advanced Usage + +#### Streams +The "Node.js way" is to use streams when possible: + +```js +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => { + const dest = fs.createWriteStream('./octocat.png'); + res.body.pipe(dest); + }); +``` + +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +const fetch = require('node-fetch'); +const response = await fetch('https://httpbin.org/stream/3'); +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +const fetch = require('node-fetch'); +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + +#### Buffer +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) + +```js +const fileType = require('file-type'); + +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => res.buffer()) + .then(buffer => fileType(buffer)) + .then(type => { /* ... */ }); +``` + +#### Accessing Headers and other Meta data +```js +fetch('https://github.com/') + .then(res => { + console.log(res.ok); + console.log(res.status); + console.log(res.statusText); + console.log(res.headers.raw()); + console.log(res.headers.get('content-type')); + }); +``` + +#### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +fetch(url).then(res => { + // returns an array of values, instead of a string of comma-separated values + console.log(res.headers.raw()['set-cookie']); +}); +``` + +#### Post data using a file stream + +```js +const { createReadStream } = require('fs'); + +const stream = createReadStream('input.txt'); + +fetch('https://httpbin.org/post', { method: 'POST', body: stream }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form-data (detect multipart) + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: form }) + .then(res => res.json()) + .then(json => console.log(json)); + +// OR, using custom headers +// NOTE: getHeaders() is non-standard API + +const form = new FormData(); +form.append('a', 1); + +const options = { + method: 'POST', + body: form, + headers: form.getHeaders() +} + +fetch('https://httpbin.org/post', options) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Request cancellation with AbortSignal + +> NOTE: You may cancel streamed requests only on Node >= v8.0.0 + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import AbortController from 'abort-controller'; + +const controller = new AbortController(); +const timeout = setTimeout( + () => { controller.abort(); }, + 150, +); + +fetch(url, { signal: controller.signal }) + .then(res => res.json()) + .then( + data => { + useData(data) + }, + err => { + if (err.name === 'AbortError') { + // request was aborted + } + }, + ) + .finally(() => { + clearTimeout(timeout); + }); +``` + +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. + + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream + redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null // http(s).Agent instance or function that returns an instance (see below) +} +``` + +##### Default Headers + +If no values are set, the following request headers will be sent automatically: + +Header | Value +------------------- | -------------------------------------------------------- +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ +`Accept` | `*/*` +`Content-Length` | _(automatically calculated, if possible)_ +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +##### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function (_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +} +``` + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `referrer` +- `referrerPolicy` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +*(spec-compliant)* + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options][#fetch-options] for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `Response.error()` +- `Response.redirect()` +- `type` +- `trailer` + +#### new Response([body[, options]]) + +*(spec-compliant)* + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +*(spec-compliant)* + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +*(spec-compliant)* + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +*(spec-compliant)* + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class + +const meta = { + 'Content-Type': 'text/xml', + 'Breaking-Bad': '<3' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [ + [ 'Content-Type', 'text/xml' ], + [ 'Breaking-Bad', '<3' ] +]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +meta.set('Breaking-Bad', '<3'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +The following methods are not yet implemented in node-fetch at this moment: + +- `formData()` + +#### body.body + +*(deviation from spec)* + +* Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +*(spec-compliant)* + +* `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() +#### body.blob() +#### body.json() +#### body.text() + +*(spec-compliant)* + +* Returns: Promise + +Consume the body and return a promise that will resolve to one of these formats. + +#### body.buffer() + +*(node-fetch extension)* + +* Returns: Promise<Buffer> + +Consume the body and return a promise that will resolve to a Buffer. + +#### body.textConverted() + +*(node-fetch extension)* + +* Returns: Promise<String> + +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. + +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) + + +### Class: FetchError + +*(node-fetch extension)* + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + +### Class: AbortError + +*(node-fetch extension)* + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). + +## License + +MIT + +[npm-image]: https://flat.badgen.net/npm/v/node-fetch +[npm-url]: https://www.npmjs.com/package/node-fetch +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch +[travis-url]: https://travis-ci.org/bitinn/node-fetch +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square +[discord-url]: https://discord.gg/Zxbndcm +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg +[opencollective-url]: https://opencollective.com/node-fetch +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md diff --git a/node_modules/node-fetch/browser.js b/node_modules/node-fetch/browser.js new file mode 100644 index 00000000..ee86265a --- /dev/null +++ b/node_modules/node-fetch/browser.js @@ -0,0 +1,25 @@ +"use strict"; + +// ref: https://github.com/tc39/proposal-global +var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +} + +var globalObject = getGlobal(); + +module.exports = exports = globalObject.fetch; + +// Needed for TypeScript and Webpack. +if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); +} + +exports.Headers = globalObject.Headers; +exports.Request = globalObject.Request; +exports.Response = globalObject.Response; diff --git a/node_modules/node-fetch/lib/index.es.js b/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 00000000..aae9799c --- /dev/null +++ b/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1777 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/lib/index.js b/node_modules/node-fetch/lib/index.js new file mode 100644 index 00000000..567ff5da --- /dev/null +++ b/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1787 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/node_modules/node-fetch/lib/index.mjs b/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 00000000..2863dd9c --- /dev/null +++ b/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1775 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/package.json b/node_modules/node-fetch/package.json new file mode 100644 index 00000000..e0be1768 --- /dev/null +++ b/node_modules/node-fetch/package.json @@ -0,0 +1,89 @@ +{ + "name": "node-fetch", + "version": "2.7.0", + "description": "A light-weight module that brings window.fetch to node.js", + "main": "lib/index.js", + "browser": "./browser.js", + "module": "lib/index.mjs", + "files": [ + "lib/index.js", + "lib/index.mjs", + "lib/index.es.js", + "browser.js" + ], + "engines": { + "node": "4.x || >=6.0.0" + }, + "scripts": { + "build": "cross-env BABEL_ENV=rollup rollup -c", + "prepare": "npm run build", + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js", + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js", + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitinn/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitinn/node-fetch/issues" + }, + "homepage": "https://github.com/bitinn/node-fetch", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + }, + "devDependencies": { + "@ungap/url-search-params": "^0.1.2", + "abort-controller": "^1.1.0", + "abortcontroller-polyfill": "^1.3.0", + "babel-core": "^6.26.3", + "babel-plugin-istanbul": "^4.1.6", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "1.4.0", + "babel-register": "^6.16.3", + "chai": "^3.5.0", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^1.1.1", + "chai-string": "~1.3.0", + "codecov": "3.3.0", + "cross-env": "^5.2.0", + "form-data": "^2.3.3", + "is-builtin-module": "^1.0.0", + "mocha": "^5.0.0", + "nyc": "11.9.0", + "parted": "^0.1.1", + "promise": "^8.0.3", + "resumer": "0.0.0", + "rollup": "^0.63.4", + "rollup-plugin-babel": "^3.0.7", + "string-to-arraybuffer": "^1.0.2", + "teeny-request": "3.7.0" + }, + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/node_modules/omggif/README b/node_modules/omggif/README new file mode 100644 index 00000000..a526f263 --- /dev/null +++ b/node_modules/omggif/README @@ -0,0 +1,24 @@ +omggif is a JavaScript implementation of a GIF 89a encoder and decoder. + +https://github.com/deanm/omggif + + +(c) Dean McNamee , 2013. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/omggif/example_node.js b/node_modules/omggif/example_node.js new file mode 100644 index 00000000..b3dadc2e --- /dev/null +++ b/node_modules/omggif/example_node.js @@ -0,0 +1,116 @@ +// (c) Dean McNamee , 2013. +// Node omggif example to write out a few example images. + +var fs = require('fs'); +var omggif = require('./omggif'); + +// Needs to be large enough for the final full file size. Can be any type of +// buffer that supports [] (an Array, Uint8Array, Node Buffer, etc). +var buf = new Buffer(1024 * 1024); + +function gen_static_global() { + var gf = new omggif.GifWriter(buf, 2, 2, {palette: [0xff0000, 0x0000ff]}); + gf.addFrame(0, 0, 2, 2, + [0, 1, 1, 0]); + return buf.slice(0, gf.end()); +} + +function gen_static_local() { + var gf = new omggif.GifWriter(buf, 2, 2); + gf.addFrame(0, 0, 2, 2, + [0, 1, 1, 0], + {palette: [0xff0000, 0x0000ff]}); + return buf.slice(0, gf.end()); +} + +function gen_anim() { + // The loop parameter is the number of times to loop, or 0 for forever. + // A value of 1 will play twice (first time, and then one loop time). + // To play only once do not specify loop or pass null. + var gf = new omggif.GifWriter(buf, 2, 2, {loop: 1}); + gf.addFrame(0, 0, 2, 2, + [0, 1, 1, 0], + {palette: [0xff0000, 0x0000ff]}); + gf.addFrame(0, 0, 2, 2, + [1, 0, 0, 1], + {palette: [0xff0000, 0x0000ff], + delay: 10}); // Delay in hundredths of a sec (100 = 1s). + return buf.slice(0, gf.end()); +} + +function gen_gray_strip() { + var gf = new omggif.GifWriter(buf, 256, 1); + var palette = [ ]; + var indices = [ ]; + for (var i = 0; i < 256; ++i) { + palette.push(i << 16 | i << 8 | i); + indices.push(i); + } + gf.addFrame(0, 0, 256, 1, indices, {palette: palette}); + return buf.slice(0, gf.end()); +} + +// More than 8-bit color (via tiling of several frames). Browsers seem to +// treat this as an animation though, with an enforced minimum time between +// frames which makes it animated instead of the intended static image. +function gen_color_strip() { + var gf = new omggif.GifWriter(buf, 256, 256, {palette: [0x000000, 0xff0000], + background: 1}); + + var indices = [ ]; + for (var i = 0; i < 256; ++i) indices.push(i); + + for (var j = 0; j < 256; ++j) { + var palette = [ ]; + for (var i = 0; i < 256; ++i) + palette.push(j << 16 | i << 8 | i); + gf.addFrame(0, j, 256, 1, indices, {palette: palette, disposal: 1}); + } + return buf.slice(0, gf.end()); +} + +// 1x1 white, generates the same as Google's 35 byte __utm.gif, except for some +// reason that I'm not sure of they set their background index to 255. +function gen_empty_white() { + var gf = new omggif.GifWriter(buf, 1, 1, {palette: [0xffffff, 0x000000]}); + gf.addFrame(0, 0, 1, 1, [0]); + return buf.slice(0, gf.end()); +} + +// 1x1 transparent 43 bytes. +function gen_empty_trans() { + var gf = new omggif.GifWriter(buf, 1, 1, {palette: [0x000000, 0x000000]}); + gf.addFrame(0, 0, 1, 1, [0], {transparent: 0}); + return buf.slice(0, gf.end()); +} + +// with lzw block of 256. +// see: https://github.com/deanm/omggif/issues/5 +function gen_block256() { + var width = 4840; + var gf = new omggif.GifWriter(buf, width, 1, { + palette: [0x000000, 0x000000, 0x000000, 0x000000, + 0x000000, 0x000000, 0x000000, 0x000000] + }); + var stream = Array(width); + for (var i = 0; i < width; ++i) stream[i] = i & 0x7; + gf.addFrame(0, 0, width, 1, stream, {transparent: 0}); + var data = buf.slice(0, gf.end()); + // Make sure it decodes. + var gr = new omggif.GifReader(data); + var fi0 = gr.frameInfo(0); + /* + console.log(fi0); + console.log(buf.slice(fi0.data_offset, fi0.data_offset + fi0.data_length)); + */ + return data; +} + +fs.writeFileSync('./test_static_global_palette.gif', gen_static_global()); +fs.writeFileSync('./test_static_local_palette.gif', gen_static_local()); +fs.writeFileSync('./test_anim.gif', gen_anim()); +fs.writeFileSync('./test_gray_strip.gif', gen_gray_strip()); +fs.writeFileSync('./test_color_strip.gif', gen_color_strip()); +fs.writeFileSync('./test_empty_white.gif', gen_empty_white()); +fs.writeFileSync('./test_empty_trans.gif', gen_empty_trans()); +fs.writeFileSync('./test_block256.gif', gen_block256()); diff --git a/node_modules/omggif/omggif.js b/node_modules/omggif/omggif.js new file mode 100644 index 00000000..4b814fb3 --- /dev/null +++ b/node_modules/omggif/omggif.js @@ -0,0 +1,807 @@ +// (c) Dean McNamee , 2013. +// +// https://github.com/deanm/omggif +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +// +// omggif is a JavaScript implementation of a GIF 89a encoder and decoder, +// including animation and compression. It does not rely on any specific +// underlying system, so should run in the browser, Node, or Plask. + +"use strict"; + +function GifWriter(buf, width, height, gopts) { + var p = 0; + + var gopts = gopts === undefined ? { } : gopts; + var loop_count = gopts.loop === undefined ? null : gopts.loop; + var global_palette = gopts.palette === undefined ? null : gopts.palette; + + if (width <= 0 || height <= 0 || width > 65535 || height > 65535) + throw new Error("Width/Height invalid."); + + function check_palette_and_num_colors(palette) { + var num_colors = palette.length; + if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) { + throw new Error( + "Invalid code/color length, must be power of 2 and 2 .. 256."); + } + return num_colors; + } + + // - Header. + buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF + buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a + + // Handling of Global Color Table (palette) and background index. + var gp_num_colors_pow2 = 0; + var background = 0; + if (global_palette !== null) { + var gp_num_colors = check_palette_and_num_colors(global_palette); + while (gp_num_colors >>= 1) ++gp_num_colors_pow2; + gp_num_colors = 1 << gp_num_colors_pow2; + --gp_num_colors_pow2; + if (gopts.background !== undefined) { + background = gopts.background; + if (background >= gp_num_colors) + throw new Error("Background index out of range."); + // The GIF spec states that a background index of 0 should be ignored, so + // this is probably a mistake and you really want to set it to another + // slot in the palette. But actually in the end most browsers, etc end + // up ignoring this almost completely (including for dispose background). + if (background === 0) + throw new Error("Background index explicitly passed as 0."); + } + } + + // - Logical Screen Descriptor. + // NOTE(deanm): w/h apparently ignored by implementations, but set anyway. + buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff; + buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff; + // NOTE: Indicates 0-bpp original color resolution (unused?). + buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag. + gp_num_colors_pow2; // NOTE: No sort flag (unused?). + buf[p++] = background; // Background Color Index. + buf[p++] = 0; // Pixel aspect ratio (unused?). + + // - Global Color Table + if (global_palette !== null) { + for (var i = 0, il = global_palette.length; i < il; ++i) { + var rgb = global_palette[i]; + buf[p++] = rgb >> 16 & 0xff; + buf[p++] = rgb >> 8 & 0xff; + buf[p++] = rgb & 0xff; + } + } + + if (loop_count !== null) { // Netscape block for looping. + if (loop_count < 0 || loop_count > 65535) + throw new Error("Loop count invalid.") + // Extension code, label, and length. + buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b; + // NETSCAPE2.0 + buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53; + buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45; + buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30; + // Sub-block + buf[p++] = 0x03; buf[p++] = 0x01; + buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff; + buf[p++] = 0x00; // Terminator. + } + + + var ended = false; + + this.addFrame = function(x, y, w, h, indexed_pixels, opts) { + if (ended === true) { --p; ended = false; } // Un-end. + + opts = opts === undefined ? { } : opts; + + // TODO(deanm): Bounds check x, y. Do they need to be within the virtual + // canvas width/height, I imagine? + if (x < 0 || y < 0 || x > 65535 || y > 65535) + throw new Error("x/y invalid.") + + if (w <= 0 || h <= 0 || w > 65535 || h > 65535) + throw new Error("Width/Height invalid.") + + if (indexed_pixels.length < w * h) + throw new Error("Not enough pixels for the frame size."); + + var using_local_palette = true; + var palette = opts.palette; + if (palette === undefined || palette === null) { + using_local_palette = false; + palette = global_palette; + } + + if (palette === undefined || palette === null) + throw new Error("Must supply either a local or global palette."); + + var num_colors = check_palette_and_num_colors(palette); + + // Compute the min_code_size (power of 2), destroying num_colors. + var min_code_size = 0; + while (num_colors >>= 1) ++min_code_size; + num_colors = 1 << min_code_size; // Now we can easily get it back. + + var delay = opts.delay === undefined ? 0 : opts.delay; + + // From the spec: + // 0 - No disposal specified. The decoder is + // not required to take any action. + // 1 - Do not dispose. The graphic is to be left + // in place. + // 2 - Restore to background color. The area used by the + // graphic must be restored to the background color. + // 3 - Restore to previous. The decoder is required to + // restore the area overwritten by the graphic with + // what was there prior to rendering the graphic. + // 4-7 - To be defined. + // NOTE(deanm): Dispose background doesn't really work, apparently most + // browsers ignore the background palette index and clear to transparency. + var disposal = opts.disposal === undefined ? 0 : opts.disposal; + if (disposal < 0 || disposal > 3) // 4-7 is reserved. + throw new Error("Disposal out of range."); + + var use_transparency = false; + var transparent_index = 0; + if (opts.transparent !== undefined && opts.transparent !== null) { + use_transparency = true; + transparent_index = opts.transparent; + if (transparent_index < 0 || transparent_index >= num_colors) + throw new Error("Transparent color index."); + } + + if (disposal !== 0 || use_transparency || delay !== 0) { + // - Graphics Control Extension + buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label. + buf[p++] = 4; // Byte size. + + buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0); + buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff; + buf[p++] = transparent_index; // Transparent color index. + buf[p++] = 0; // Block Terminator. + } + + // - Image Descriptor + buf[p++] = 0x2c; // Image Seperator. + buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left. + buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top. + buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff; + buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff; + // NOTE: No sort flag (unused?). + // TODO(deanm): Support interlace. + buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0; + + // - Local Color Table + if (using_local_palette === true) { + for (var i = 0, il = palette.length; i < il; ++i) { + var rgb = palette[i]; + buf[p++] = rgb >> 16 & 0xff; + buf[p++] = rgb >> 8 & 0xff; + buf[p++] = rgb & 0xff; + } + } + + p = GifWriterOutputLZWCodeStream( + buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels); + + return p; + }; + + this.end = function() { + if (ended === false) { + buf[p++] = 0x3b; // Trailer. + ended = true; + } + return p; + }; + + this.getOutputBuffer = function() { return buf; }; + this.setOutputBuffer = function(v) { buf = v; }; + this.getOutputBufferPosition = function() { return p; }; + this.setOutputBufferPosition = function(v) { p = v; }; +} + +// Main compression routine, palette indexes -> LZW code stream. +// |index_stream| must have at least one entry. +function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) { + buf[p++] = min_code_size; + var cur_subblock = p++; // Pointing at the length field. + + var clear_code = 1 << min_code_size; + var code_mask = clear_code - 1; + var eoi_code = clear_code + 1; + var next_code = eoi_code + 1; + + var cur_code_size = min_code_size + 1; // Number of bits per code. + var cur_shift = 0; + // We have at most 12-bit codes, so we should have to hold a max of 19 + // bits here (and then we would write out). + var cur = 0; + + function emit_bytes_to_buffer(bit_block_size) { + while (cur_shift >= bit_block_size) { + buf[p++] = cur & 0xff; + cur >>= 8; cur_shift -= 8; + if (p === cur_subblock + 256) { // Finished a subblock. + buf[cur_subblock] = 255; + cur_subblock = p++; + } + } + } + + function emit_code(c) { + cur |= c << cur_shift; + cur_shift += cur_code_size; + emit_bytes_to_buffer(8); + } + + // I am not an expert on the topic, and I don't want to write a thesis. + // However, it is good to outline here the basic algorithm and the few data + // structures and optimizations here that make this implementation fast. + // The basic idea behind LZW is to build a table of previously seen runs + // addressed by a short id (herein called output code). All data is + // referenced by a code, which represents one or more values from the + // original input stream. All input bytes can be referenced as the same + // value as an output code. So if you didn't want any compression, you + // could more or less just output the original bytes as codes (there are + // some details to this, but it is the idea). In order to achieve + // compression, values greater then the input range (codes can be up to + // 12-bit while input only 8-bit) represent a sequence of previously seen + // inputs. The decompressor is able to build the same mapping while + // decoding, so there is always a shared common knowledge between the + // encoding and decoder, which is also important for "timing" aspects like + // how to handle variable bit width code encoding. + // + // One obvious but very important consequence of the table system is there + // is always a unique id (at most 12-bits) to map the runs. 'A' might be + // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship + // can be used for an effecient lookup strategy for the code mapping. We + // need to know if a run has been seen before, and be able to map that run + // to the output code. Since we start with known unique ids (input bytes), + // and then from those build more unique ids (table entries), we can + // continue this chain (almost like a linked list) to always have small + // integer values that represent the current byte chains in the encoder. + // This means instead of tracking the input bytes (AAAABCD) to know our + // current state, we can track the table entry for AAAABC (it is guaranteed + // to exist by the nature of the algorithm) and the next character D. + // Therefor the tuple of (table_entry, byte) is guaranteed to also be + // unique. This allows us to create a simple lookup key for mapping input + // sequences to codes (table indices) without having to store or search + // any of the code sequences. So if 'AAAA' has a table entry of 12, the + // tuple of ('AAAA', K) for any input byte K will be unique, and can be our + // key. This leads to a integer value at most 20-bits, which can always + // fit in an SMI value and be used as a fast sparse array / object key. + + // Output code for the current contents of the index buffer. + var ib_code = index_stream[0] & code_mask; // Load first input index. + var code_table = { }; // Key'd on our 20-bit "tuple". + + emit_code(clear_code); // Spec says first code should be a clear code. + + // First index already loaded, process the rest of the stream. + for (var i = 1, il = index_stream.length; i < il; ++i) { + var k = index_stream[i] & code_mask; + var cur_key = ib_code << 8 | k; // (prev, k) unique tuple. + var cur_code = code_table[cur_key]; // buffer + k. + + // Check if we have to create a new code table entry. + if (cur_code === undefined) { // We don't have buffer + k. + // Emit index buffer (without k). + // This is an inline version of emit_code, because this is the core + // writing routine of the compressor (and V8 cannot inline emit_code + // because it is a closure here in a different context). Additionally + // we can call emit_byte_to_buffer less often, because we can have + // 30-bits (from our 31-bit signed SMI), and we know our codes will only + // be 12-bits, so can safely have 18-bits there without overflow. + // emit_code(ib_code); + cur |= ib_code << cur_shift; + cur_shift += cur_code_size; + while (cur_shift >= 8) { + buf[p++] = cur & 0xff; + cur >>= 8; cur_shift -= 8; + if (p === cur_subblock + 256) { // Finished a subblock. + buf[cur_subblock] = 255; + cur_subblock = p++; + } + } + + if (next_code === 4096) { // Table full, need a clear. + emit_code(clear_code); + next_code = eoi_code + 1; + cur_code_size = min_code_size + 1; + code_table = { }; + } else { // Table not full, insert a new entry. + // Increase our variable bit code sizes if necessary. This is a bit + // tricky as it is based on "timing" between the encoding and + // decoder. From the encoders perspective this should happen after + // we've already emitted the index buffer and are about to create the + // first table entry that would overflow our current code bit size. + if (next_code >= (1 << cur_code_size)) ++cur_code_size; + code_table[cur_key] = next_code++; // Insert into code table. + } + + ib_code = k; // Index buffer to single input k. + } else { + ib_code = cur_code; // Index buffer to sequence in code table. + } + } + + emit_code(ib_code); // There will still be something in the index buffer. + emit_code(eoi_code); // End Of Information. + + // Flush / finalize the sub-blocks stream to the buffer. + emit_bytes_to_buffer(1); + + // Finish the sub-blocks, writing out any unfinished lengths and + // terminating with a sub-block of length 0. If we have already started + // but not yet used a sub-block it can just become the terminator. + if (cur_subblock + 1 === p) { // Started but unused. + buf[cur_subblock] = 0; + } else { // Started and used, write length and additional terminator block. + buf[cur_subblock] = p - cur_subblock - 1; + buf[p++] = 0; + } + return p; +} + +function GifReader(buf) { + var p = 0; + + // - Header (GIF87a or GIF89a). + if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 || + buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) { + throw new Error("Invalid GIF 87a/89a header."); + } + + // - Logical Screen Descriptor. + var width = buf[p++] | buf[p++] << 8; + var height = buf[p++] | buf[p++] << 8; + var pf0 = buf[p++]; // . + var global_palette_flag = pf0 >> 7; + var num_global_colors_pow2 = pf0 & 0x7; + var num_global_colors = 1 << (num_global_colors_pow2 + 1); + var background = buf[p++]; + buf[p++]; // Pixel aspect ratio (unused?). + + var global_palette_offset = null; + var global_palette_size = null; + + if (global_palette_flag) { + global_palette_offset = p; + global_palette_size = num_global_colors; + p += num_global_colors * 3; // Seek past palette. + } + + var no_eof = true; + + var frames = [ ]; + + var delay = 0; + var transparent_index = null; + var disposal = 0; // 0 - No disposal specified. + var loop_count = null; + + this.width = width; + this.height = height; + + while (no_eof && p < buf.length) { + switch (buf[p++]) { + case 0x21: // Graphics Control Extension Block + switch (buf[p++]) { + case 0xff: // Application specific block + // Try if it's a Netscape block (with animation loop counter). + if (buf[p ] !== 0x0b || // 21 FF already read, check block size. + // NETSCAPE2.0 + buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 && + buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 && + buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 && + buf[p+10] == 0x2e && buf[p+11] == 0x30 && + // Sub-block + buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) { + p += 14; + loop_count = buf[p++] | buf[p++] << 8; + p++; // Skip terminator. + } else { // We don't know what it is, just try to get past it. + p += 12; + while (true) { // Seek through subblocks. + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + p += block_size; + } + } + break; + + case 0xf9: // Graphics Control Extension + if (buf[p++] !== 0x4 || buf[p+4] !== 0) + throw new Error("Invalid graphics extension block."); + var pf1 = buf[p++]; + delay = buf[p++] | buf[p++] << 8; + transparent_index = buf[p++]; + if ((pf1 & 1) === 0) transparent_index = null; + disposal = pf1 >> 2 & 0x7; + p++; // Skip terminator. + break; + + case 0xfe: // Comment Extension. + while (true) { // Seek through subblocks. + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + // console.log(buf.slice(p, p+block_size).toString('ascii')); + p += block_size; + } + break; + + default: + throw new Error( + "Unknown graphic control label: 0x" + buf[p-1].toString(16)); + } + break; + + case 0x2c: // Image Descriptor. + var x = buf[p++] | buf[p++] << 8; + var y = buf[p++] | buf[p++] << 8; + var w = buf[p++] | buf[p++] << 8; + var h = buf[p++] | buf[p++] << 8; + var pf2 = buf[p++]; + var local_palette_flag = pf2 >> 7; + var interlace_flag = pf2 >> 6 & 1; + var num_local_colors_pow2 = pf2 & 0x7; + var num_local_colors = 1 << (num_local_colors_pow2 + 1); + var palette_offset = global_palette_offset; + var palette_size = global_palette_size; + var has_local_palette = false; + if (local_palette_flag) { + var has_local_palette = true; + palette_offset = p; // Override with local palette. + palette_size = num_local_colors; + p += num_local_colors * 3; // Seek past palette. + } + + var data_offset = p; + + p++; // codesize + while (true) { + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + p += block_size; + } + + frames.push({x: x, y: y, width: w, height: h, + has_local_palette: has_local_palette, + palette_offset: palette_offset, + palette_size: palette_size, + data_offset: data_offset, + data_length: p - data_offset, + transparent_index: transparent_index, + interlaced: !!interlace_flag, + delay: delay, + disposal: disposal}); + break; + + case 0x3b: // Trailer Marker (end of file). + no_eof = false; + break; + + default: + throw new Error("Unknown gif block: 0x" + buf[p-1].toString(16)); + break; + } + } + + this.numFrames = function() { + return frames.length; + }; + + this.loopCount = function() { + return loop_count; + }; + + this.frameInfo = function(frame_num) { + if (frame_num < 0 || frame_num >= frames.length) + throw new Error("Frame index out of range."); + return frames[frame_num]; + } + + this.decodeAndBlitFrameBGRA = function(frame_num, pixels) { + var frame = this.frameInfo(frame_num); + var num_pixels = frame.width * frame.height; + var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. + GifReaderLZWOutputIndexStream( + buf, frame.data_offset, index_stream, num_pixels); + var palette_offset = frame.palette_offset; + + // NOTE(deanm): It seems to be much faster to compare index to 256 than + // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in + // the profile, not sure if it's related to using a Uint8Array. + var trans = frame.transparent_index; + if (trans === null) trans = 256; + + // We are possibly just blitting to a portion of the entire frame. + // That is a subrect within the framerect, so the additional pixels + // must be skipped over after we finished a scanline. + var framewidth = frame.width; + var framestride = width - framewidth; + var xleft = framewidth; // Number of subrect pixels left in scanline. + + // Output indicies of the top left and bottom right corners of the subrect. + var opbeg = ((frame.y * width) + frame.x) * 4; + var opend = ((frame.y + frame.height) * width + frame.x) * 4; + var op = opbeg; + + var scanstride = framestride * 4; + + // Use scanstride to skip past the rows when interlacing. This is skipping + // 7 rows for the first two passes, then 3 then 1. + if (frame.interlaced === true) { + scanstride += width * 4 * 7; // Pass 1. + } + + var interlaceskip = 8; // Tracking the row interval in the current pass. + + for (var i = 0, il = index_stream.length; i < il; ++i) { + var index = index_stream[i]; + + if (xleft === 0) { // Beginning of new scan line + op += scanstride; + xleft = framewidth; + if (op >= opend) { // Catch the wrap to switch passes when interlacing. + scanstride = framestride * 4 + width * 4 * (interlaceskip-1); + // interlaceskip / 2 * 4 is interlaceskip << 1. + op = opbeg + (framewidth + framestride) * (interlaceskip << 1); + interlaceskip >>= 1; + } + } + + if (index === trans) { + op += 4; + } else { + var r = buf[palette_offset + index * 3]; + var g = buf[palette_offset + index * 3 + 1]; + var b = buf[palette_offset + index * 3 + 2]; + pixels[op++] = b; + pixels[op++] = g; + pixels[op++] = r; + pixels[op++] = 255; + } + --xleft; + } + }; + + // I will go to copy and paste hell one day... + this.decodeAndBlitFrameRGBA = function(frame_num, pixels) { + var frame = this.frameInfo(frame_num); + var num_pixels = frame.width * frame.height; + var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. + GifReaderLZWOutputIndexStream( + buf, frame.data_offset, index_stream, num_pixels); + var palette_offset = frame.palette_offset; + + // NOTE(deanm): It seems to be much faster to compare index to 256 than + // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in + // the profile, not sure if it's related to using a Uint8Array. + var trans = frame.transparent_index; + if (trans === null) trans = 256; + + // We are possibly just blitting to a portion of the entire frame. + // That is a subrect within the framerect, so the additional pixels + // must be skipped over after we finished a scanline. + var framewidth = frame.width; + var framestride = width - framewidth; + var xleft = framewidth; // Number of subrect pixels left in scanline. + + // Output indicies of the top left and bottom right corners of the subrect. + var opbeg = ((frame.y * width) + frame.x) * 4; + var opend = ((frame.y + frame.height) * width + frame.x) * 4; + var op = opbeg; + + var scanstride = framestride * 4; + + // Use scanstride to skip past the rows when interlacing. This is skipping + // 7 rows for the first two passes, then 3 then 1. + if (frame.interlaced === true) { + scanstride += width * 4 * 7; // Pass 1. + } + + var interlaceskip = 8; // Tracking the row interval in the current pass. + + for (var i = 0, il = index_stream.length; i < il; ++i) { + var index = index_stream[i]; + + if (xleft === 0) { // Beginning of new scan line + op += scanstride; + xleft = framewidth; + if (op >= opend) { // Catch the wrap to switch passes when interlacing. + scanstride = framestride * 4 + width * 4 * (interlaceskip-1); + // interlaceskip / 2 * 4 is interlaceskip << 1. + op = opbeg + (framewidth + framestride) * (interlaceskip << 1); + interlaceskip >>= 1; + } + } + + if (index === trans) { + op += 4; + } else { + var r = buf[palette_offset + index * 3]; + var g = buf[palette_offset + index * 3 + 1]; + var b = buf[palette_offset + index * 3 + 2]; + pixels[op++] = r; + pixels[op++] = g; + pixels[op++] = b; + pixels[op++] = 255; + } + --xleft; + } + }; +} + +function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) { + var min_code_size = code_stream[p++]; + + var clear_code = 1 << min_code_size; + var eoi_code = clear_code + 1; + var next_code = eoi_code + 1; + + var cur_code_size = min_code_size + 1; // Number of bits per code. + // NOTE: This shares the same name as the encoder, but has a different + // meaning here. Here this masks each code coming from the code stream. + var code_mask = (1 << cur_code_size) - 1; + var cur_shift = 0; + var cur = 0; + + var op = 0; // Output pointer. + + var subblock_size = code_stream[p++]; + + // TODO(deanm): Would using a TypedArray be any faster? At least it would + // solve the fast mode / backing store uncertainty. + // var code_table = Array(4096); + var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits. + + var prev_code = null; // Track code-1. + + while (true) { + // Read up to two bytes, making sure we always 12-bits for max sized code. + while (cur_shift < 16) { + if (subblock_size === 0) break; // No more data to be read. + + cur |= code_stream[p++] << cur_shift; + cur_shift += 8; + + if (subblock_size === 1) { // Never let it get to 0 to hold logic above. + subblock_size = code_stream[p++]; // Next subblock. + } else { + --subblock_size; + } + } + + // TODO(deanm): We should never really get here, we should have received + // and EOI. + if (cur_shift < cur_code_size) + break; + + var code = cur & code_mask; + cur >>= cur_code_size; + cur_shift -= cur_code_size; + + // TODO(deanm): Maybe should check that the first code was a clear code, + // at least this is what you're supposed to do. But actually our encoder + // now doesn't emit a clear code first anyway. + if (code === clear_code) { + // We don't actually have to clear the table. This could be a good idea + // for greater error checking, but we don't really do any anyway. We + // will just track it with next_code and overwrite old entries. + + next_code = eoi_code + 1; + cur_code_size = min_code_size + 1; + code_mask = (1 << cur_code_size) - 1; + + // Don't update prev_code ? + prev_code = null; + continue; + } else if (code === eoi_code) { + break; + } + + // We have a similar situation as the decoder, where we want to store + // variable length entries (code table entries), but we want to do in a + // faster manner than an array of arrays. The code below stores sort of a + // linked list within the code table, and then "chases" through it to + // construct the dictionary entries. When a new entry is created, just the + // last byte is stored, and the rest (prefix) of the entry is only + // referenced by its table entry. Then the code chases through the + // prefixes until it reaches a single byte code. We have to chase twice, + // first to compute the length, and then to actually copy the data to the + // output (backwards, since we know the length). The alternative would be + // storing something in an intermediate stack, but that doesn't make any + // more sense. I implemented an approach where it also stored the length + // in the code table, although it's a bit tricky because you run out of + // bits (12 + 12 + 8), but I didn't measure much improvements (the table + // entries are generally not the long). Even when I created benchmarks for + // very long table entries the complexity did not seem worth it. + // The code table stores the prefix entry in 12 bits and then the suffix + // byte in 8 bits, so each entry is 20 bits. + + var chase_code = code < next_code ? code : prev_code; + + // Chase what we will output, either {CODE} or {CODE-1}. + var chase_length = 0; + var chase = chase_code; + while (chase > clear_code) { + chase = code_table[chase] >> 8; + ++chase_length; + } + + var k = chase; + + var op_end = op + chase_length + (chase_code !== code ? 1 : 0); + if (op_end > output_length) { + console.log("Warning, gif stream longer than expected."); + return; + } + + // Already have the first byte from the chase, might as well write it fast. + output[op++] = k; + + op += chase_length; + var b = op; // Track pointer, writing backwards. + + if (chase_code !== code) // The case of emitting {CODE-1} + k. + output[op++] = k; + + chase = chase_code; + while (chase_length--) { + chase = code_table[chase]; + output[--b] = chase & 0xff; // Write backwards. + chase >>= 8; // Pull down to the prefix code. + } + + if (prev_code !== null && next_code < 4096) { + code_table[next_code++] = prev_code << 8 | k; + // TODO(deanm): Figure out this clearing vs code growth logic better. I + // have an feeling that it should just happen somewhere else, for now it + // is awkward between when we grow past the max and then hit a clear code. + // For now just check if we hit the max 12-bits (then a clear code should + // follow, also of course encoded in 12-bits). + if (next_code >= code_mask+1 && cur_code_size < 12) { + ++cur_code_size; + code_mask = code_mask << 1 | 1; + } + } + + prev_code = code; + } + + if (op !== output_length) { + console.log("Warning, gif stream shorter than expected."); + } + + return output; +} + +// CommonJS. +try { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) {} diff --git a/node_modules/omggif/package.json b/node_modules/omggif/package.json new file mode 100644 index 00000000..83766f51 --- /dev/null +++ b/node_modules/omggif/package.json @@ -0,0 +1,12 @@ +{ + "name": "omggif", + "version": "1.0.10", + "author": "Dean McNamee ", + "license": "MIT", + "keywords": ["gif", "gif89a", "gif87a", "plask"], + "repository": { + "type": "git", + "url": "https://github.com/deanm/omggif" + }, + "main": "omggif.js" +} diff --git a/node_modules/omggif/plask_viewer.js b/node_modules/omggif/plask_viewer.js new file mode 100644 index 00000000..b2bd6172 --- /dev/null +++ b/node_modules/omggif/plask_viewer.js @@ -0,0 +1,42 @@ + +var plask = require('plask'); +var fs = require('fs'); +var omggif = require('./omggif'); + +if (process.argv.length < 3) throw "Usage: "; +var buf = fs.readFileSync(process.argv[2]); +var gr = new omggif.GifReader(buf); + +var pixels = plask.SkCanvas.create(gr.width, gr.height); + +plask.simpleWindow({ + settings: { + width: 800, + height: 600 + }, + + init: function() { + var canvas = this.canvas, paint = this.paint; + + canvas.clear(230, 230, 230, 255); // Draw the background, just once. + }, + + draw: function() { + var canvas = this.canvas, paint = this.paint; + + var frame_num = this.framenum % gr.numFrames(); + var frame_info = gr.frameInfo(frame_num); + + if (frame_num === 0 || frame_info.disposal === 2 /* restore to bg */) + pixels.clear(0, 0, 0, 255); + + var start = Date.now(); + gr.decodeAndBlitFrameBGRA(frame_num, pixels.pixels || pixels); + console.log('Decoded and blit frame in: ' + (Date.now() - start) + 'ms'); + + canvas.drawCanvas(paint, pixels, 0, 0, gr.width, gr.height); + + var this_ = this; + setTimeout(function() { this_.redraw(); }, frame_info.delay * 10); + } +}); diff --git a/node_modules/pako/CHANGELOG.md b/node_modules/pako/CHANGELOG.md new file mode 100644 index 00000000..a861326b --- /dev/null +++ b/node_modules/pako/CHANGELOG.md @@ -0,0 +1,164 @@ +# 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). + + +## [1.0.11] - 2020-01-29 +### Fixed +- Fix tests in node.js v12+, #179. + + +## [1.0.10] - 2019-02-28 +### Fixed +- Fix minified version, #161. + + +## [1.0.9] - 2019-02-28 +### Fixed +- Fix `new Buffer()` warning, #154. + + +## [1.0.8] - 2019-01-14 +### Fixed +- Fix raw inflate with dictionary, #155. + + +## [1.0.7] - 2018-11-29 +### Fixed +- Fixed RangeError in Crome 72, #150. + + +## [1.0.6] - 2017-09-14 +### Changed +- Improve @std/esm compatibility. + + +## [1.0.5] - 2017-03-17 +### Changed +- Maintenance. More formal `zlib` attribution and related + changes, #93. Thanks to @bastien-roucaries for the help. + + +## [1.0.4] - 2016-12-15 +### Changed +- Bump dev dependencies. + +### Fixed +- Make sure `err.message` is filled on throw. + +### Added +- Code examples for utf-16 string encoding & object compression. + + +## [1.0.3] - 2016-07-25 +### Fixed +- Maintenance: re-release to properly display latest version in npm registry + and badges. Because `npm publish` timestamp used instead of versions. + + +## [1.0.2] - 2016-07-21 +### Fixed +- Fixed nasty bug in deflate (wrong `d_buf` offset), which could cause + broken data in some rare cases. +- Also released as 0.2.9 to give chance to old dependents, not updated to 1.x + version. + + +## [1.0.1] - 2016-04-01 +### Added +- Added dictionary support. Thanks to @dignifiedquire. + + +## [1.0.0] - 2016-02-17 +### Changed +- Maintenance release (semver, coding style). + + +## [0.2.8] - 2015-09-14 +### Fixed +- Fixed regression after 0.2.4 for edge conditions in inflate wrapper (#65). + Added more tests to cover possible cases. + + +## [0.2.7] - 2015-06-09 +### Added +- Added Z_SYNC_FLUSH support. Thanks to @TinoLange. + + +## [0.2.6] - 2015-03-24 +### Added +- Allow ArrayBuffer input. + + +## [0.2.5] - 2014-07-19 +### Fixed +- Workaround for Chrome 38.0.2096.0 script parser bug, #30. + + +## [0.2.4] - 2014-07-07 +### Fixed +- Fixed bug in inflate wrapper, #29 + + +## [0.2.3] - 2014-06-09 +### Changed +- Maintenance release, dependencies update. + + +## [0.2.2] - 2014-06-04 +### Fixed +- Fixed iOS 5.1 Safari issue with `apply(typed_array)`, #26. + + +## [0.2.1] - 2014-05-01 +### Fixed +- Fixed collision on switch dynamic/fixed tables. + + +## [0.2.0] - 2014-04-18 +### Added +- Added custom gzip headers support. +- Added strings support. +- More coverage tests. + +### Fixed +- Improved memory allocations for small chunks. +- ZStream properties rename/cleanup. + + +## [0.1.1] - 2014-03-20 +### Fixed +- Bugfixes for inflate/deflate. + + +## [0.1.0] - 2014-03-15 +### Added +- First release. + + +[1.0.10]: https://github.com/nodeca/pako/compare/1.0.10...1.0.11 +[1.0.10]: https://github.com/nodeca/pako/compare/1.0.9...1.0.10 +[1.0.9]: https://github.com/nodeca/pako/compare/1.0.8...1.0.9 +[1.0.8]: https://github.com/nodeca/pako/compare/1.0.7...1.0.8 +[1.0.7]: https://github.com/nodeca/pako/compare/1.0.6...1.0.7 +[1.0.6]: https://github.com/nodeca/pako/compare/1.0.5...1.0.6 +[1.0.5]: https://github.com/nodeca/pako/compare/1.0.4...1.0.5 +[1.0.4]: https://github.com/nodeca/pako/compare/1.0.3...1.0.4 +[1.0.3]: https://github.com/nodeca/pako/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/pako/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/pako/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/pako/compare/0.2.8...1.0.0 +[0.2.8]: https://github.com/nodeca/pako/compare/0.2.7...0.2.8 +[0.2.7]: https://github.com/nodeca/pako/compare/0.2.6...0.2.7 +[0.2.6]: https://github.com/nodeca/pako/compare/0.2.5...0.2.6 +[0.2.5]: https://github.com/nodeca/pako/compare/0.2.4...0.2.5 +[0.2.4]: https://github.com/nodeca/pako/compare/0.2.3...0.2.4 +[0.2.3]: https://github.com/nodeca/pako/compare/0.2.2...0.2.3 +[0.2.2]: https://github.com/nodeca/pako/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/nodeca/pako/compare/0.2.0...0.2.1 +[0.2.0]: https://github.com/nodeca/pako/compare/0.1.1...0.2.0 +[0.1.1]: https://github.com/nodeca/pako/compare/0.1.0...0.1.1 +[0.1.0]: https://github.com/nodeca/pako/releases/tag/0.1.0 diff --git a/node_modules/pako/LICENSE b/node_modules/pako/LICENSE new file mode 100644 index 00000000..a934ef8d --- /dev/null +++ b/node_modules/pako/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2014-2017 by Vitaly Puzrin and Andrei Tuputcyn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/pako/README.md b/node_modules/pako/README.md new file mode 100644 index 00000000..e952992c --- /dev/null +++ b/node_modules/pako/README.md @@ -0,0 +1,191 @@ +pako +========================================== + +[![Build Status](https://travis-ci.org/nodeca/pako.svg?branch=master)](https://travis-ci.org/nodeca/pako) +[![NPM version](https://img.shields.io/npm/v/pako.svg)](https://www.npmjs.org/package/pako) + +> zlib port to javascript, very fast! + +__Why pako is cool:__ + +- Almost as fast in modern JS engines as C implementation (see benchmarks). +- Works in browsers, you can browserify any separate component. +- Chunking support for big blobs. +- Results are binary equal to well known [zlib](http://www.zlib.net/) (now contains ported zlib v1.2.8). + +This project was done to understand how fast JS can be and is it necessary to +develop native C modules for CPU-intensive tasks. Enjoy the result! + + +__Famous projects, using pako:__ + +- [browserify](http://browserify.org/) (via [browserify-zlib](https://github.com/devongovett/browserify-zlib)) +- [JSZip](http://stuk.github.io/jszip/) +- [mincer](https://github.com/nodeca/mincer) +- [JS-Git](https://github.com/creationix/js-git) and + [Tedit](https://chrome.google.com/webstore/detail/tedit-development-environ/ooekdijbnbbjdfjocaiflnjgoohnblgf) + by [@creationix](https://github.com/creationix) + + +__Benchmarks:__ + +``` +node v0.10.26, 1mb sample: + + deflate-dankogai x 4.73 ops/sec ±0.82% (15 runs sampled) + deflate-gildas x 4.58 ops/sec ±2.33% (15 runs sampled) + deflate-imaya x 3.22 ops/sec ±3.95% (12 runs sampled) + ! deflate-pako x 6.99 ops/sec ±0.51% (21 runs sampled) + deflate-pako-string x 5.89 ops/sec ±0.77% (18 runs sampled) + deflate-pako-untyped x 4.39 ops/sec ±1.58% (14 runs sampled) + * deflate-zlib x 14.71 ops/sec ±4.23% (59 runs sampled) + inflate-dankogai x 32.16 ops/sec ±0.13% (56 runs sampled) + inflate-imaya x 30.35 ops/sec ±0.92% (53 runs sampled) + ! inflate-pako x 69.89 ops/sec ±1.46% (71 runs sampled) + inflate-pako-string x 19.22 ops/sec ±1.86% (49 runs sampled) + inflate-pako-untyped x 17.19 ops/sec ±0.85% (32 runs sampled) + * inflate-zlib x 70.03 ops/sec ±1.64% (81 runs sampled) + +node v0.11.12, 1mb sample: + + deflate-dankogai x 5.60 ops/sec ±0.49% (17 runs sampled) + deflate-gildas x 5.06 ops/sec ±6.00% (16 runs sampled) + deflate-imaya x 3.52 ops/sec ±3.71% (13 runs sampled) + ! deflate-pako x 11.52 ops/sec ±0.22% (32 runs sampled) + deflate-pako-string x 9.53 ops/sec ±1.12% (27 runs sampled) + deflate-pako-untyped x 5.44 ops/sec ±0.72% (17 runs sampled) + * deflate-zlib x 14.05 ops/sec ±3.34% (63 runs sampled) + inflate-dankogai x 42.19 ops/sec ±0.09% (56 runs sampled) + inflate-imaya x 79.68 ops/sec ±1.07% (68 runs sampled) + ! inflate-pako x 97.52 ops/sec ±0.83% (80 runs sampled) + inflate-pako-string x 45.19 ops/sec ±1.69% (57 runs sampled) + inflate-pako-untyped x 24.35 ops/sec ±2.59% (40 runs sampled) + * inflate-zlib x 60.32 ops/sec ±1.36% (69 runs sampled) +``` + +zlib's test is partially affected by marshalling (that make sense for inflate only). +You can change deflate level to 0 in benchmark source, to investigate details. +For deflate level 6 results can be considered as correct. + +__Install:__ + +node.js: + +``` +npm install pako +``` + +browser: + +``` +bower install pako +``` + + +Example & API +------------- + +Full docs - http://nodeca.github.io/pako/ + +```javascript +var pako = require('pako'); + +// Deflate +// +var input = new Uint8Array(); +//... fill input data here +var output = pako.deflate(input); + +// Inflate (simple wrapper can throw exception on broken stream) +// +var compressed = new Uint8Array(); +//... fill data to uncompress here +try { + var result = pako.inflate(compressed); +} catch (err) { + console.log(err); +} + +// +// Alternate interface for chunking & without exceptions +// + +var inflator = new pako.Inflate(); + +inflator.push(chunk1, false); +inflator.push(chunk2, false); +... +inflator.push(chunkN, true); // true -> last chunk + +if (inflator.err) { + console.log(inflator.msg); +} + +var output = inflator.result; + +``` + +Sometime you can wish to work with strings. For example, to send +big objects as json to server. Pako detects input data type. You can +force output to be string with option `{ to: 'string' }`. + +```javascript +var pako = require('pako'); + +var test = { my: 'super', puper: [456, 567], awesome: 'pako' }; + +var binaryString = pako.deflate(JSON.stringify(test), { to: 'string' }); + +// +// Here you can do base64 encode, make xhr requests and so on. +// + +var restored = JSON.parse(pako.inflate(binaryString, { to: 'string' })); +``` + + +Notes +----- + +Pako does not contain some specific zlib functions: + +- __deflate__ - methods `deflateCopy`, `deflateBound`, `deflateParams`, + `deflatePending`, `deflatePrime`, `deflateTune`. +- __inflate__ - methods `inflateCopy`, `inflateMark`, + `inflatePrime`, `inflateGetDictionary`, `inflateSync`, `inflateSyncPoint`, `inflateUndermine`. +- High level inflate/deflate wrappers (classes) may not support some flush + modes. Those should work: Z_NO_FLUSH, Z_FINISH, Z_SYNC_FLUSH. + + +pako for enterprise +------------------- + +Available as part of the Tidelift Subscription + +The maintainers of pako 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-pako?utm_source=npm-pako&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +Authors +------- + +- Andrey Tupitsin [@anrd83](https://github.com/andr83) +- Vitaly Puzrin [@puzrin](https://github.com/puzrin) + +Personal thanks to: + +- Vyacheslav Egorov ([@mraleph](https://github.com/mraleph)) for his awesome + tutorials about optimising JS code for v8, [IRHydra](http://mrale.ph/irhydra/) + tool and his advices. +- David Duponchel ([@dduponchel](https://github.com/dduponchel)) for help with + testing. + +Original implementation (in C): + +- [zlib](http://zlib.net/) by Jean-loup Gailly and Mark Adler. + + +License +------- + +- MIT - all files, except `/lib/zlib` folder +- ZLIB - `/lib/zlib` content diff --git a/node_modules/pako/index.js b/node_modules/pako/index.js new file mode 100644 index 00000000..cd072515 --- /dev/null +++ b/node_modules/pako/index.js @@ -0,0 +1,14 @@ +// Top level file is just a mixin of submodules & constants +'use strict'; + +var assign = require('./lib/utils/common').assign; + +var deflate = require('./lib/deflate'); +var inflate = require('./lib/inflate'); +var constants = require('./lib/zlib/constants'); + +var pako = {}; + +assign(pako, deflate, inflate, constants); + +module.exports = pako; diff --git a/node_modules/pako/lib/deflate.js b/node_modules/pako/lib/deflate.js new file mode 100644 index 00000000..efeb00c7 --- /dev/null +++ b/node_modules/pako/lib/deflate.js @@ -0,0 +1,400 @@ +'use strict'; + + +var zlib_deflate = require('./zlib/deflate'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var msg = require('./zlib/messages'); +var ZStream = require('./zlib/zstream'); + +var toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH = 0; +var Z_FINISH = 4; + +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_SYNC_FLUSH = 2; + +var Z_DEFAULT_COMPRESSION = -1; + +var Z_DEFAULT_STRATEGY = 0; + +var Z_DEFLATED = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; diff --git a/node_modules/pako/lib/inflate.js b/node_modules/pako/lib/inflate.js new file mode 100644 index 00000000..7535d15a --- /dev/null +++ b/node_modules/pako/lib/inflate.js @@ -0,0 +1,423 @@ +'use strict'; + + +var zlib_inflate = require('./zlib/inflate'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var c = require('./zlib/constants'); +var msg = require('./zlib/messages'); +var ZStream = require('./zlib/zstream'); +var GZheader = require('./zlib/gzheader'); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; diff --git a/node_modules/pako/lib/utils/common.js b/node_modules/pako/lib/utils/common.js new file mode 100644 index 00000000..58be4beb --- /dev/null +++ b/node_modules/pako/lib/utils/common.js @@ -0,0 +1,105 @@ +'use strict'; + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); diff --git a/node_modules/pako/lib/utils/strings.js b/node_modules/pako/lib/utils/strings.js new file mode 100644 index 00000000..b07a732d --- /dev/null +++ b/node_modules/pako/lib/utils/strings.js @@ -0,0 +1,187 @@ +// String encode/decode helpers +'use strict'; + + +var utils = require('./common'); + + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +var STR_APPLY_OK = true; +var STR_APPLY_UIA_OK = true; + +try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } +try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +var _utf8len = new utils.Buf8(256); +for (var q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function (buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function (str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; diff --git a/node_modules/pako/lib/zlib/README b/node_modules/pako/lib/zlib/README new file mode 100644 index 00000000..88a87524 --- /dev/null +++ b/node_modules/pako/lib/zlib/README @@ -0,0 +1,59 @@ +Content of this folder follows zlib C sources as close as possible. +That's intended to simplify maintainability and guarantee equal API +and result. + +Key differences: + +- Everything is in JavaScript. +- No platform-dependent blocks. +- Some things like crc32 rewritten to keep size small and make JIT + work better. +- Some code is different due missed features in JS (macros, pointers, + structures, header files) +- Specific API methods are not implemented (see notes in root readme) + +This port is based on zlib 1.2.8. + +This port is under zlib license (see below) with contribution and addition of javascript +port under expat license (see LICENSE at root of project) + +Copyright: +(C) 1995-2013 Jean-loup Gailly and Mark Adler +(C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + + +From zlib's README +============================================================================= + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate and + zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; they + are too numerous to cite here. + +Copyright notice: + + (C) 1995-2013 Jean-loup Gailly and Mark Adler + +Copyright (c) <''year''> <''copyright holders''> + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu diff --git a/node_modules/pako/lib/zlib/adler32.js b/node_modules/pako/lib/zlib/adler32.js new file mode 100644 index 00000000..d440a981 --- /dev/null +++ b/node_modules/pako/lib/zlib/adler32.js @@ -0,0 +1,51 @@ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; diff --git a/node_modules/pako/lib/zlib/constants.js b/node_modules/pako/lib/zlib/constants.js new file mode 100644 index 00000000..569b8724 --- /dev/null +++ b/node_modules/pako/lib/zlib/constants.js @@ -0,0 +1,68 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; diff --git a/node_modules/pako/lib/zlib/crc32.js b/node_modules/pako/lib/zlib/crc32.js new file mode 100644 index 00000000..6a960924 --- /dev/null +++ b/node_modules/pako/lib/zlib/crc32.js @@ -0,0 +1,59 @@ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; diff --git a/node_modules/pako/lib/zlib/deflate.js b/node_modules/pako/lib/zlib/deflate.js new file mode 100644 index 00000000..31456989 --- /dev/null +++ b/node_modules/pako/lib/zlib/deflate.js @@ -0,0 +1,1874 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ diff --git a/node_modules/pako/lib/zlib/gzheader.js b/node_modules/pako/lib/zlib/gzheader.js new file mode 100644 index 00000000..9582cba6 --- /dev/null +++ b/node_modules/pako/lib/zlib/gzheader.js @@ -0,0 +1,58 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; diff --git a/node_modules/pako/lib/zlib/inffast.js b/node_modules/pako/lib/zlib/inffast.js new file mode 100644 index 00000000..4cc958fe --- /dev/null +++ b/node_modules/pako/lib/zlib/inffast.js @@ -0,0 +1,345 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; diff --git a/node_modules/pako/lib/zlib/inflate.js b/node_modules/pako/lib/zlib/inflate.js new file mode 100644 index 00000000..63848448 --- /dev/null +++ b/node_modules/pako/lib/zlib/inflate.js @@ -0,0 +1,1556 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ diff --git a/node_modules/pako/lib/zlib/inftrees.js b/node_modules/pako/lib/zlib/inftrees.js new file mode 100644 index 00000000..ec4e4e90 --- /dev/null +++ b/node_modules/pako/lib/zlib/inftrees.js @@ -0,0 +1,343 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; diff --git a/node_modules/pako/lib/zlib/messages.js b/node_modules/pako/lib/zlib/messages.js new file mode 100644 index 00000000..426daec6 --- /dev/null +++ b/node_modules/pako/lib/zlib/messages.js @@ -0,0 +1,32 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; diff --git a/node_modules/pako/lib/zlib/trees.js b/node_modules/pako/lib/zlib/trees.js new file mode 100644 index 00000000..aaf15dba --- /dev/null +++ b/node_modules/pako/lib/zlib/trees.js @@ -0,0 +1,1222 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; diff --git a/node_modules/pako/lib/zlib/zstream.js b/node_modules/pako/lib/zlib/zstream.js new file mode 100644 index 00000000..122acfef --- /dev/null +++ b/node_modules/pako/lib/zlib/zstream.js @@ -0,0 +1,47 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; diff --git a/node_modules/pako/package.json b/node_modules/pako/package.json new file mode 100644 index 00000000..7aaade84 --- /dev/null +++ b/node_modules/pako/package.json @@ -0,0 +1,44 @@ +{ + "name": "pako", + "description": "zlib port to javascript - fast, modularized, with browser support", + "version": "1.0.11", + "keywords": [ + "zlib", + "deflate", + "inflate", + "gzip" + ], + "homepage": "https://github.com/nodeca/pako", + "contributors": [ + "Andrei Tuputcyn (https://github.com/andr83)", + "Vitaly Puzrin (https://github.com/puzrin)", + "Friedel Ziegelmayer (https://github.com/dignifiedquire)", + "Kirill Efimov (https://github.com/Kirill89)", + "Jean-loup Gailly", + "Mark Adler" + ], + "files": [ + "index.js", + "dist/", + "lib/" + ], + "license": "(MIT AND Zlib)", + "repository": "nodeca/pako", + "scripts": { + "test": "make test" + }, + "devDependencies": { + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "browserify": "^16.2.3", + "buffer-from": "^1.1.1", + "eslint": "^5.9.0", + "istanbul": "^0.4.5", + "mocha": "^5.2.0", + "multiparty": "^4.1.3", + "ndoc": "^5.0.1", + "uglify-js": "=3.4.8", + "zlibjs": "^0.3.1" + }, + "dependencies": {} +} diff --git a/node_modules/parse-bmfont-ascii/README.md b/node_modules/parse-bmfont-ascii/README.md new file mode 100644 index 00000000..00df52c2 --- /dev/null +++ b/node_modules/parse-bmfont-ascii/README.md @@ -0,0 +1,56 @@ +# parse-bmfont-ascii + +[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) + +Parses ASCII (text) [BMFont files](http://www.angelcode.com/products/bmfont/). + +Takes a string or Buffer: + +```js +var fs = require('fs') +var parse = require('parse-bmfont-xml') + +fs.readFileSync(__dirname+'/Arial.fnt', function(err, data) { + var result = parse(data) + console.log(result.info.face) // "Arial" + console.log(result.pages) // [ 'sheet0.png' ] + console.log(result.chars) // [ ... char data ... ] + console.log(result.kernings) // [ ... kernings data ... ] +}) +``` + +The spec for the returned JSON object is [here](https://github.com/mattdesl/bmfont2json/wiki/JsonSpec). The input data should match the spec, see [test/Nexa Light-32.fnt](test/Nexa Light-32.fnt) for an example. + +## See Also + +See [text-modules](https://github.com/mattdesl/text-modules) for related modules. + +## Usage + +[![NPM](https://nodei.co/npm/parse-bmfont-ascii.png)](https://www.npmjs.com/package/parse-bmfont-ascii) + +#### `result = parse(data)` + +Parses `data`, a string or Buffer that represents ASCII (text) data of an AngelCode BMFont file. The returned `result` object looks like this: + +```js +{ + pages: [ + "sheet_0.png", + "sheet_1.png" + ], + chars: [ + { chnl, height, id, page, width, x, y, xoffset, yoffset, xadvance }, + ... + ], + info: { ... }, + common: { ... }, + kernings: [ + { first, second, amount } + ] +} +``` + +## License + +MIT, see [LICENSE.md](http://github.com/mattdesl/parse-bmfont-ascii/blob/master/LICENSE.md) for details. diff --git a/node_modules/parse-bmfont-ascii/index.js b/node_modules/parse-bmfont-ascii/index.js new file mode 100644 index 00000000..27b2f641 --- /dev/null +++ b/node_modules/parse-bmfont-ascii/index.js @@ -0,0 +1,108 @@ +module.exports = function parseBMFontAscii(data) { + if (!data) + throw new Error('no data provided') + data = data.toString().trim() + + var output = { + pages: [], + chars: [], + kernings: [] + } + + var lines = data.split(/\r\n?|\n/g) + + if (lines.length === 0) + throw new Error('no data in BMFont file') + + for (var i = 0; i < lines.length; i++) { + var lineData = splitLine(lines[i], i) + if (!lineData) //skip empty lines + continue + + if (lineData.key === 'page') { + if (typeof lineData.data.id !== 'number') + throw new Error('malformed file at line ' + i + ' -- needs page id=N') + if (typeof lineData.data.file !== 'string') + throw new Error('malformed file at line ' + i + ' -- needs page file="path"') + output.pages[lineData.data.id] = lineData.data.file + } else if (lineData.key === 'chars' || lineData.key === 'kernings') { + //... do nothing for these two ... + } else if (lineData.key === 'char') { + output.chars.push(lineData.data) + } else if (lineData.key === 'kerning') { + output.kernings.push(lineData.data) + } else { + output[lineData.key] = lineData.data + } + } + + return output +} + +function splitLine(line, idx) { + line = line.replace(/\t+/g, ' ').trim() + if (!line) + return null + + var space = line.indexOf(' ') + if (space === -1) + throw new Error("no named row at line " + idx) + + var key = line.substring(0, space) + + line = line.substring(space + 1) + //clear "letter" field as it is non-standard and + //requires additional complexity to parse " / = symbols + line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '') + line = line.split("=") + line = line.map(function(str) { + return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g)) + }) + + var data = [] + for (var i = 0; i < line.length; i++) { + var dt = line[i] + if (i === 0) { + data.push({ + key: dt[0], + data: "" + }) + } else if (i === line.length - 1) { + data[data.length - 1].data = parseData(dt[0]) + } else { + data[data.length - 1].data = parseData(dt[0]) + data.push({ + key: dt[1], + data: "" + }) + } + } + + var out = { + key: key, + data: {} + } + + data.forEach(function(v) { + out.data[v.key] = v.data; + }) + + return out +} + +function parseData(data) { + if (!data || data.length === 0) + return "" + + if (data.indexOf('"') === 0 || data.indexOf("'") === 0) + return data.substring(1, data.length - 1) + if (data.indexOf(',') !== -1) + return parseIntList(data) + return parseInt(data, 10) +} + +function parseIntList(data) { + return data.split(',').map(function(val) { + return parseInt(val, 10) + }) +} \ No newline at end of file diff --git a/node_modules/parse-bmfont-ascii/package.json b/node_modules/parse-bmfont-ascii/package.json new file mode 100644 index 00000000..f0ffc182 --- /dev/null +++ b/node_modules/parse-bmfont-ascii/package.json @@ -0,0 +1,45 @@ +{ + "name": "parse-bmfont-ascii", + "version": "1.0.6", + "description": "parses ASCII BMFont files to a JavaScript object", + "main": "index.js", + "license": "MIT", + "author": { + "name": "Matt DesLauriers", + "email": "dave.des@gmail.com", + "url": "https://github.com/mattdesl" + }, + "dependencies": {}, + "devDependencies": { + "tape": "^3.5.0" + }, + "scripts": { + "test": "node test/test.js" + }, + "keywords": [ + "ascii", + "parse", + "convert", + "bmfont", + "bm", + "bitmap", + "font", + "bitmaps", + "angel", + "angelcode", + "code", + "text", + "gl", + "sprite", + "sprites", + "stackgl" + ], + "repository": { + "type": "git", + "url": "git://github.com/mattdesl/parse-bmfont-ascii.git" + }, + "homepage": "https://github.com/mattdesl/parse-bmfont-ascii", + "bugs": { + "url": "https://github.com/mattdesl/parse-bmfont-ascii/issues" + } +} diff --git a/node_modules/parse-bmfont-binary/LICENSE.md b/node_modules/parse-bmfont-binary/LICENSE.md new file mode 100644 index 00000000..9b10ce2a --- /dev/null +++ b/node_modules/parse-bmfont-binary/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) +Copyright (c) 2015 Jam3 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/parse-bmfont-binary/README.md b/node_modules/parse-bmfont-binary/README.md new file mode 100644 index 00000000..ea99282d --- /dev/null +++ b/node_modules/parse-bmfont-binary/README.md @@ -0,0 +1,37 @@ +# parse-bmfont-binary + +[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) + +Encodes a BMFont from a binary Buffer into JSON, as per the [BMFont Spec](http://www.angelcode.com/products/bmfont/doc/file_format.html). Can be used in Node or the browser (e.g. with browserify). + +```js +var parse = require('parse-bmfont-binary') + +fs.readFile('fonts/Lato.bin', function(err, data) { + if (err) throw err + var font = parse(data) + + //do something with your font + console.log(font.info.face) + console.log(font.info.size) + console.log(font.common.lineHeight) + console.log(font.chars) + console.log(font.kernings) +}) +``` + +## See Also + +See [text-modules](https://github.com/mattdesl/text-modules) for related modules. + +## Usage + +[![NPM](https://nodei.co/npm/parse-bmfont-binary.png)](https://www.npmjs.com/package/parse-bmfont-binary) + +#### `font = parse(buffer)` + +Reads a binary BMFont Buffer and returns a new JSON representation of that font. See [here](https://github.com/mattdesl/bmfont2json/wiki/JsonSpec) for details on the return format. + +## License + +MIT, see [LICENSE.md](http://github.com/Jam3/parse-bmfont-binary/blob/master/LICENSE.md) for details. diff --git a/node_modules/parse-bmfont-binary/index.js b/node_modules/parse-bmfont-binary/index.js new file mode 100644 index 00000000..6b0071c9 --- /dev/null +++ b/node_modules/parse-bmfont-binary/index.js @@ -0,0 +1,160 @@ +var HEADER = [66, 77, 70] + +module.exports = function readBMFontBinary(buf) { + if (buf.length < 6) + throw new Error('invalid buffer length for BMFont') + + var header = HEADER.every(function(byte, i) { + return buf.readUInt8(i) === byte + }) + + if (!header) + throw new Error('BMFont missing BMF byte header') + + var i = 3 + var vers = buf.readUInt8(i++) + if (vers > 3) + throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)') + + var target = { kernings: [], chars: [] } + for (var b=0; b<5; b++) + i += readBlock(target, buf, i) + return target +} + +function readBlock(target, buf, i) { + if (i > buf.length-1) + return 0 + + var blockID = buf.readUInt8(i++) + var blockSize = buf.readInt32LE(i) + i += 4 + + switch(blockID) { + case 1: + target.info = readInfo(buf, i) + break + case 2: + target.common = readCommon(buf, i) + break + case 3: + target.pages = readPages(buf, i, blockSize) + break + case 4: + target.chars = readChars(buf, i, blockSize) + break + case 5: + target.kernings = readKernings(buf, i, blockSize) + break + } + return 5 + blockSize +} + +function readInfo(buf, i) { + var info = {} + info.size = buf.readInt16LE(i) + + var bitField = buf.readUInt8(i+2) + info.smooth = (bitField >> 7) & 1 + info.unicode = (bitField >> 6) & 1 + info.italic = (bitField >> 5) & 1 + info.bold = (bitField >> 4) & 1 + + //fixedHeight is only mentioned in binary spec + if ((bitField >> 3) & 1) + info.fixedHeight = 1 + + info.charset = buf.readUInt8(i+3) || '' + info.stretchH = buf.readUInt16LE(i+4) + info.aa = buf.readUInt8(i+6) + info.padding = [ + buf.readInt8(i+7), + buf.readInt8(i+8), + buf.readInt8(i+9), + buf.readInt8(i+10) + ] + info.spacing = [ + buf.readInt8(i+11), + buf.readInt8(i+12) + ] + info.outline = buf.readUInt8(i+13) + info.face = readStringNT(buf, i+14) + return info +} + +function readCommon(buf, i) { + var common = {} + common.lineHeight = buf.readUInt16LE(i) + common.base = buf.readUInt16LE(i+2) + common.scaleW = buf.readUInt16LE(i+4) + common.scaleH = buf.readUInt16LE(i+6) + common.pages = buf.readUInt16LE(i+8) + var bitField = buf.readUInt8(i+10) + common.packed = 0 + common.alphaChnl = buf.readUInt8(i+11) + common.redChnl = buf.readUInt8(i+12) + common.greenChnl = buf.readUInt8(i+13) + common.blueChnl = buf.readUInt8(i+14) + return common +} + +function readPages(buf, i, size) { + var pages = [] + var text = readNameNT(buf, i) + var len = text.length+1 + var count = size / len + for (var c=0; c` root element, see [test/Nexa Light-32.fnt](test/Nexa Light-32.fnt) for an example. + +## See Also + +See [text-modules](https://github.com/mattdesl/text-modules) for related modules. + +## Usage + +[![NPM](https://nodei.co/npm/parse-bmfont-xml.png)](https://www.npmjs.com/package/parse-bmfont-xml) + +#### `result = parse(data)` + +Parses `data`, a string or Buffer that represents XML data of an AngelCode BMFont file. The returned `result` object looks like this: + +```js +{ + pages: [ + "sheet_0.png", + "sheet_1.png" + ], + chars: [ + { chnl, height, id, page, width, x, y, xoffset, yoffset, xadvance }, + ... + ], + info: { ... }, + common: { ... }, + kernings: [ + { first, second, amount } + ] +} +``` + +If the data is malformed, an error will be thrown. + +The browser implementation relies on [xml-parse-from-string](https://github.com/Jam3/xml-parse-from-string), which may not work in environments without valid DOM APIs (like CocoonJS). + +## License + +MIT, see [LICENSE.md](http://github.com/mattdesl/parse-bmfont-xml/blob/master/LICENSE.md) for details. diff --git a/node_modules/parse-bmfont-xml/lib/browser.js b/node_modules/parse-bmfont-xml/lib/browser.js new file mode 100644 index 00000000..a6857d5c --- /dev/null +++ b/node_modules/parse-bmfont-xml/lib/browser.js @@ -0,0 +1,85 @@ +var parseAttributes = require('./parse-attribs') +var parseFromString = require('xml-parse-from-string') + +//In some cases element.attribute.nodeName can return +//all lowercase values.. so we need to map them to the correct +//case +var NAME_MAP = { + scaleh: 'scaleH', + scalew: 'scaleW', + stretchh: 'stretchH', + lineheight: 'lineHeight', + alphachnl: 'alphaChnl', + redchnl: 'redChnl', + greenchnl: 'greenChnl', + bluechnl: 'blueChnl' +} + +module.exports = function parse(data) { + data = data.toString() + + var xmlRoot = parseFromString(data) + var output = { + pages: [], + chars: [], + kernings: [] + } + + //get config settings + ;['info', 'common'].forEach(function(key) { + var element = xmlRoot.getElementsByTagName(key)[0] + if (element) + output[key] = parseAttributes(getAttribs(element)) + }) + + //get page info + var pageRoot = xmlRoot.getElementsByTagName('pages')[0] + if (!pageRoot) + throw new Error('malformed file -- no element') + var pages = pageRoot.getElementsByTagName('page') + for (var i=0; i root" + result = result.font + + output.common = parseAttributes(result.common[0].$) + output.info = parseAttributes(result.info[0].$) + + for (var i = 0; i < result.pages.length; i++) { + var p = result.pages[i].page[0].$ + + if (typeof p.id === "undefined") + throw new Error("malformed file -- needs page id=N") + if (typeof p.file !== "string") + throw new Error("malformed file -- needs page file=\"path\"") + + output.pages[parseInt(p.id, 10)] = p.file + } + + if (result.chars) { + var chrArray = result.chars[0]['char'] || [] + for (var i = 0; i < chrArray.length; i++) { + output.chars.push(parseAttributes(chrArray[i].$)) + } + } + + if (result.kernings) { + var kernArray = result.kernings[0]['kerning'] || [] + for (var i = 0; i < kernArray.length; i++) { + output.kernings.push(parseAttributes(kernArray[i].$)) + } + } + }) + return output +} diff --git a/node_modules/parse-bmfont-xml/lib/parse-attribs.js b/node_modules/parse-bmfont-xml/lib/parse-attribs.js new file mode 100644 index 00000000..1dfba3b6 --- /dev/null +++ b/node_modules/parse-bmfont-xml/lib/parse-attribs.js @@ -0,0 +1,29 @@ +//Some versions of GlyphDesigner have a typo +//that causes some bugs with parsing. +//Need to confirm with recent version of the software +//to see whether this is still an issue or not. +var GLYPH_DESIGNER_ERROR = 'chasrset' + +module.exports = function parseAttributes(obj) { + obj = Object.assign({}, obj) + if (GLYPH_DESIGNER_ERROR in obj) { + obj['charset'] = obj[GLYPH_DESIGNER_ERROR] + delete obj[GLYPH_DESIGNER_ERROR] + } + + for (var k in obj) { + if (k === 'face' || k === 'charset') + continue + else if (k === 'padding' || k === 'spacing') + obj[k] = parseIntList(obj[k]) + else + obj[k] = parseInt(obj[k], 10) + } + return obj +} + +function parseIntList(data) { + return data.split(',').map(function(val) { + return parseInt(val, 10) + }) +} \ No newline at end of file diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/LICENSE b/node_modules/parse-bmfont-xml/node_modules/xml2js/LICENSE new file mode 100644 index 00000000..e3b4222a --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/LICENSE @@ -0,0 +1,19 @@ +Copyright 2010, 2011, 2012, 2013. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/README.md b/node_modules/parse-bmfont-xml/node_modules/xml2js/README.md new file mode 100644 index 00000000..67f2104a --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/README.md @@ -0,0 +1,507 @@ +node-xml2js +=========== + +Ever had the urge to parse XML? And wanted to access the data in some sane, +easy way? Don't want to compile a C parser, for whatever reason? Then xml2js is +what you're looking for! + +Description +=========== + +Simple XML to JavaScript object converter. It supports bi-directional conversion. +Uses [sax-js](https://github.com/isaacs/sax-js/) and +[xmlbuilder-js](https://github.com/oozcitak/xmlbuilder-js/). + +Note: If you're looking for a full DOM parser, you probably want +[JSDom](https://github.com/tmpvar/jsdom). + +Installation +============ + +Simplest way to install `xml2js` is to use [npm](http://npmjs.org), just `npm +install xml2js` which will download xml2js and all dependencies. + +xml2js is also available via [Bower](http://bower.io/), just `bower install +xml2js` which will download xml2js and all dependencies. + +Usage +===== + +No extensive tutorials required because you are a smart developer! The task of +parsing XML should be an easy one, so let's make it so! Here's some examples. + +Shoot-and-forget usage +---------------------- + +You want to parse XML as simple and easy as possible? It's dangerous to go +alone, take this: + +```javascript +var parseString = require('xml2js').parseString; +var xml = "Hello xml2js!" +parseString(xml, function (err, result) { + console.dir(result); +}); +``` + +Can't get easier than this, right? This works starting with `xml2js` 0.2.3. +With CoffeeScript it looks like this: + +```coffeescript +{parseString} = require 'xml2js' +xml = "Hello xml2js!" +parseString xml, (err, result) -> + console.dir result +``` + +If you need some special options, fear not, `xml2js` supports a number of +options (see below), you can specify these as second argument: + +```javascript +parseString(xml, {trim: true}, function (err, result) { +}); +``` + +Simple as pie usage +------------------- + +That's right, if you have been using xml-simple or a home-grown +wrapper, this was added in 0.1.11 just for you: + +```javascript +var fs = require('fs'), + xml2js = require('xml2js'); + +var parser = new xml2js.Parser(); +fs.readFile(__dirname + '/foo.xml', function(err, data) { + parser.parseString(data, function (err, result) { + console.dir(result); + console.log('Done'); + }); +}); +``` + +Look ma, no event listeners! + +You can also use `xml2js` from +[CoffeeScript](https://github.com/jashkenas/coffeescript), further reducing +the clutter: + +```coffeescript +fs = require 'fs', +xml2js = require 'xml2js' + +parser = new xml2js.Parser() +fs.readFile __dirname + '/foo.xml', (err, data) -> + parser.parseString data, (err, result) -> + console.dir result + console.log 'Done.' +``` + +But what happens if you forget the `new` keyword to create a new `Parser`? In +the middle of a nightly coding session, it might get lost, after all. Worry +not, we got you covered! Starting with 0.2.8 you can also leave it out, in +which case `xml2js` will helpfully add it for you, no bad surprises and +inexplicable bugs! + +Promise usage +------------- + +```javascript +var xml2js = require('xml2js'); +var xml = ''; + +// With parser +var parser = new xml2js.Parser(/* options */); +parser.parseStringPromise(xml).then(function (result) { + console.dir(result); + console.log('Done'); +}) +.catch(function (err) { + // Failed +}); + +// Without parser +xml2js.parseStringPromise(xml /*, options */).then(function (result) { + console.dir(result); + console.log('Done'); +}) +.catch(function (err) { + // Failed +}); +``` + +Parsing multiple files +---------------------- + +If you want to parse multiple files, you have multiple possibilities: + + * You can create one `xml2js.Parser` per file. That's the recommended one + and is promised to always *just work*. + * You can call `reset()` on your parser object. + * You can hope everything goes well anyway. This behaviour is not + guaranteed work always, if ever. Use option #1 if possible. Thanks! + +So you wanna some JSON? +----------------------- + +Just wrap the `result` object in a call to `JSON.stringify` like this +`JSON.stringify(result)`. You get a string containing the JSON representation +of the parsed object that you can feed to JSON-hungry consumers. + +Displaying results +------------------ + +You might wonder why, using `console.dir` or `console.log` the output at some +level is only `[Object]`. Don't worry, this is not because `xml2js` got lazy. +That's because Node uses `util.inspect` to convert the object into strings and +that function stops after `depth=2` which is a bit low for most XML. + +To display the whole deal, you can use `console.log(util.inspect(result, false, +null))`, which displays the whole result. + +So much for that, but what if you use +[eyes](https://github.com/cloudhead/eyes.js) for nice colored output and it +truncates the output with `…`? Don't fear, there's also a solution for that, +you just need to increase the `maxLength` limit by creating a custom inspector +`var inspect = require('eyes').inspector({maxLength: false})` and then you can +easily `inspect(result)`. + +XML builder usage +----------------- + +Since 0.4.0, objects can be also be used to build XML: + +```javascript +var xml2js = require('xml2js'); + +var obj = {name: "Super", Surname: "Man", age: 23}; + +var builder = new xml2js.Builder(); +var xml = builder.buildObject(obj); +``` +will result in: + +```xml + + + Super + Man + 23 + +``` + +At the moment, a one to one bi-directional conversion is guaranteed only for +default configuration, except for `attrkey`, `charkey` and `explicitArray` options +you can redefine to your taste. Writing CDATA is supported via setting the `cdata` +option to `true`. + +To specify attributes: +```javascript +var xml2js = require('xml2js'); + +var obj = {root: {$: {id: "my id"}, _: "my inner text"}}; + +var builder = new xml2js.Builder(); +var xml = builder.buildObject(obj); +``` +will result in: +```xml + +my inner text +``` + +### Adding xmlns attributes + +You can generate XML that declares XML namespace prefix / URI pairs with xmlns attributes. + +Example declaring a default namespace on the root element: + +```javascript +let obj = { + Foo: { + $: { + "xmlns": "http://foo.com" + } + } +}; +``` +Result of `buildObject(obj)`: +```xml + +``` +Example declaring non-default namespaces on non-root elements: +```javascript +let obj = { + 'foo:Foo': { + $: { + 'xmlns:foo': 'http://foo.com' + }, + 'bar:Bar': { + $: { + 'xmlns:bar': 'http://bar.com' + } + } + } +} +``` +Result of `buildObject(obj)`: +```xml + + + +``` + + +Processing attribute, tag names and values +------------------------------------------ + +Since 0.4.1 you can optionally provide the parser with attribute name and tag name processors as well as element value processors (Since 0.4.14, you can also optionally provide the parser with attribute value processors): + +```javascript + +function nameToUpperCase(name){ + return name.toUpperCase(); +} + +//transform all attribute and tag names and values to uppercase +parseString(xml, { + tagNameProcessors: [nameToUpperCase], + attrNameProcessors: [nameToUpperCase], + valueProcessors: [nameToUpperCase], + attrValueProcessors: [nameToUpperCase]}, + function (err, result) { + // processed data +}); +``` + +The `tagNameProcessors` and `attrNameProcessors` options +accept an `Array` of functions with the following signature: + +```javascript +function (name){ + //do something with `name` + return name +} +``` + +The `attrValueProcessors` and `valueProcessors` options +accept an `Array` of functions with the following signature: + +```javascript +function (value, name) { + //`name` will be the node name or attribute name + //do something with `value`, (optionally) dependent on the node/attr name + return value +} +``` + +Some processors are provided out-of-the-box and can be found in `lib/processors.js`: + +- `normalize`: transforms the name to lowercase. +(Automatically used when `options.normalize` is set to `true`) + +- `firstCharLowerCase`: transforms the first character to lower case. +E.g. 'MyTagName' becomes 'myTagName' + +- `stripPrefix`: strips the xml namespace prefix. E.g `` will become 'Bar'. +(N.B.: the `xmlns` prefix is NOT stripped.) + +- `parseNumbers`: parses integer-like strings as integers and float-like strings as floats +E.g. "0" becomes 0 and "15.56" becomes 15.56 + +- `parseBooleans`: parses boolean-like strings to booleans +E.g. "true" becomes true and "False" becomes false + +Options +======= + +Apart from the default settings, there are a number of options that can be +specified for the parser. Options are specified by ``new Parser({optionName: +value})``. Possible options are: + + * `attrkey` (default: `$`): Prefix that is used to access the attributes. + Version 0.1 default was `@`. + * `charkey` (default: `_`): Prefix that is used to access the character + content. Version 0.1 default was `#`. + * `explicitCharkey` (default: `false`) Determines whether or not to use + a `charkey` prefix for elements with no attributes. + * `trim` (default: `false`): Trim the whitespace at the beginning and end of + text nodes. + * `normalizeTags` (default: `false`): Normalize all tag names to lowercase. + * `normalize` (default: `false`): Trim whitespaces inside text nodes. + * `explicitRoot` (default: `true`): Set this if you want to get the root + node in the resulting object. + * `emptyTag` (default: `''`): what will the value of empty nodes be. In case + you want to use an empty object as a default value, it is better to provide a factory + function `() => ({})` instead. Without this function a plain object would + become a shared reference across all occurrences with unwanted behavior. + * `explicitArray` (default: `true`): Always put child nodes in an array if + true; otherwise an array is created only if there is more than one. + * `ignoreAttrs` (default: `false`): Ignore all XML attributes and only create + text nodes. + * `mergeAttrs` (default: `false`): Merge attributes and child elements as + properties of the parent, instead of keying attributes off a child + attribute object. This option is ignored if `ignoreAttrs` is `true`. + * `validator` (default `null`): You can specify a callable that validates + the resulting structure somehow, however you want. See unit tests + for an example. + * `xmlns` (default `false`): Give each element a field usually called '$ns' + (the first character is the same as attrkey) that contains its local name + and namespace URI. + * `explicitChildren` (default `false`): Put child elements to separate + property. Doesn't work with `mergeAttrs = true`. If element has no children + then "children" won't be created. Added in 0.2.5. + * `childkey` (default `$$`): Prefix that is used to access child elements if + `explicitChildren` is set to `true`. Added in 0.2.5. + * `preserveChildrenOrder` (default `false`): Modifies the behavior of + `explicitChildren` so that the value of the "children" property becomes an + ordered array. When this is `true`, every node will also get a `#name` field + whose value will correspond to the XML nodeName, so that you may iterate + the "children" array and still be able to determine node names. The named + (and potentially unordered) properties are also retained in this + configuration at the same level as the ordered "children" array. Added in + 0.4.9. + * `charsAsChildren` (default `false`): Determines whether chars should be + considered children if `explicitChildren` is on. Added in 0.2.5. + * `includeWhiteChars` (default `false`): Determines whether whitespace-only + text nodes should be included. Added in 0.4.17. + * `async` (default `false`): Should the callbacks be async? This *might* be + an incompatible change if your code depends on sync execution of callbacks. + Future versions of `xml2js` might change this default, so the recommendation + is to not depend on sync execution anyway. Added in 0.2.6. + * `strict` (default `true`): Set sax-js to strict or non-strict parsing mode. + Defaults to `true` which is *highly* recommended, since parsing HTML which + is not well-formed XML might yield just about anything. Added in 0.2.7. + * `attrNameProcessors` (default: `null`): Allows the addition of attribute + name processing functions. Accepts an `Array` of functions with following + signature: + ```javascript + function (name){ + //do something with `name` + return name + } + ``` + Added in 0.4.14 + * `attrValueProcessors` (default: `null`): Allows the addition of attribute + value processing functions. Accepts an `Array` of functions with following + signature: + ```javascript + function (value, name){ + //do something with `name` + return name + } + ``` + Added in 0.4.1 + * `tagNameProcessors` (default: `null`): Allows the addition of tag name + processing functions. Accepts an `Array` of functions with following + signature: + ```javascript + function (name){ + //do something with `name` + return name + } + ``` + Added in 0.4.1 + * `valueProcessors` (default: `null`): Allows the addition of element value + processing functions. Accepts an `Array` of functions with following + signature: + ```javascript + function (value, name){ + //do something with `name` + return name + } + ``` + Added in 0.4.6 + +Options for the `Builder` class +------------------------------- +These options are specified by ``new Builder({optionName: value})``. +Possible options are: + + * `attrkey` (default: `$`): Prefix that is used to access the attributes. + Version 0.1 default was `@`. + * `charkey` (default: `_`): Prefix that is used to access the character + content. Version 0.1 default was `#`. + * `rootName` (default `root` or the root key name): root element name to be used in case + `explicitRoot` is `false` or to override the root element name. + * `renderOpts` (default `{ 'pretty': true, 'indent': ' ', 'newline': '\n' }`): + Rendering options for xmlbuilder-js. + * pretty: prettify generated XML + * indent: whitespace for indentation (only when pretty) + * newline: newline char (only when pretty) + * `xmldec` (default `{ 'version': '1.0', 'encoding': 'UTF-8', 'standalone': true }`: + XML declaration attributes. + * `xmldec.version` A version number string, e.g. 1.0 + * `xmldec.encoding` Encoding declaration, e.g. UTF-8 + * `xmldec.standalone` standalone document declaration: true or false + * `doctype` (default `null`): optional DTD. Eg. `{'ext': 'hello.dtd'}` + * `headless` (default: `false`): omit the XML header. Added in 0.4.3. + * `allowSurrogateChars` (default: `false`): allows using characters from the Unicode + surrogate blocks. + * `cdata` (default: `false`): wrap text nodes in `` instead of + escaping when necessary. Does not add `` if it is not required. + Added in 0.4.5. + +`renderOpts`, `xmldec`,`doctype` and `headless` pass through to +[xmlbuilder-js](https://github.com/oozcitak/xmlbuilder-js). + +Updating to new version +======================= + +Version 0.2 changed the default parsing settings, but version 0.1.14 introduced +the default settings for version 0.2, so these settings can be tried before the +migration. + +```javascript +var xml2js = require('xml2js'); +var parser = new xml2js.Parser(xml2js.defaults["0.2"]); +``` + +To get the 0.1 defaults in version 0.2 you can just use +`xml2js.defaults["0.1"]` in the same place. This provides you with enough time +to migrate to the saner way of parsing in `xml2js` 0.2. We try to make the +migration as simple and gentle as possible, but some breakage cannot be +avoided. + +So, what exactly did change and why? In 0.2 we changed some defaults to parse +the XML in a more universal and sane way. So we disabled `normalize` and `trim` +so `xml2js` does not cut out any text content. You can reenable this at will of +course. A more important change is that we return the root tag in the resulting +JavaScript structure via the `explicitRoot` setting, so you need to access the +first element. This is useful for anybody who wants to know what the root node +is and preserves more information. The last major change was to enable +`explicitArray`, so everytime it is possible that one might embed more than one +sub-tag into a tag, xml2js >= 0.2 returns an array even if the array just +includes one element. This is useful when dealing with APIs that return +variable amounts of subtags. + +Running tests, development +========================== + +[![Build Status](https://travis-ci.org/Leonidas-from-XIV/node-xml2js.svg?branch=master)](https://travis-ci.org/Leonidas-from-XIV/node-xml2js) +[![Coverage Status](https://coveralls.io/repos/Leonidas-from-XIV/node-xml2js/badge.svg?branch=)](https://coveralls.io/r/Leonidas-from-XIV/node-xml2js?branch=master) +[![Dependency Status](https://david-dm.org/Leonidas-from-XIV/node-xml2js.svg)](https://david-dm.org/Leonidas-from-XIV/node-xml2js) + +The development requirements are handled by npm, you just need to install them. +We also have a number of unit tests, they can be run using `npm test` directly +from the project root. This runs zap to discover all the tests and execute +them. + +If you like to contribute, keep in mind that `xml2js` is written in +CoffeeScript, so don't develop on the JavaScript files that are checked into +the repository for convenience reasons. Also, please write some unit test to +check your behaviour and if it is some user-facing thing, add some +documentation to this README, so people will know it exists. Thanks in advance! + +Getting support +=============== + +Please, if you have a problem with the library, first make sure you read this +README. If you read this far, thanks, you're good. Then, please make sure your +problem really is with `xml2js`. It is? Okay, then I'll look at it. Send me a +mail and we can talk. Please don't open issues, as I don't think that is the +proper forum for support problems. Some problems might as well really be bugs +in `xml2js`, if so I'll let you know to open an issue instead :) + +But if you know you really found a bug, feel free to open an issue instead. diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/bom.js b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/bom.js new file mode 100644 index 00000000..7b8fb27b --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/bom.js @@ -0,0 +1,12 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + exports.stripBOM = function(str) { + if (str[0] === '\uFEFF') { + return str.substring(1); + } else { + return str; + } + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/builder.js b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/builder.js new file mode 100644 index 00000000..58f36384 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/builder.js @@ -0,0 +1,127 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA, + hasProp = {}.hasOwnProperty; + + builder = require('xmlbuilder'); + + defaults = require('./defaults').defaults; + + requiresCDATA = function(entry) { + return typeof entry === "string" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0); + }; + + wrapCDATA = function(entry) { + return ""; + }; + + escapeCDATA = function(entry) { + return entry.replace(']]>', ']]]]>'); + }; + + exports.Builder = (function() { + function Builder(opts) { + var key, ref, value; + this.options = {}; + ref = defaults["0.2"]; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this.options[key] = value; + } + for (key in opts) { + if (!hasProp.call(opts, key)) continue; + value = opts[key]; + this.options[key] = value; + } + } + + Builder.prototype.buildObject = function(rootObj) { + var attrkey, charkey, render, rootElement, rootName; + attrkey = this.options.attrkey; + charkey = this.options.charkey; + if ((Object.keys(rootObj).length === 1) && (this.options.rootName === defaults['0.2'].rootName)) { + rootName = Object.keys(rootObj)[0]; + rootObj = rootObj[rootName]; + } else { + rootName = this.options.rootName; + } + render = (function(_this) { + return function(element, obj) { + var attr, child, entry, index, key, value; + if (typeof obj !== 'object') { + if (_this.options.cdata && requiresCDATA(obj)) { + element.raw(wrapCDATA(obj)); + } else { + element.txt(obj); + } + } else if (Array.isArray(obj)) { + for (index in obj) { + if (!hasProp.call(obj, index)) continue; + child = obj[index]; + for (key in child) { + entry = child[key]; + element = render(element.ele(key), entry).up(); + } + } + } else { + for (key in obj) { + if (!hasProp.call(obj, key)) continue; + child = obj[key]; + if (key === attrkey) { + if (typeof child === "object") { + for (attr in child) { + value = child[attr]; + element = element.att(attr, value); + } + } + } else if (key === charkey) { + if (_this.options.cdata && requiresCDATA(child)) { + element = element.raw(wrapCDATA(child)); + } else { + element = element.txt(child); + } + } else if (Array.isArray(child)) { + for (index in child) { + if (!hasProp.call(child, index)) continue; + entry = child[index]; + if (typeof entry === 'string') { + if (_this.options.cdata && requiresCDATA(entry)) { + element = element.ele(key).raw(wrapCDATA(entry)).up(); + } else { + element = element.ele(key, entry).up(); + } + } else { + element = render(element.ele(key), entry).up(); + } + } + } else if (typeof child === "object") { + element = render(element.ele(key), child).up(); + } else { + if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) { + element = element.ele(key).raw(wrapCDATA(child)).up(); + } else { + if (child == null) { + child = ''; + } + element = element.ele(key, child.toString()).up(); + } + } + } + } + return element; + }; + })(this); + rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, { + headless: this.options.headless, + allowSurrogateChars: this.options.allowSurrogateChars + }); + return render(rootElement, rootObj).end(this.options.renderOpts); + }; + + return Builder; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/defaults.js b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/defaults.js new file mode 100644 index 00000000..0a21da0a --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/defaults.js @@ -0,0 +1,72 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + exports.defaults = { + "0.1": { + explicitCharkey: false, + trim: true, + normalize: true, + normalizeTags: false, + attrkey: "@", + charkey: "#", + explicitArray: false, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: false, + validator: null, + xmlns: false, + explicitChildren: false, + childkey: '@@', + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: null, + attrValueProcessors: null, + tagNameProcessors: null, + valueProcessors: null, + emptyTag: '' + }, + "0.2": { + explicitCharkey: false, + trim: false, + normalize: false, + normalizeTags: false, + attrkey: "$", + charkey: "_", + explicitArray: true, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: true, + validator: null, + xmlns: false, + explicitChildren: false, + preserveChildrenOrder: false, + childkey: '$$', + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: null, + attrValueProcessors: null, + tagNameProcessors: null, + valueProcessors: null, + rootName: 'root', + xmldec: { + 'version': '1.0', + 'encoding': 'UTF-8', + 'standalone': true + }, + doctype: null, + renderOpts: { + 'pretty': true, + 'indent': ' ', + 'newline': '\n' + }, + headless: false, + chunkSize: 10000, + emptyTag: '', + cdata: false + } + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/parser.js b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/parser.js new file mode 100644 index 00000000..192382d3 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/parser.js @@ -0,0 +1,385 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var bom, defaults, events, isEmpty, processItem, processors, sax, setImmediate, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + sax = require('sax'); + + events = require('events'); + + bom = require('./bom'); + + processors = require('./processors'); + + setImmediate = require('timers').setImmediate; + + defaults = require('./defaults').defaults; + + isEmpty = function(thing) { + return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0; + }; + + processItem = function(processors, item, key) { + var i, len, process; + for (i = 0, len = processors.length; i < len; i++) { + process = processors[i]; + item = process(item, key); + } + return item; + }; + + exports.Parser = (function(superClass) { + extend(Parser, superClass); + + function Parser(opts) { + this.parseStringPromise = bind(this.parseStringPromise, this); + this.parseString = bind(this.parseString, this); + this.reset = bind(this.reset, this); + this.assignOrPush = bind(this.assignOrPush, this); + this.processAsync = bind(this.processAsync, this); + var key, ref, value; + if (!(this instanceof exports.Parser)) { + return new exports.Parser(opts); + } + this.options = {}; + ref = defaults["0.2"]; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this.options[key] = value; + } + for (key in opts) { + if (!hasProp.call(opts, key)) continue; + value = opts[key]; + this.options[key] = value; + } + if (this.options.xmlns) { + this.options.xmlnskey = this.options.attrkey + "ns"; + } + if (this.options.normalizeTags) { + if (!this.options.tagNameProcessors) { + this.options.tagNameProcessors = []; + } + this.options.tagNameProcessors.unshift(processors.normalize); + } + this.reset(); + } + + Parser.prototype.processAsync = function() { + var chunk, err; + try { + if (this.remaining.length <= this.options.chunkSize) { + chunk = this.remaining; + this.remaining = ''; + this.saxParser = this.saxParser.write(chunk); + return this.saxParser.close(); + } else { + chunk = this.remaining.substr(0, this.options.chunkSize); + this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length); + this.saxParser = this.saxParser.write(chunk); + return setImmediate(this.processAsync); + } + } catch (error1) { + err = error1; + if (!this.saxParser.errThrown) { + this.saxParser.errThrown = true; + return this.emit(err); + } + } + }; + + Parser.prototype.assignOrPush = function(obj, key, newValue) { + if (!(key in obj)) { + if (!this.options.explicitArray) { + return obj[key] = newValue; + } else { + return obj[key] = [newValue]; + } + } else { + if (!(obj[key] instanceof Array)) { + obj[key] = [obj[key]]; + } + return obj[key].push(newValue); + } + }; + + Parser.prototype.reset = function() { + var attrkey, charkey, ontext, stack; + this.removeAllListeners(); + this.saxParser = sax.parser(this.options.strict, { + trim: false, + normalize: false, + xmlns: this.options.xmlns + }); + this.saxParser.errThrown = false; + this.saxParser.onerror = (function(_this) { + return function(error) { + _this.saxParser.resume(); + if (!_this.saxParser.errThrown) { + _this.saxParser.errThrown = true; + return _this.emit("error", error); + } + }; + })(this); + this.saxParser.onend = (function(_this) { + return function() { + if (!_this.saxParser.ended) { + _this.saxParser.ended = true; + return _this.emit("end", _this.resultObject); + } + }; + })(this); + this.saxParser.ended = false; + this.EXPLICIT_CHARKEY = this.options.explicitCharkey; + this.resultObject = null; + stack = []; + attrkey = this.options.attrkey; + charkey = this.options.charkey; + this.saxParser.onopentag = (function(_this) { + return function(node) { + var key, newValue, obj, processedKey, ref; + obj = Object.create(null); + obj[charkey] = ""; + if (!_this.options.ignoreAttrs) { + ref = node.attributes; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + if (!(attrkey in obj) && !_this.options.mergeAttrs) { + obj[attrkey] = Object.create(null); + } + newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; + processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; + if (_this.options.mergeAttrs) { + _this.assignOrPush(obj, processedKey, newValue); + } else { + obj[attrkey][processedKey] = newValue; + } + } + } + obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name; + if (_this.options.xmlns) { + obj[_this.options.xmlnskey] = { + uri: node.uri, + local: node.local + }; + } + return stack.push(obj); + }; + })(this); + this.saxParser.onclosetag = (function(_this) { + return function() { + var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath; + obj = stack.pop(); + nodeName = obj["#name"]; + if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) { + delete obj["#name"]; + } + if (obj.cdata === true) { + cdata = obj.cdata; + delete obj.cdata; + } + s = stack[stack.length - 1]; + if (obj[charkey].match(/^\s*$/) && !cdata) { + emptyStr = obj[charkey]; + delete obj[charkey]; + } else { + if (_this.options.trim) { + obj[charkey] = obj[charkey].trim(); + } + if (_this.options.normalize) { + obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim(); + } + obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey]; + if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { + obj = obj[charkey]; + } + } + if (isEmpty(obj)) { + if (typeof _this.options.emptyTag === 'function') { + obj = _this.options.emptyTag(); + } else { + obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; + } + } + if (_this.options.validator != null) { + xpath = "/" + ((function() { + var i, len, results; + results = []; + for (i = 0, len = stack.length; i < len; i++) { + node = stack[i]; + results.push(node["#name"]); + } + return results; + })()).concat(nodeName).join("/"); + (function() { + var err; + try { + return obj = _this.options.validator(xpath, s && s[nodeName], obj); + } catch (error1) { + err = error1; + return _this.emit("error", err); + } + })(); + } + if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { + if (!_this.options.preserveChildrenOrder) { + node = Object.create(null); + if (_this.options.attrkey in obj) { + node[_this.options.attrkey] = obj[_this.options.attrkey]; + delete obj[_this.options.attrkey]; + } + if (!_this.options.charsAsChildren && _this.options.charkey in obj) { + node[_this.options.charkey] = obj[_this.options.charkey]; + delete obj[_this.options.charkey]; + } + if (Object.getOwnPropertyNames(obj).length > 0) { + node[_this.options.childkey] = obj; + } + obj = node; + } else if (s) { + s[_this.options.childkey] = s[_this.options.childkey] || []; + objClone = Object.create(null); + for (key in obj) { + if (!hasProp.call(obj, key)) continue; + objClone[key] = obj[key]; + } + s[_this.options.childkey].push(objClone); + delete obj["#name"]; + if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { + obj = obj[charkey]; + } + } + } + if (stack.length > 0) { + return _this.assignOrPush(s, nodeName, obj); + } else { + if (_this.options.explicitRoot) { + old = obj; + obj = Object.create(null); + obj[nodeName] = old; + } + _this.resultObject = obj; + _this.saxParser.ended = true; + return _this.emit("end", _this.resultObject); + } + }; + })(this); + ontext = (function(_this) { + return function(text) { + var charChild, s; + s = stack[stack.length - 1]; + if (s) { + s[charkey] += text; + if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, '').trim() !== '')) { + s[_this.options.childkey] = s[_this.options.childkey] || []; + charChild = { + '#name': '__text__' + }; + charChild[charkey] = text; + if (_this.options.normalize) { + charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim(); + } + s[_this.options.childkey].push(charChild); + } + return s; + } + }; + })(this); + this.saxParser.ontext = ontext; + return this.saxParser.oncdata = (function(_this) { + return function(text) { + var s; + s = ontext(text); + if (s) { + return s.cdata = true; + } + }; + })(this); + }; + + Parser.prototype.parseString = function(str, cb) { + var err; + if ((cb != null) && typeof cb === "function") { + this.on("end", function(result) { + this.reset(); + return cb(null, result); + }); + this.on("error", function(err) { + this.reset(); + return cb(err); + }); + } + try { + str = str.toString(); + if (str.trim() === '') { + this.emit("end", null); + return true; + } + str = bom.stripBOM(str); + if (this.options.async) { + this.remaining = str; + setImmediate(this.processAsync); + return this.saxParser; + } + return this.saxParser.write(str).close(); + } catch (error1) { + err = error1; + if (!(this.saxParser.errThrown || this.saxParser.ended)) { + this.emit('error', err); + return this.saxParser.errThrown = true; + } else if (this.saxParser.ended) { + throw err; + } + } + }; + + Parser.prototype.parseStringPromise = function(str) { + return new Promise((function(_this) { + return function(resolve, reject) { + return _this.parseString(str, function(err, value) { + if (err) { + return reject(err); + } else { + return resolve(value); + } + }); + }; + })(this)); + }; + + return Parser; + + })(events); + + exports.parseString = function(str, a, b) { + var cb, options, parser; + if (b != null) { + if (typeof b === 'function') { + cb = b; + } + if (typeof a === 'object') { + options = a; + } + } else { + if (typeof a === 'function') { + cb = a; + } + options = {}; + } + parser = new exports.Parser(options); + return parser.parseString(str, cb); + }; + + exports.parseStringPromise = function(str, a) { + var options, parser; + if (typeof a === 'object') { + options = a; + } + parser = new exports.Parser(options); + return parser.parseStringPromise(str); + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/processors.js b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/processors.js new file mode 100644 index 00000000..89aa85f2 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/processors.js @@ -0,0 +1,34 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var prefixMatch; + + prefixMatch = new RegExp(/(?!xmlns)^.*:/); + + exports.normalize = function(str) { + return str.toLowerCase(); + }; + + exports.firstCharLowerCase = function(str) { + return str.charAt(0).toLowerCase() + str.slice(1); + }; + + exports.stripPrefix = function(str) { + return str.replace(prefixMatch, ''); + }; + + exports.parseNumbers = function(str) { + if (!isNaN(str)) { + str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str); + } + return str; + }; + + exports.parseBooleans = function(str) { + if (/^(?:true|false)$/i.test(str)) { + str = str.toLowerCase() === 'true'; + } + return str; + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/xml2js.js b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/xml2js.js new file mode 100644 index 00000000..24b6e699 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/lib/xml2js.js @@ -0,0 +1,39 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var builder, defaults, parser, processors, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + defaults = require('./defaults'); + + builder = require('./builder'); + + parser = require('./parser'); + + processors = require('./processors'); + + exports.defaults = defaults.defaults; + + exports.processors = processors; + + exports.ValidationError = (function(superClass) { + extend(ValidationError, superClass); + + function ValidationError(message) { + this.message = message; + } + + return ValidationError; + + })(Error); + + exports.Builder = builder.Builder; + + exports.Parser = parser.Parser; + + exports.parseString = parser.parseString; + + exports.parseStringPromise = parser.parseStringPromise; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xml2js/package.json b/node_modules/parse-bmfont-xml/node_modules/xml2js/package.json new file mode 100644 index 00000000..bc8eb663 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xml2js/package.json @@ -0,0 +1,93 @@ +{ + "name": "xml2js", + "description": "Simple XML to JavaScript object converter.", + "keywords": [ + "xml", + "json" + ], + "homepage": "https://github.com/Leonidas-from-XIV/node-xml2js", + "version": "0.5.0", + "author": "Marek Kubica (https://xivilization.net)", + "contributors": [ + "maqr (https://github.com/maqr)", + "Ben Weaver (http://benweaver.com/)", + "Jae Kwon (https://github.com/jaekwon)", + "Jim Robert", + "Ștefan Rusu (http://www.saltwaterc.eu/)", + "Carter Cole (http://cartercole.com/)", + "Kurt Raschke (http://www.kurtraschke.com/)", + "Contra (https://github.com/Contra)", + "Marcelo Diniz (https://github.com/mdiniz)", + "Michael Hart (https://github.com/mhart)", + "Zachary Scott (http://zacharyscott.net/)", + "Raoul Millais (https://github.com/raoulmillais)", + "Salsita Software (http://www.salsitasoft.com/)", + "Mike Schilling (http://www.emotive.com/)", + "Jackson Tian (http://weibo.com/shyvo)", + "Mikhail Zyatin (https://github.com/Sitin)", + "Chris Tavares (https://github.com/christav)", + "Frank Xu (http://f2e.us/)", + "Guido D'Albore (http://www.bitstorm.it/)", + "Jack Senechal (http://jacksenechal.com/)", + "Matthias Hölzl (https://github.com/hoelzl)", + "Camille Reynders (http://www.creynders.be/)", + "Taylor Gautier (https://github.com/tsgautier)", + "Todd Bryan (https://github.com/toddrbryan)", + "Leore Avidar (http://leoreavidar.com/)", + "Dave Aitken (http://www.actionshrimp.com/)", + "Shaney Orrowe ", + "Candle ", + "Jess Telford (http://jes.st)", + "Tom Hughes < (http://compton.nu/)", + "Piotr Rochala (http://rocha.la/)", + "Michael Avila (https://github.com/michaelavila)", + "Ryan Gahl (https://github.com/ryedin)", + "Eric Laberge (https://github.com/elaberge)", + "Benjamin E. Coe (https://twitter.com/benjamincoe)", + "Stephen Cresswell (https://github.com/cressie176)", + "Pascal Ehlert (http://www.hacksrus.net/)", + "Tom Spencer (http://fiznool.com/)", + "Tristian Flanagan (https://github.com/tflanagan)", + "Tim Johns (https://github.com/TimJohns)", + "Bogdan Chadkin (https://github.com/TrySound)", + "David Wood (http://codesleuth.co.uk/)", + "Nicolas Maquet (https://github.com/nmaquet)", + "Lovell Fuller (http://lovell.info/)", + "d3adc0d3 (https://github.com/d3adc0d3)", + "James Crosby (https://github.com/autopulated)" + ], + "main": "./lib/xml2js", + "files": [ + "lib" + ], + "directories": { + "lib": "./lib" + }, + "scripts": { + "build": "cake build", + "test": "zap", + "coverage": "nyc npm test && nyc report", + "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls", + "doc": "cake doc" + }, + "repository": { + "type": "git", + "url": "https://github.com/Leonidas-from-XIV/node-xml2js.git" + }, + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "devDependencies": { + "coffee-script": ">=1.10.0", + "coveralls": "^3.0.1", + "diff": ">=1.0.8", + "docco": ">=0.6.2", + "nyc": ">=2.2.1", + "zap": ">=0.2.9" + }, + "engines": { + "node": ">=4.0.0" + }, + "license": "MIT" +} diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/CHANGELOG.md b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/CHANGELOG.md new file mode 100644 index 00000000..610f412e --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/CHANGELOG.md @@ -0,0 +1,470 @@ +# Change Log + +All notable changes to this project are documented in this file. This project adheres to [Semantic Versioning](http://semver.org/#semantic-versioning-200). + +## [11.0.0] - 2019-02-18 +- Calling `end()` with arguments no longer overwrites writer options. See [#120](https://github.com/oozcitak/xmlbuilder-js/issues/120). +- Added writer state and customizable space and endline functions to help customize writer behavior. Also added `openNode` and `closeNode` functions to writer. See [#193](https://github.com/oozcitak/xmlbuilder-js/issues/193). +- Fixed a bug where writer functions would not be called for nodes with a single child node in pretty print mode. See [#195](https://github.com/oozcitak/xmlbuilder-js/issues/195). +- Renamed `elEscape` to `textEscape` in `XMLStringifier`. +- Fixed a bug where empty arrays would produce child nodes. See [#190](https://github.com/oozcitak/xmlbuilder-js/issues/190). +- Removed the `skipNullAttributes` option. `null` attributes are now skipped by default. Added the `keepNullAttributes` option in case someone needs the old behavior. +- Removed the `skipNullNodes` option. `null` nodes are now skipped by default. Added the `keepNullNodes` option in case someone needs the old behavior. +- `undefined` values are now skipped when converting JS objects. +- Renamed stringify functions. See [#194](https://github.com/oozcitak/xmlbuilder-js/issues/194): + * `eleName` -> `name` + * `attName` -> `name` + * `eleText` -> `text` +- Fixed argument order for `attribute` function in the writer. See [#196](https://github.com/oozcitak/xmlbuilder-js/issues/196). +- Added `openAttribute` and `closeAttribute` functions to writer. See [#196](https://github.com/oozcitak/xmlbuilder-js/issues/196). +- Added node types to node objects. Node types and writer states are exported by the module with the `nodeType` and `writerState` properties. +- Fixed a bug where array items would not be correctly converted. See [#159](https://github.com/oozcitak/xmlbuilder-js/issues/159). +- Fixed a bug where mixed-content inside JS objects with `#text` decorator would not be correctly converted. See [#171](https://github.com/oozcitak/xmlbuilder-js/issues/171). +- Fixed a bug where JS objects would not be expanded in callback mode. See [#173](https://github.com/oozcitak/xmlbuilder-js/issues/173). +- Fixed a bug where character validation would not obey document's XML version. Added separate validation for XML 1.0 and XML 1.1 documents. See [#169](https://github.com/oozcitak/xmlbuilder-js/issues/169). +- Fixed a bug where names would not be validated according to the spec. See [#49](https://github.com/oozcitak/xmlbuilder-js/issues/49). +- Renamed `text` property to `value` in comment and cdata nodes to unify the API. +- Removed `doctype` function to prevent name clash with DOM implementation. Use the `dtd` function instead. +- Removed dummy nodes from the XML tree (Those were created while chain-building the tree). +- Renamed `attributes`property to `attribs` to prevent name clash with DOM property with the same name. +- Implemented the DOM standard (read-only) to support XPath lookups. XML namespaces are not currently supported. See [#122](https://github.com/oozcitak/xmlbuilder-js/issues/122). + +## [10.1.1] - 2018-10-24 +- Fixed an edge case where a null node at root level would be printed although `skipNullNodes` was set. See [#187](https://github.com/oozcitak/xmlbuilder-js/issues/187). + +## [10.1.0] - 2018-10-10 +- Added the `skipNullNodes` option to skip nodes with null values. See [#158](https://github.com/oozcitak/xmlbuilder-js/issues/158). + +## [10.0.0] - 2018-04-26 +- Added current indentation level as a parameter to the onData function when in callback mode. See [#125](https://github.com/oozcitak/xmlbuilder-js/issues/125). +- Added name of the current node and parent node to error messages where possible. See [#152](https://github.com/oozcitak/xmlbuilder-js/issues/152). This has the potential to break code depending on the content of error messages. +- Fixed an issue where objects created with Object.create(null) created an error. See [#176](https://github.com/oozcitak/xmlbuilder-js/issues/176). +- Added test builds for node.js v8 and v10. + +## [9.0.7] - 2018-02-09 +- Simplified regex used for validating encoding. + +## [9.0.4] - 2017-08-16 +- `spacebeforeslash` writer option accepts `true` as well as space char(s). + +## [9.0.3] - 2017-08-15 +- `spacebeforeslash` writer option can now be used with XML fragments. + +## [9.0.2] - 2017-08-15 +- Added the `spacebeforeslash` writer option to add a space character before closing tags of empty elements. See +[#157](https://github.com/oozcitak/xmlbuilder-js/issues/157). + +## [9.0.1] - 2017-06-19 +- Fixed character validity checks to work with node.js 4.0 and 5.0. See +[#161](https://github.com/oozcitak/xmlbuilder-js/issues/161). + +## [9.0.0] - 2017-05-05 +- Removed case conversion options. +- Removed support for node.js 4.0 and 5.0. Minimum required version is now 6.0. +- Fixed valid char filter to use XML 1.1 instead of 1.0. See +[#147](https://github.com/oozcitak/xmlbuilder-js/issues/147). +- Added options for negative indentation and suppressing pretty printing of text +nodes. See +[#145](https://github.com/oozcitak/xmlbuilder-js/issues/145). + +## [8.2.2] - 2016-04-08 +- Falsy values can now be used as a text node in callback mode. + +## [8.2.1] - 2016-04-07 +- Falsy values can now be used as a text node. See +[#117](https://github.com/oozcitak/xmlbuilder-js/issues/117). + +## [8.2.0] - 2016-04-01 +- Removed lodash dependency to keep the library small and simple. See +[#114](https://github.com/oozcitak/xmlbuilder-js/issues/114), +[#53](https://github.com/oozcitak/xmlbuilder-js/issues/53), +and [#43](https://github.com/oozcitak/xmlbuilder-js/issues/43). +- Added title case to name conversion options. + +## [8.1.0] - 2016-03-29 +- Added the callback option to the `begin` export function. When used with a +callback function, the XML document will be generated in chunks and each chunk +will be passed to the supplied function. In this mode, `begin` uses a different +code path and the builder should use much less memory since the entire XML tree +is not kept. There are a few drawbacks though. For example, traversing the document +tree or adding attributes to a node after it is written is not possible. It is +also not possible to remove nodes or attributes. + +``` js +var result = ''; + +builder.begin(function(chunk) { result += chunk; }) + .dec() + .ele('root') + .ele('xmlbuilder').up() + .end(); +``` + +- Replaced native `Object.assign` with `lodash.assign` to support old JS engines. See [#111](https://github.com/oozcitak/xmlbuilder-js/issues/111). + +## [8.0.0] - 2016-03-25 +- Added the `begin` export function. See the wiki for details. +- Added the ability to add comments and processing instructions before and after the root element. Added `commentBefore`, `commentAfter`, `instructionBefore` and `instructionAfter` functions for this purpose. +- Dropped support for old node.js releases. Minimum required node.js version is now 4.0. + +## [7.0.0] - 2016-03-21 +- Processing instructions are now created as regular nodes. This is a major breaking change if you are using processing instructions. Previously processing instructions were inserted before their parent node. After this change processing instructions are appended to the children of the parent node. Note that it is not currently possible to insert processing instructions before or after the root element. +```js +root.ele('node').ins('pi'); +// pre-v7 + +// v7 + +``` + +## [6.0.0] - 2016-03-20 +- Added custom XML writers. The default string conversion functions are now collected under the `XMLStringWriter` class which can be accessed by the `stringWriter(options)` function exported by the module. An `XMLStreamWriter` is also added which outputs the XML document to a writable stream. A stream writer can be created by calling the `streamWriter(stream, options)` function exported by the module. Both classes are heavily customizable and the details are added to the wiki. It is also possible to write an XML writer from scratch and use it when calling `end()` on the XML document. + +## [5.0.1] - 2016-03-08 +- Moved require statements for text case conversion to the top of files to reduce lazy requires. + +## [5.0.0] - 2016-03-05 +- Added text case option for element names and attribute names. Valid cases are `lower`, `upper`, `camel`, `kebab` and `snake`. +- Attribute and element values are escaped according to the [Canonical XML 1.0 specification](http://www.w3.org/TR/2000/WD-xml-c14n-20000119.html#charescaping). See [#54](https://github.com/oozcitak/xmlbuilder-js/issues/54) and [#86](https://github.com/oozcitak/xmlbuilder-js/issues/86). +- Added the `allowEmpty` option to `end()`. When this option is set, empty elements are not self-closed. +- Added support for [nested CDATA](https://en.wikipedia.org/wiki/CDATA#Nesting). The triad `]]>` in CDATA is now automatically replaced with `]]]]>`. + +## [4.2.1] - 2016-01-15 +- Updated lodash dependency to 4.0.0. + +## [4.2.0] - 2015-12-16 +- Added the `noDoubleEncoding` option to `create()` to control whether existing html entities are encoded. + +## [4.1.0] - 2015-11-11 +- Added the `separateArrayItems` option to `create()` to control how arrays are handled when converting from objects. e.g. + +```js +root.ele({ number: [ "one", "two" ]}); +// with separateArrayItems: true + + + + +// with separateArrayItems: false +one +two +``` + +## [4.0.0] - 2015-11-01 +- Removed the `#list` decorator. Array items are now created as child nodes by default. +- Fixed a bug where the XML encoding string was checked partially. + +## [3.1.0] - 2015-09-19 +- `#list` decorator ignores empty arrays. + +## [3.0.0] - 2015-09-10 +- Allow `\r`, `\n` and `\t` in attribute values without escaping. See [#86](https://github.com/oozcitak/xmlbuilder-js/issues/86). + +## [2.6.5] - 2015-09-09 +- Use native `isArray` instead of lodash. +- Indentation of processing instructions are set to the parent element's. + +## [2.6.4] - 2015-05-27 +- Updated lodash dependency to 3.5.0. + +## [2.6.3] - 2015-05-27 +- Bumped version because previous release was not published on npm. + +## [2.6.2] - 2015-03-10 +- Updated lodash dependency to 3.5.0. + +## [2.6.1] - 2015-02-20 +- Updated lodash dependency to 3.3.0. + +## [2.6.0] - 2015-02-20 +- Fixed a bug where the `XMLNode` constructor overwrote the super class parent. +- Removed document property from cloned nodes. +- Switched to mocha.js for testing. + +## [2.5.2] - 2015-02-16 +- Updated lodash dependency to 3.2.0. + +## [2.5.1] - 2015-02-09 +- Updated lodash dependency to 3.1.0. +- Support all node >= 0.8. + +## [2.5.0] - 2015-00-03 +- Updated lodash dependency to 3.0.0. + +## [2.4.6] - 2015-01-26 +- Show more information from attribute creation with null values. +- Added iojs as an engine. +- Self close elements with empty text. + +## [2.4.5] - 2014-11-15 +- Fixed prepublish script to run on windows. +- Fixed bug in XMLStringifier where an undefined value was used while reporting an invalid encoding value. +- Moved require statements to the top of files to reduce lazy requires. See [#62](https://github.com/oozcitak/xmlbuilder-js/issues/62). + +## [2.4.4] - 2014-09-08 +- Added the `offset` option to `toString()` for use in XML fragments. + +## [2.4.3] - 2014-08-13 +- Corrected license in package description. + +## [2.4.2] - 2014-08-13 +- Dropped performance test and memwatch dependency. + +## [2.4.1] - 2014-08-12 +- Fixed a bug where empty indent string was omitted when pretty printing. See [#59](https://github.com/oozcitak/xmlbuilder-js/issues/59). + +## [2.4.0] - 2014-08-04 +- Correct cases of pubID and sysID. +- Use single lodash instead of separate npm modules. See [#53](https://github.com/oozcitak/xmlbuilder-js/issues/53). +- Escape according to Canonical XML 1.0. See [#54](https://github.com/oozcitak/xmlbuilder-js/issues/54). + +## [2.3.0] - 2014-07-17 +- Convert objects to JS primitives while sanitizing user input. +- Object builder preserves items with null values. See [#44](https://github.com/oozcitak/xmlbuilder-js/issues/44). +- Use modularized lodash functions to cut down dependencies. +- Process empty objects when converting from objects so that we don't throw on empty child objects. + +## [2.2.1] - 2014-04-04 +- Bumped version because previous release was not published on npm. + +## [2.2.0] - 2014-04-04 +- Switch to lodash from underscore. +- Removed legacy `ext` option from `create()`. +- Drop old node versions: 0.4, 0.5, 0.6. 0.8 is the minimum requirement from now on. + +## [2.1.0] - 2013-12-30 +- Removed duplicate null checks from constructors. +- Fixed node count in performance test. +- Added option for skipping null attribute values. See [#26](https://github.com/oozcitak/xmlbuilder-js/issues/26). +- Allow multiple values in `att()` and `ins()`. +- Added ability to run individual performance tests. +- Added flag for ignoring decorator strings. + +## [2.0.1] - 2013-12-24 +- Removed performance tests from npm package. + +## [2.0.0] - 2013-12-24 +- Combined loops for speed up. +- Added support for the DTD and XML declaration. +- `clone` includes attributes. +- Added performance tests. +- Evaluate attribute value if function. +- Evaluate instruction value if function. + +## [1.1.2] - 2013-12-11 +- Changed processing instruction decorator to `?`. + +## [1.1.1] - 2013-12-11 +- Added processing instructions to JS object conversion. + +## [1.1.0] - 2013-12-10 +- Added license to package. +- `create()` and `element()` accept JS object to fully build the document. +- Added `nod()` and `n()` aliases for `node()`. +- Renamed `convertAttChar` decorator to `convertAttKey`. +- Ignore empty decorator strings when converting JS objects. + +## [1.0.2] - 2013-11-27 +- Removed temp file which was accidentally included in the package. + +## [1.0.1] - 2013-11-27 +- Custom stringify functions affect current instance only. + +## [1.0.0] - 2013-11-27 +- Added processing instructions. +- Added stringify functions to sanitize and convert input values. +- Added option for headless XML documents. +- Added vows tests. +- Removed Makefile. Using npm publish scripts instead. +- Removed the `begin()` function. `create()` begins the document by creating the root node. + +## [0.4.3] - 2013-11-08 +- Added option to include surrogate pairs in XML content. See [#29](https://github.com/oozcitak/xmlbuilder-js/issues/29). +- Fixed empty value string representation in pretty mode. +- Added pre and postpublish scripts to package.json. +- Filtered out prototype properties when appending attributes. See [#31](https://github.com/oozcitak/xmlbuilder-js/issues/31). + +## [0.4.2] - 2012-09-14 +- Removed README.md from `.npmignore`. + +## [0.4.1] - 2012-08-31 +- Removed `begin()` calls in favor of `XMLBuilder` constructor. +- Added the `end()` function. `end()` is a convenience over `doc().toString()`. + +## [0.4.0] - 2012-08-31 +- Added arguments to `XMLBuilder` constructor to allow the name of the root element and XML prolog to be defined in one line. +- Soft deprecated `begin()`. + +## [0.3.11] - 2012-08-13 +- Package keywords are fixed to be an array of values. + +## [0.3.10] - 2012-08-13 +- Brought back npm package contents which were lost due to incorrect configuration of `package.json` in previous releases. + +## [0.3.3] - 2012-07-27 +- Implemented `importXMLBuilder()`. + +## [0.3.2] - 2012-07-20 +- Fixed a duplicated escaping problem on `element()`. +- Fixed a problem with text node creation from empty string. +- Calling `root()` on the document element returns the root element. +- `XMLBuilder` no longer extends `XMLFragment`. + +## [0.3.1] - 2011-11-28 +- Added guards for document element so that nodes cannot be inserted at document level. + +## [0.3.0] - 2011-11-28 +- Added `doc()` to return the document element. + +## [0.2.2] - 2011-11-28 +- Prevent code relying on `up()`'s older behavior to break. + +## [0.2.1] - 2011-11-28 +- Added the `root()` function. + +## [0.2.0] - 2011-11-21 +- Added Travis-CI integration. +- Added coffee-script dependency. +- Added insert, traversal and delete functions. + +## [0.1.7] - 2011-10-25 +- No changes. Accidental release. + +## [0.1.6] - 2011-10-25 +- Corrected `package.json` bugs link to `url` from `web`. + +## [0.1.5] - 2011-08-08 +- Added missing npm package contents. + +## [0.1.4] - 2011-07-29 +- Text-only nodes are no longer indented. +- Added documentation for multiple instances. + +## [0.1.3] - 2011-07-27 +- Exported the `create()` function to return a new instance. This allows multiple builder instances to be constructed. +- Fixed `u()` function so that it now correctly calls `up()`. +- Fixed typo in `element()` so that `attributes` and `text` can be passed interchangeably. + +## [0.1.2] - 2011-06-03 +- `ele()` accepts element text. +- `attributes()` now overrides existing attributes if passed the same attribute name. + +## [0.1.1] - 2011-05-19 +- Added the raw output option. +- Removed most validity checks. + +## [0.1.0] - 2011-04-27 +- `text()` and `cdata()` now return parent element. +- Attribute values are escaped. + +## [0.0.7] - 2011-04-23 +- Coerced text values to string. + +## [0.0.6] - 2011-02-23 +- Added support for XML comments. +- Text nodes are checked against CharData. + +## [0.0.5] - 2010-12-31 +- Corrected the name of the main npm module in `package.json`. + +## [0.0.4] - 2010-12-28 +- Added `.npmignore`. + +## [0.0.3] - 2010-12-27 +- root element is now constructed in `begin()`. +- moved prolog to `begin()`. +- Added the ability to have CDATA in element text. +- Removed unused prolog aliases. +- Removed `builder()` function from main module. +- Added the name of the main npm module in `package.json`. + +## [0.0.2] - 2010-11-03 +- `element()` expands nested arrays. +- Added pretty printing. +- Added the `up()`, `build()` and `prolog()` functions. +- Added readme. + +## 0.0.1 - 2010-11-02 +- Initial release + +[11.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v10.1.1...v11.0.0 +[10.1.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v10.1.0...v10.1.1 +[10.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v10.0.0...v10.1.0 +[10.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.7...v10.0.0 +[9.0.7]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.4...v9.0.7 +[9.0.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.3...v9.0.4 +[9.0.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.2...v9.0.3 +[9.0.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.1...v9.0.2 +[9.0.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v9.0.0...v9.0.1 +[9.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.2.2...v9.0.0 +[8.2.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.2.1...v8.2.2 +[8.2.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.2.0...v8.2.1 +[8.2.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.1.0...v8.2.0 +[8.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v8.0.0...v8.1.0 +[8.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v7.0.0...v8.0.0 +[7.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v6.0.0...v7.0.0 +[6.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v5.0.1...v6.0.0 +[5.0.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v5.0.0...v5.0.1 +[5.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v4.2.1...v5.0.0 +[4.2.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v4.2.0...v4.2.1 +[4.2.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v4.1.0...v4.2.0 +[4.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v4.0.0...v4.1.0 +[4.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v3.1.0...v4.0.0 +[3.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v3.0.0...v3.1.0 +[3.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.5...v3.0.0 +[2.6.5]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.4...v2.6.5 +[2.6.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.3...v2.6.4 +[2.6.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.2...v2.6.3 +[2.6.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.1...v2.6.2 +[2.6.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.6.0...v2.6.1 +[2.6.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.5.2...v2.6.0 +[2.5.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.5.1...v2.5.2 +[2.5.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.5.0...v2.5.1 +[2.5.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.6...v2.5.0 +[2.4.6]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.5...v2.4.6 +[2.4.5]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.4...v2.4.5 +[2.4.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.3...v2.4.4 +[2.4.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.2...v2.4.3 +[2.4.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.1...v2.4.2 +[2.4.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.4.0...v2.4.1 +[2.4.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.3.0...v2.4.0 +[2.3.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.2.1...v2.3.0 +[2.2.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.2.0...v2.2.1 +[2.2.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.1.0...v2.2.0 +[2.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.0.1...v2.1.0 +[2.0.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v2.0.0...v2.0.1 +[2.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.1.2...v2.0.0 +[1.1.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.1.1...v1.1.2 +[1.1.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.1.0...v1.1.1 +[1.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.0.2...v1.1.0 +[1.0.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.0.1...v1.0.2 +[1.0.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v1.0.0...v1.0.1 +[1.0.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.4.3...v1.0.0 +[0.4.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.4.2...v0.4.3 +[0.4.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.4.1...v0.4.2 +[0.4.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.4.0...v0.4.1 +[0.4.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.11...v0.4.0 +[0.3.11]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.10...v0.3.11 +[0.3.10]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.3...v0.3.10 +[0.3.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.2...v0.3.3 +[0.3.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.1...v0.3.2 +[0.3.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.3.0...v0.3.1 +[0.3.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.2.2...v0.3.0 +[0.2.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.2.1...v0.2.2 +[0.2.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.2.0...v0.2.1 +[0.2.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.7...v0.2.0 +[0.1.7]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.6...v0.1.7 +[0.1.6]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.5...v0.1.6 +[0.1.5]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.4...v0.1.5 +[0.1.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.3...v0.1.4 +[0.1.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.2...v0.1.3 +[0.1.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.1...v0.1.2 +[0.1.1]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.1.0...v0.1.1 +[0.1.0]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.7...v0.1.0 +[0.0.7]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.6...v0.0.7 +[0.0.6]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.5...v0.0.6 +[0.0.5]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.4...v0.0.5 +[0.0.4]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.3...v0.0.4 +[0.0.3]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.2...v0.0.3 +[0.0.2]: https://github.com/oozcitak/xmlbuilder-js/compare/v0.0.1...v0.0.2 + diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/LICENSE b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/LICENSE new file mode 100644 index 00000000..e7cbac9a --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Ozgur Ozcitak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/parse-bmfont-xml/node_modules/xmlbuilder/README.md b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/README.md new file mode 100644 index 00000000..efcb4b11 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/README.md @@ -0,0 +1,86 @@ +# xmlbuilder-js + +An XML builder for [node.js](https://nodejs.org/) similar to +[java-xmlbuilder](https://github.com/jmurty/java-xmlbuilder). + +[![License](http://img.shields.io/npm/l/xmlbuilder.svg?style=flat-square)](http://opensource.org/licenses/MIT) +[![NPM Version](http://img.shields.io/npm/v/xmlbuilder.svg?style=flat-square)](https://npmjs.com/package/xmlbuilder) +[![NPM Downloads](https://img.shields.io/npm/dm/xmlbuilder.svg?style=flat-square)](https://npmjs.com/package/xmlbuilder) + +[![Travis Build Status](http://img.shields.io/travis/oozcitak/xmlbuilder-js.svg?style=flat-square)](http://travis-ci.org/oozcitak/xmlbuilder-js) +[![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/bf7odb20hj77isry?svg=true)](https://ci.appveyor.com/project/oozcitak/xmlbuilder-js) +[![Dev Dependency Status](http://img.shields.io/david/dev/oozcitak/xmlbuilder-js.svg?style=flat-square)](https://david-dm.org/oozcitak/xmlbuilder-js) +[![Code Coverage](https://img.shields.io/coveralls/oozcitak/xmlbuilder-js.svg?style=flat-square)](https://coveralls.io/github/oozcitak/xmlbuilder-js) + +### Installation: + +``` sh +npm install xmlbuilder +``` + +### Usage: + +``` js +var builder = require('xmlbuilder'); +var xml = builder.create('root') + .ele('xmlbuilder') + .ele('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git') + .end({ pretty: true}); + +console.log(xml); +``` + +will result in: + +``` xml + + + + git://github.com/oozcitak/xmlbuilder-js.git + + +``` + +It is also possible to convert objects into nodes: + +``` js +builder.create({ + root: { + xmlbuilder: { + repo: { + '@type': 'git', // attributes start with @ + '#text': 'git://github.com/oozcitak/xmlbuilder-js.git' // text node + } + } + } +}); +``` + +If you need to do some processing: + +``` js +var root = builder.create('squares'); +root.com('f(x) = x^2'); +for(var i = 1; i <= 5; i++) +{ + var item = root.ele('data'); + item.att('x', i); + item.att('y', i * i); +} +``` + +This will result in: + +``` xml + + + + + + + + + +``` + +See the [wiki](https://github.com/oozcitak/xmlbuilder-js/wiki) for details and [examples](https://github.com/oozcitak/xmlbuilder-js/wiki/Examples) for more complex examples. diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/appveyor.yml b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/appveyor.yml new file mode 100644 index 00000000..39a26282 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/appveyor.yml @@ -0,0 +1,20 @@ +environment: + matrix: + - nodejs_version: "4" + - nodejs_version: "5" + - nodejs_version: "6" + - nodejs_version: "8" + - nodejs_version: "10" + - nodejs_version: "" # latest + +install: + - ps: "Install-Product node $env:nodejs_version" + - "npm install" + +test_script: + - "node --version" + - "npm --version" + - "npm test" + +build: off + diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/Derivation.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/Derivation.js new file mode 100644 index 00000000..2abfd08d --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/Derivation.js @@ -0,0 +1,10 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Restriction: 1, + Extension: 2, + Union: 4, + List: 8 + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/DocumentPosition.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/DocumentPosition.js new file mode 100644 index 00000000..1cbd21c1 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/DocumentPosition.js @@ -0,0 +1,12 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Disconnected: 1, + Preceding: 2, + Following: 4, + Contains: 8, + ContainedBy: 16, + ImplementationSpecific: 32 + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/NodeType.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/NodeType.js new file mode 100644 index 00000000..4c200e3c --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/NodeType.js @@ -0,0 +1,23 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Element: 1, + Attribute: 2, + Text: 3, + CData: 4, + EntityReference: 5, + EntityDeclaration: 6, + ProcessingInstruction: 7, + Comment: 8, + Document: 9, + DocType: 10, + DocumentFragment: 11, + NotationDeclaration: 12, + Declaration: 201, + Raw: 202, + AttributeDeclaration: 203, + ElementDeclaration: 204, + Dummy: 205 + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/OperationType.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/OperationType.js new file mode 100644 index 00000000..29428f61 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/OperationType.js @@ -0,0 +1,11 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Clones: 1, + Imported: 2, + Deleted: 3, + Renamed: 4, + Adopted: 5 + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/Utility.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/Utility.js new file mode 100644 index 00000000..1d42cfd3 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/Utility.js @@ -0,0 +1,83 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var assign, getValue, isArray, isEmpty, isFunction, isObject, isPlainObject, + slice = [].slice, + hasProp = {}.hasOwnProperty; + + assign = function() { + var i, key, len, source, sources, target; + target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : []; + if (isFunction(Object.assign)) { + Object.assign.apply(null, arguments); + } else { + for (i = 0, len = sources.length; i < len; i++) { + source = sources[i]; + if (source != null) { + for (key in source) { + if (!hasProp.call(source, key)) continue; + target[key] = source[key]; + } + } + } + } + return target; + }; + + isFunction = function(val) { + return !!val && Object.prototype.toString.call(val) === '[object Function]'; + }; + + isObject = function(val) { + var ref; + return !!val && ((ref = typeof val) === 'function' || ref === 'object'); + }; + + isArray = function(val) { + if (isFunction(Array.isArray)) { + return Array.isArray(val); + } else { + return Object.prototype.toString.call(val) === '[object Array]'; + } + }; + + isEmpty = function(val) { + var key; + if (isArray(val)) { + return !val.length; + } else { + for (key in val) { + if (!hasProp.call(val, key)) continue; + return false; + } + return true; + } + }; + + isPlainObject = function(val) { + var ctor, proto; + return isObject(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && (typeof ctor === 'function') && (ctor instanceof ctor) && (Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object)); + }; + + getValue = function(obj) { + if (isFunction(obj.valueOf)) { + return obj.valueOf(); + } else { + return obj; + } + }; + + module.exports.assign = assign; + + module.exports.isFunction = isFunction; + + module.exports.isObject = isObject; + + module.exports.isArray = isArray; + + module.exports.isEmpty = isEmpty; + + module.exports.isPlainObject = isPlainObject; + + module.exports.getValue = getValue; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/WriterState.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/WriterState.js new file mode 100644 index 00000000..0923eec9 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/WriterState.js @@ -0,0 +1,10 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + None: 0, + OpenTag: 1, + InsideTag: 2, + CloseTag: 3 + }; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLAttribute.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLAttribute.js new file mode 100644 index 00000000..c208566d --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLAttribute.js @@ -0,0 +1,108 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLAttribute, XMLNode; + + NodeType = require('./NodeType'); + + XMLNode = require('./XMLNode'); + + module.exports = XMLAttribute = (function() { + function XMLAttribute(parent, name, value) { + this.parent = parent; + if (this.parent) { + this.options = this.parent.options; + this.stringify = this.parent.stringify; + } + if (name == null) { + throw new Error("Missing attribute name. " + this.debugInfo(name)); + } + this.name = this.stringify.name(name); + this.value = this.stringify.attValue(value); + this.type = NodeType.Attribute; + this.isId = false; + this.schemaTypeInfo = null; + } + + Object.defineProperty(XMLAttribute.prototype, 'nodeType', { + get: function() { + return this.type; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'ownerElement', { + get: function() { + return this.parent; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'textContent', { + get: function() { + return this.value; + }, + set: function(value) { + return this.value = value || ''; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'namespaceURI', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'prefix', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'localName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLAttribute.prototype, 'specified', { + get: function() { + return true; + } + }); + + XMLAttribute.prototype.clone = function() { + return Object.create(this); + }; + + XMLAttribute.prototype.toString = function(options) { + return this.options.writer.attribute(this, this.options.writer.filterOptions(options)); + }; + + XMLAttribute.prototype.debugInfo = function(name) { + name = name || this.name; + if (name == null) { + return "parent: <" + this.parent.name + ">"; + } else { + return "attribute: {" + name + "}, parent: <" + this.parent.name + ">"; + } + }; + + XMLAttribute.prototype.isEqualNode = function(node) { + if (node.namespaceURI !== this.namespaceURI) { + return false; + } + if (node.prefix !== this.prefix) { + return false; + } + if (node.localName !== this.localName) { + return false; + } + if (node.value !== this.value) { + return false; + } + return true; + }; + + return XMLAttribute; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLCData.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLCData.js new file mode 100644 index 00000000..c732ec5b --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLCData.js @@ -0,0 +1,36 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLCData, XMLCharacterData, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLCharacterData = require('./XMLCharacterData'); + + module.exports = XMLCData = (function(superClass) { + extend(XMLCData, superClass); + + function XMLCData(parent, text) { + XMLCData.__super__.constructor.call(this, parent); + if (text == null) { + throw new Error("Missing CDATA text. " + this.debugInfo()); + } + this.name = "#cdata-section"; + this.type = NodeType.CData; + this.value = this.stringify.cdata(text); + } + + XMLCData.prototype.clone = function() { + return Object.create(this); + }; + + XMLCData.prototype.toString = function(options) { + return this.options.writer.cdata(this, this.options.writer.filterOptions(options)); + }; + + return XMLCData; + + })(XMLCharacterData); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLCharacterData.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLCharacterData.js new file mode 100644 index 00000000..c007a181 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLCharacterData.js @@ -0,0 +1,79 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLCharacterData, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + module.exports = XMLCharacterData = (function(superClass) { + extend(XMLCharacterData, superClass); + + function XMLCharacterData(parent) { + XMLCharacterData.__super__.constructor.call(this, parent); + this.value = ''; + } + + Object.defineProperty(XMLCharacterData.prototype, 'data', { + get: function() { + return this.value; + }, + set: function(value) { + return this.value = value || ''; + } + }); + + Object.defineProperty(XMLCharacterData.prototype, 'length', { + get: function() { + return this.value.length; + } + }); + + Object.defineProperty(XMLCharacterData.prototype, 'textContent', { + get: function() { + return this.value; + }, + set: function(value) { + return this.value = value || ''; + } + }); + + XMLCharacterData.prototype.clone = function() { + return Object.create(this); + }; + + XMLCharacterData.prototype.substringData = function(offset, count) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.appendData = function(arg) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.insertData = function(offset, arg) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.deleteData = function(offset, count) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.replaceData = function(offset, count, arg) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLCharacterData.prototype.isEqualNode = function(node) { + if (!XMLCharacterData.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.data !== this.data) { + return false; + } + return true; + }; + + return XMLCharacterData; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLComment.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLComment.js new file mode 100644 index 00000000..82872168 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLComment.js @@ -0,0 +1,36 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLCharacterData, XMLComment, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLCharacterData = require('./XMLCharacterData'); + + module.exports = XMLComment = (function(superClass) { + extend(XMLComment, superClass); + + function XMLComment(parent, text) { + XMLComment.__super__.constructor.call(this, parent); + if (text == null) { + throw new Error("Missing comment text. " + this.debugInfo()); + } + this.name = "#comment"; + this.type = NodeType.Comment; + this.value = this.stringify.comment(text); + } + + XMLComment.prototype.clone = function() { + return Object.create(this); + }; + + XMLComment.prototype.toString = function(options) { + return this.options.writer.comment(this, this.options.writer.filterOptions(options)); + }; + + return XMLComment; + + })(XMLCharacterData); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js new file mode 100644 index 00000000..b331b86f --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js @@ -0,0 +1,64 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLDOMConfiguration, XMLDOMErrorHandler, XMLDOMStringList; + + XMLDOMErrorHandler = require('./XMLDOMErrorHandler'); + + XMLDOMStringList = require('./XMLDOMStringList'); + + module.exports = XMLDOMConfiguration = (function() { + function XMLDOMConfiguration() { + var clonedSelf; + this.defaultParams = { + "canonical-form": false, + "cdata-sections": false, + "comments": false, + "datatype-normalization": false, + "element-content-whitespace": true, + "entities": true, + "error-handler": new XMLDOMErrorHandler(), + "infoset": true, + "validate-if-schema": false, + "namespaces": true, + "namespace-declarations": true, + "normalize-characters": false, + "schema-location": '', + "schema-type": '', + "split-cdata-sections": true, + "validate": false, + "well-formed": true + }; + this.params = clonedSelf = Object.create(this.defaultParams); + } + + Object.defineProperty(XMLDOMConfiguration.prototype, 'parameterNames', { + get: function() { + return new XMLDOMStringList(Object.keys(this.defaultParams)); + } + }); + + XMLDOMConfiguration.prototype.getParameter = function(name) { + if (this.params.hasOwnProperty(name)) { + return this.params[name]; + } else { + return null; + } + }; + + XMLDOMConfiguration.prototype.canSetParameter = function(name, value) { + return true; + }; + + XMLDOMConfiguration.prototype.setParameter = function(name, value) { + if (value != null) { + return this.params[name] = value; + } else { + return delete this.params[name]; + } + }; + + return XMLDOMConfiguration; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js new file mode 100644 index 00000000..4a0446c0 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js @@ -0,0 +1,16 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLDOMErrorHandler; + + module.exports = XMLDOMErrorHandler = (function() { + function XMLDOMErrorHandler() {} + + XMLDOMErrorHandler.prototype.handleError = function(error) { + throw new Error(error); + }; + + return XMLDOMErrorHandler; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMImplementation.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMImplementation.js new file mode 100644 index 00000000..4f9f9db1 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMImplementation.js @@ -0,0 +1,32 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLDOMImplementation; + + module.exports = XMLDOMImplementation = (function() { + function XMLDOMImplementation() {} + + XMLDOMImplementation.prototype.hasFeature = function(feature, version) { + return true; + }; + + XMLDOMImplementation.prototype.createDocumentType = function(qualifiedName, publicId, systemId) { + throw new Error("This DOM method is not implemented."); + }; + + XMLDOMImplementation.prototype.createDocument = function(namespaceURI, qualifiedName, doctype) { + throw new Error("This DOM method is not implemented."); + }; + + XMLDOMImplementation.prototype.createHTMLDocument = function(title) { + throw new Error("This DOM method is not implemented."); + }; + + XMLDOMImplementation.prototype.getFeature = function(feature, version) { + throw new Error("This DOM method is not implemented."); + }; + + return XMLDOMImplementation; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMStringList.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMStringList.js new file mode 100644 index 00000000..ba558c5b --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDOMStringList.js @@ -0,0 +1,28 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLDOMStringList; + + module.exports = XMLDOMStringList = (function() { + function XMLDOMStringList(arr) { + this.arr = arr || []; + } + + Object.defineProperty(XMLDOMStringList.prototype, 'length', { + get: function() { + return this.arr.length; + } + }); + + XMLDOMStringList.prototype.item = function(index) { + return this.arr[index] || null; + }; + + XMLDOMStringList.prototype.contains = function(str) { + return this.arr.indexOf(str) !== -1; + }; + + return XMLDOMStringList; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDAttList.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDAttList.js new file mode 100644 index 00000000..aca9dbd4 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDAttList.js @@ -0,0 +1,55 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDAttList, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDTDAttList = (function(superClass) { + extend(XMLDTDAttList, superClass); + + function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) { + XMLDTDAttList.__super__.constructor.call(this, parent); + if (elementName == null) { + throw new Error("Missing DTD element name. " + this.debugInfo()); + } + if (attributeName == null) { + throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName)); + } + if (!attributeType) { + throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName)); + } + if (!defaultValueType) { + throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName)); + } + if (defaultValueType.indexOf('#') !== 0) { + defaultValueType = '#' + defaultValueType; + } + if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) { + throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName)); + } + if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) { + throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName)); + } + this.elementName = this.stringify.name(elementName); + this.type = NodeType.AttributeDeclaration; + this.attributeName = this.stringify.name(attributeName); + this.attributeType = this.stringify.dtdAttType(attributeType); + if (defaultValue) { + this.defaultValue = this.stringify.dtdAttDefault(defaultValue); + } + this.defaultValueType = defaultValueType; + } + + XMLDTDAttList.prototype.toString = function(options) { + return this.options.writer.dtdAttList(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDAttList; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDElement.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDElement.js new file mode 100644 index 00000000..f8f1ae76 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDElement.js @@ -0,0 +1,38 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDElement, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDTDElement = (function(superClass) { + extend(XMLDTDElement, superClass); + + function XMLDTDElement(parent, name, value) { + XMLDTDElement.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing DTD element name. " + this.debugInfo()); + } + if (!value) { + value = '(#PCDATA)'; + } + if (Array.isArray(value)) { + value = '(' + value.join(',') + ')'; + } + this.name = this.stringify.name(name); + this.type = NodeType.ElementDeclaration; + this.value = this.stringify.dtdElementValue(value); + } + + XMLDTDElement.prototype.toString = function(options) { + return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDElement; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDEntity.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDEntity.js new file mode 100644 index 00000000..0a940d6e --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDEntity.js @@ -0,0 +1,97 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDEntity, XMLNode, isObject, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + isObject = require('./Utility').isObject; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDTDEntity = (function(superClass) { + extend(XMLDTDEntity, superClass); + + function XMLDTDEntity(parent, pe, name, value) { + XMLDTDEntity.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing DTD entity name. " + this.debugInfo(name)); + } + if (value == null) { + throw new Error("Missing DTD entity value. " + this.debugInfo(name)); + } + this.pe = !!pe; + this.name = this.stringify.name(name); + this.type = NodeType.EntityDeclaration; + if (!isObject(value)) { + this.value = this.stringify.dtdEntityValue(value); + this.internal = true; + } else { + if (!value.pubID && !value.sysID) { + throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name)); + } + if (value.pubID && !value.sysID) { + throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name)); + } + this.internal = false; + if (value.pubID != null) { + this.pubID = this.stringify.dtdPubID(value.pubID); + } + if (value.sysID != null) { + this.sysID = this.stringify.dtdSysID(value.sysID); + } + if (value.nData != null) { + this.nData = this.stringify.dtdNData(value.nData); + } + if (this.pe && this.nData) { + throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name)); + } + } + } + + Object.defineProperty(XMLDTDEntity.prototype, 'publicId', { + get: function() { + return this.pubID; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'systemId', { + get: function() { + return this.sysID; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'notationName', { + get: function() { + return this.nData || null; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'inputEncoding', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'xmlEncoding', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDTDEntity.prototype, 'xmlVersion', { + get: function() { + return null; + } + }); + + XMLDTDEntity.prototype.toString = function(options) { + return this.options.writer.dtdEntity(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDEntity; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDNotation.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDNotation.js new file mode 100644 index 00000000..57a119d2 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDTDNotation.js @@ -0,0 +1,52 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDNotation, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDTDNotation = (function(superClass) { + extend(XMLDTDNotation, superClass); + + function XMLDTDNotation(parent, name, value) { + XMLDTDNotation.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing DTD notation name. " + this.debugInfo(name)); + } + if (!value.pubID && !value.sysID) { + throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name)); + } + this.name = this.stringify.name(name); + this.type = NodeType.NotationDeclaration; + if (value.pubID != null) { + this.pubID = this.stringify.dtdPubID(value.pubID); + } + if (value.sysID != null) { + this.sysID = this.stringify.dtdSysID(value.sysID); + } + } + + Object.defineProperty(XMLDTDNotation.prototype, 'publicId', { + get: function() { + return this.pubID; + } + }); + + Object.defineProperty(XMLDTDNotation.prototype, 'systemId', { + get: function() { + return this.sysID; + } + }); + + XMLDTDNotation.prototype.toString = function(options) { + return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDNotation; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDeclaration.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDeclaration.js new file mode 100644 index 00000000..d4f7f447 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDeclaration.js @@ -0,0 +1,43 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDeclaration, XMLNode, isObject, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + isObject = require('./Utility').isObject; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDeclaration = (function(superClass) { + extend(XMLDeclaration, superClass); + + function XMLDeclaration(parent, version, encoding, standalone) { + var ref; + XMLDeclaration.__super__.constructor.call(this, parent); + if (isObject(version)) { + ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone; + } + if (!version) { + version = '1.0'; + } + this.type = NodeType.Declaration; + this.version = this.stringify.xmlVersion(version); + if (encoding != null) { + this.encoding = this.stringify.xmlEncoding(encoding); + } + if (standalone != null) { + this.standalone = this.stringify.xmlStandalone(standalone); + } + } + + XMLDeclaration.prototype.toString = function(options) { + return this.options.writer.declaration(this, this.options.writer.filterOptions(options)); + }; + + return XMLDeclaration; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocType.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocType.js new file mode 100644 index 00000000..ef043f4c --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocType.js @@ -0,0 +1,186 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNamedNodeMap, XMLNode, isObject, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + isObject = require('./Utility').isObject; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + XMLDTDAttList = require('./XMLDTDAttList'); + + XMLDTDEntity = require('./XMLDTDEntity'); + + XMLDTDElement = require('./XMLDTDElement'); + + XMLDTDNotation = require('./XMLDTDNotation'); + + XMLNamedNodeMap = require('./XMLNamedNodeMap'); + + module.exports = XMLDocType = (function(superClass) { + extend(XMLDocType, superClass); + + function XMLDocType(parent, pubID, sysID) { + var child, i, len, ref, ref1, ref2; + XMLDocType.__super__.constructor.call(this, parent); + this.type = NodeType.DocType; + if (parent.children) { + ref = parent.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + if (child.type === NodeType.Element) { + this.name = child.name; + break; + } + } + } + this.documentObject = parent; + if (isObject(pubID)) { + ref1 = pubID, pubID = ref1.pubID, sysID = ref1.sysID; + } + if (sysID == null) { + ref2 = [pubID, sysID], sysID = ref2[0], pubID = ref2[1]; + } + if (pubID != null) { + this.pubID = this.stringify.dtdPubID(pubID); + } + if (sysID != null) { + this.sysID = this.stringify.dtdSysID(sysID); + } + } + + Object.defineProperty(XMLDocType.prototype, 'entities', { + get: function() { + var child, i, len, nodes, ref; + nodes = {}; + ref = this.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + if ((child.type === NodeType.EntityDeclaration) && !child.pe) { + nodes[child.name] = child; + } + } + return new XMLNamedNodeMap(nodes); + } + }); + + Object.defineProperty(XMLDocType.prototype, 'notations', { + get: function() { + var child, i, len, nodes, ref; + nodes = {}; + ref = this.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + if (child.type === NodeType.NotationDeclaration) { + nodes[child.name] = child; + } + } + return new XMLNamedNodeMap(nodes); + } + }); + + Object.defineProperty(XMLDocType.prototype, 'publicId', { + get: function() { + return this.pubID; + } + }); + + Object.defineProperty(XMLDocType.prototype, 'systemId', { + get: function() { + return this.sysID; + } + }); + + Object.defineProperty(XMLDocType.prototype, 'internalSubset', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + XMLDocType.prototype.element = function(name, value) { + var child; + child = new XMLDTDElement(this, name, value); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { + var child; + child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.entity = function(name, value) { + var child; + child = new XMLDTDEntity(this, false, name, value); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.pEntity = function(name, value) { + var child; + child = new XMLDTDEntity(this, true, name, value); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.notation = function(name, value) { + var child; + child = new XMLDTDNotation(this, name, value); + this.children.push(child); + return this; + }; + + XMLDocType.prototype.toString = function(options) { + return this.options.writer.docType(this, this.options.writer.filterOptions(options)); + }; + + XMLDocType.prototype.ele = function(name, value) { + return this.element(name, value); + }; + + XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { + return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue); + }; + + XMLDocType.prototype.ent = function(name, value) { + return this.entity(name, value); + }; + + XMLDocType.prototype.pent = function(name, value) { + return this.pEntity(name, value); + }; + + XMLDocType.prototype.not = function(name, value) { + return this.notation(name, value); + }; + + XMLDocType.prototype.up = function() { + return this.root() || this.documentObject; + }; + + XMLDocType.prototype.isEqualNode = function(node) { + if (!XMLDocType.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.name !== this.name) { + return false; + } + if (node.publicId !== this.publicId) { + return false; + } + if (node.systemId !== this.systemId) { + return false; + } + return true; + }; + + return XMLDocType; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocument.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocument.js new file mode 100644 index 00000000..88df56c4 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocument.js @@ -0,0 +1,242 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDOMConfiguration, XMLDOMImplementation, XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + isPlainObject = require('./Utility').isPlainObject; + + XMLDOMImplementation = require('./XMLDOMImplementation'); + + XMLDOMConfiguration = require('./XMLDOMConfiguration'); + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + XMLStringifier = require('./XMLStringifier'); + + XMLStringWriter = require('./XMLStringWriter'); + + module.exports = XMLDocument = (function(superClass) { + extend(XMLDocument, superClass); + + function XMLDocument(options) { + XMLDocument.__super__.constructor.call(this, null); + this.name = "#document"; + this.type = NodeType.Document; + this.documentURI = null; + this.domConfig = new XMLDOMConfiguration(); + options || (options = {}); + if (!options.writer) { + options.writer = new XMLStringWriter(); + } + this.options = options; + this.stringify = new XMLStringifier(options); + } + + Object.defineProperty(XMLDocument.prototype, 'implementation', { + value: new XMLDOMImplementation() + }); + + Object.defineProperty(XMLDocument.prototype, 'doctype', { + get: function() { + var child, i, len, ref; + ref = this.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + if (child.type === NodeType.DocType) { + return child; + } + } + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'documentElement', { + get: function() { + return this.rootObject || null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'inputEncoding', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'strictErrorChecking', { + get: function() { + return false; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'xmlEncoding', { + get: function() { + if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { + return this.children[0].encoding; + } else { + return null; + } + } + }); + + Object.defineProperty(XMLDocument.prototype, 'xmlStandalone', { + get: function() { + if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { + return this.children[0].standalone === 'yes'; + } else { + return false; + } + } + }); + + Object.defineProperty(XMLDocument.prototype, 'xmlVersion', { + get: function() { + if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) { + return this.children[0].version; + } else { + return "1.0"; + } + } + }); + + Object.defineProperty(XMLDocument.prototype, 'URL', { + get: function() { + return this.documentURI; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'origin', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'compatMode', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'characterSet', { + get: function() { + return null; + } + }); + + Object.defineProperty(XMLDocument.prototype, 'contentType', { + get: function() { + return null; + } + }); + + XMLDocument.prototype.end = function(writer) { + var writerOptions; + writerOptions = {}; + if (!writer) { + writer = this.options.writer; + } else if (isPlainObject(writer)) { + writerOptions = writer; + writer = this.options.writer; + } + return writer.document(this, writer.filterOptions(writerOptions)); + }; + + XMLDocument.prototype.toString = function(options) { + return this.options.writer.document(this, this.options.writer.filterOptions(options)); + }; + + XMLDocument.prototype.createElement = function(tagName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createDocumentFragment = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createTextNode = function(data) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createComment = function(data) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createCDATASection = function(data) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createProcessingInstruction = function(target, data) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createAttribute = function(name) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createEntityReference = function(name) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.getElementsByTagName = function(tagname) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.importNode = function(importedNode, deep) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createElementNS = function(namespaceURI, qualifiedName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createAttributeNS = function(namespaceURI, qualifiedName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.getElementById = function(elementId) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.adoptNode = function(source) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.normalizeDocument = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.renameNode = function(node, namespaceURI, qualifiedName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.getElementsByClassName = function(classNames) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createEvent = function(eventInterface) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createRange = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createNodeIterator = function(root, whatToShow, filter) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLDocument.prototype.createTreeWalker = function(root, whatToShow, filter) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + return XMLDocument; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocumentCB.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocumentCB.js new file mode 100644 index 00000000..ca1aa1cf --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocumentCB.js @@ -0,0 +1,528 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocument, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction, isObject, isPlainObject, ref, + hasProp = {}.hasOwnProperty; + + ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue; + + NodeType = require('./NodeType'); + + XMLDocument = require('./XMLDocument'); + + XMLElement = require('./XMLElement'); + + XMLCData = require('./XMLCData'); + + XMLComment = require('./XMLComment'); + + XMLRaw = require('./XMLRaw'); + + XMLText = require('./XMLText'); + + XMLProcessingInstruction = require('./XMLProcessingInstruction'); + + XMLDeclaration = require('./XMLDeclaration'); + + XMLDocType = require('./XMLDocType'); + + XMLDTDAttList = require('./XMLDTDAttList'); + + XMLDTDEntity = require('./XMLDTDEntity'); + + XMLDTDElement = require('./XMLDTDElement'); + + XMLDTDNotation = require('./XMLDTDNotation'); + + XMLAttribute = require('./XMLAttribute'); + + XMLStringifier = require('./XMLStringifier'); + + XMLStringWriter = require('./XMLStringWriter'); + + WriterState = require('./WriterState'); + + module.exports = XMLDocumentCB = (function() { + function XMLDocumentCB(options, onData, onEnd) { + var writerOptions; + this.name = "?xml"; + this.type = NodeType.Document; + options || (options = {}); + writerOptions = {}; + if (!options.writer) { + options.writer = new XMLStringWriter(); + } else if (isPlainObject(options.writer)) { + writerOptions = options.writer; + options.writer = new XMLStringWriter(); + } + this.options = options; + this.writer = options.writer; + this.writerOptions = this.writer.filterOptions(writerOptions); + this.stringify = new XMLStringifier(options); + this.onDataCallback = onData || function() {}; + this.onEndCallback = onEnd || function() {}; + this.currentNode = null; + this.currentLevel = -1; + this.openTags = {}; + this.documentStarted = false; + this.documentCompleted = false; + this.root = null; + } + + XMLDocumentCB.prototype.createChildNode = function(node) { + var att, attName, attributes, child, i, len, ref1, ref2; + switch (node.type) { + case NodeType.CData: + this.cdata(node.value); + break; + case NodeType.Comment: + this.comment(node.value); + break; + case NodeType.Element: + attributes = {}; + ref1 = node.attribs; + for (attName in ref1) { + if (!hasProp.call(ref1, attName)) continue; + att = ref1[attName]; + attributes[attName] = att.value; + } + this.node(node.name, attributes); + break; + case NodeType.Dummy: + this.dummy(); + break; + case NodeType.Raw: + this.raw(node.value); + break; + case NodeType.Text: + this.text(node.value); + break; + case NodeType.ProcessingInstruction: + this.instruction(node.target, node.value); + break; + default: + throw new Error("This XML node type is not supported in a JS object: " + node.constructor.name); + } + ref2 = node.children; + for (i = 0, len = ref2.length; i < len; i++) { + child = ref2[i]; + this.createChildNode(child); + if (child.type === NodeType.Element) { + this.up(); + } + } + return this; + }; + + XMLDocumentCB.prototype.dummy = function() { + return this; + }; + + XMLDocumentCB.prototype.node = function(name, attributes, text) { + var ref1; + if (name == null) { + throw new Error("Missing node name."); + } + if (this.root && this.currentLevel === -1) { + throw new Error("Document can only have one root node. " + this.debugInfo(name)); + } + this.openCurrent(); + name = getValue(name); + if (attributes == null) { + attributes = {}; + } + attributes = getValue(attributes); + if (!isObject(attributes)) { + ref1 = [attributes, text], text = ref1[0], attributes = ref1[1]; + } + this.currentNode = new XMLElement(this, name, attributes); + this.currentNode.children = false; + this.currentLevel++; + this.openTags[this.currentLevel] = this.currentNode; + if (text != null) { + this.text(text); + } + return this; + }; + + XMLDocumentCB.prototype.element = function(name, attributes, text) { + var child, i, len, oldValidationFlag, ref1, root; + if (this.currentNode && this.currentNode.type === NodeType.DocType) { + this.dtdElement.apply(this, arguments); + } else { + if (Array.isArray(name) || isObject(name) || isFunction(name)) { + oldValidationFlag = this.options.noValidation; + this.options.noValidation = true; + root = new XMLDocument(this.options).element('TEMP_ROOT'); + root.element(name); + this.options.noValidation = oldValidationFlag; + ref1 = root.children; + for (i = 0, len = ref1.length; i < len; i++) { + child = ref1[i]; + this.createChildNode(child); + if (child.type === NodeType.Element) { + this.up(); + } + } + } else { + this.node(name, attributes, text); + } + } + return this; + }; + + XMLDocumentCB.prototype.attribute = function(name, value) { + var attName, attValue; + if (!this.currentNode || this.currentNode.children) { + throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name)); + } + if (name != null) { + name = getValue(name); + } + if (isObject(name)) { + for (attName in name) { + if (!hasProp.call(name, attName)) continue; + attValue = name[attName]; + this.attribute(attName, attValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + if (this.options.keepNullAttributes && (value == null)) { + this.currentNode.attribs[name] = new XMLAttribute(this, name, ""); + } else if (value != null) { + this.currentNode.attribs[name] = new XMLAttribute(this, name, value); + } + } + return this; + }; + + XMLDocumentCB.prototype.text = function(value) { + var node; + this.openCurrent(); + node = new XMLText(this, value); + this.onData(this.writer.text(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.cdata = function(value) { + var node; + this.openCurrent(); + node = new XMLCData(this, value); + this.onData(this.writer.cdata(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.comment = function(value) { + var node; + this.openCurrent(); + node = new XMLComment(this, value); + this.onData(this.writer.comment(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.raw = function(value) { + var node; + this.openCurrent(); + node = new XMLRaw(this, value); + this.onData(this.writer.raw(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.instruction = function(target, value) { + var i, insTarget, insValue, len, node; + this.openCurrent(); + if (target != null) { + target = getValue(target); + } + if (value != null) { + value = getValue(value); + } + if (Array.isArray(target)) { + for (i = 0, len = target.length; i < len; i++) { + insTarget = target[i]; + this.instruction(insTarget); + } + } else if (isObject(target)) { + for (insTarget in target) { + if (!hasProp.call(target, insTarget)) continue; + insValue = target[insTarget]; + this.instruction(insTarget, insValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + node = new XMLProcessingInstruction(this, target, value); + this.onData(this.writer.processingInstruction(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + } + return this; + }; + + XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) { + var node; + this.openCurrent(); + if (this.documentStarted) { + throw new Error("declaration() must be the first node."); + } + node = new XMLDeclaration(this, version, encoding, standalone); + this.onData(this.writer.declaration(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) { + this.openCurrent(); + if (root == null) { + throw new Error("Missing root node name."); + } + if (this.root) { + throw new Error("dtd() must come before the root node."); + } + this.currentNode = new XMLDocType(this, pubID, sysID); + this.currentNode.rootNodeName = root; + this.currentNode.children = false; + this.currentLevel++; + this.openTags[this.currentLevel] = this.currentNode; + return this; + }; + + XMLDocumentCB.prototype.dtdElement = function(name, value) { + var node; + this.openCurrent(); + node = new XMLDTDElement(this, name, value); + this.onData(this.writer.dtdElement(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { + var node; + this.openCurrent(); + node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); + this.onData(this.writer.dtdAttList(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.entity = function(name, value) { + var node; + this.openCurrent(); + node = new XMLDTDEntity(this, false, name, value); + this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.pEntity = function(name, value) { + var node; + this.openCurrent(); + node = new XMLDTDEntity(this, true, name, value); + this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.notation = function(name, value) { + var node; + this.openCurrent(); + node = new XMLDTDNotation(this, name, value); + this.onData(this.writer.dtdNotation(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1); + return this; + }; + + XMLDocumentCB.prototype.up = function() { + if (this.currentLevel < 0) { + throw new Error("The document node has no parent."); + } + if (this.currentNode) { + if (this.currentNode.children) { + this.closeNode(this.currentNode); + } else { + this.openNode(this.currentNode); + } + this.currentNode = null; + } else { + this.closeNode(this.openTags[this.currentLevel]); + } + delete this.openTags[this.currentLevel]; + this.currentLevel--; + return this; + }; + + XMLDocumentCB.prototype.end = function() { + while (this.currentLevel >= 0) { + this.up(); + } + return this.onEnd(); + }; + + XMLDocumentCB.prototype.openCurrent = function() { + if (this.currentNode) { + this.currentNode.children = true; + return this.openNode(this.currentNode); + } + }; + + XMLDocumentCB.prototype.openNode = function(node) { + var att, chunk, name, ref1; + if (!node.isOpen) { + if (!this.root && this.currentLevel === 0 && node.type === NodeType.Element) { + this.root = node; + } + chunk = ''; + if (node.type === NodeType.Element) { + this.writerOptions.state = WriterState.OpenTag; + chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '<' + node.name; + ref1 = node.attribs; + for (name in ref1) { + if (!hasProp.call(ref1, name)) continue; + att = ref1[name]; + chunk += this.writer.attribute(att, this.writerOptions, this.currentLevel); + } + chunk += (node.children ? '>' : '/>') + this.writer.endline(node, this.writerOptions, this.currentLevel); + this.writerOptions.state = WriterState.InsideTag; + } else { + this.writerOptions.state = WriterState.OpenTag; + chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ''; + } + chunk += this.writer.endline(node, this.writerOptions, this.currentLevel); + } + this.onData(chunk, this.currentLevel); + return node.isOpen = true; + } + }; + + XMLDocumentCB.prototype.closeNode = function(node) { + var chunk; + if (!node.isClosed) { + chunk = ''; + this.writerOptions.state = WriterState.CloseTag; + if (node.type === NodeType.Element) { + chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '' + this.writer.endline(node, this.writerOptions, this.currentLevel); + } else { + chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ']>' + this.writer.endline(node, this.writerOptions, this.currentLevel); + } + this.writerOptions.state = WriterState.None; + this.onData(chunk, this.currentLevel); + return node.isClosed = true; + } + }; + + XMLDocumentCB.prototype.onData = function(chunk, level) { + this.documentStarted = true; + return this.onDataCallback(chunk, level + 1); + }; + + XMLDocumentCB.prototype.onEnd = function() { + this.documentCompleted = true; + return this.onEndCallback(); + }; + + XMLDocumentCB.prototype.debugInfo = function(name) { + if (name == null) { + return ""; + } else { + return "node: <" + name + ">"; + } + }; + + XMLDocumentCB.prototype.ele = function() { + return this.element.apply(this, arguments); + }; + + XMLDocumentCB.prototype.nod = function(name, attributes, text) { + return this.node(name, attributes, text); + }; + + XMLDocumentCB.prototype.txt = function(value) { + return this.text(value); + }; + + XMLDocumentCB.prototype.dat = function(value) { + return this.cdata(value); + }; + + XMLDocumentCB.prototype.com = function(value) { + return this.comment(value); + }; + + XMLDocumentCB.prototype.ins = function(target, value) { + return this.instruction(target, value); + }; + + XMLDocumentCB.prototype.dec = function(version, encoding, standalone) { + return this.declaration(version, encoding, standalone); + }; + + XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) { + return this.doctype(root, pubID, sysID); + }; + + XMLDocumentCB.prototype.e = function(name, attributes, text) { + return this.element(name, attributes, text); + }; + + XMLDocumentCB.prototype.n = function(name, attributes, text) { + return this.node(name, attributes, text); + }; + + XMLDocumentCB.prototype.t = function(value) { + return this.text(value); + }; + + XMLDocumentCB.prototype.d = function(value) { + return this.cdata(value); + }; + + XMLDocumentCB.prototype.c = function(value) { + return this.comment(value); + }; + + XMLDocumentCB.prototype.r = function(value) { + return this.raw(value); + }; + + XMLDocumentCB.prototype.i = function(target, value) { + return this.instruction(target, value); + }; + + XMLDocumentCB.prototype.att = function() { + if (this.currentNode && this.currentNode.type === NodeType.DocType) { + return this.attList.apply(this, arguments); + } else { + return this.attribute.apply(this, arguments); + } + }; + + XMLDocumentCB.prototype.a = function() { + if (this.currentNode && this.currentNode.type === NodeType.DocType) { + return this.attList.apply(this, arguments); + } else { + return this.attribute.apply(this, arguments); + } + }; + + XMLDocumentCB.prototype.ent = function(name, value) { + return this.entity(name, value); + }; + + XMLDocumentCB.prototype.pent = function(name, value) { + return this.pEntity(name, value); + }; + + XMLDocumentCB.prototype.not = function(name, value) { + return this.notation(name, value); + }; + + return XMLDocumentCB; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocumentFragment.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocumentFragment.js new file mode 100644 index 00000000..5d6039c4 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDocumentFragment.js @@ -0,0 +1,24 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDocumentFragment, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDocumentFragment = (function(superClass) { + extend(XMLDocumentFragment, superClass); + + function XMLDocumentFragment() { + XMLDocumentFragment.__super__.constructor.call(this, null); + this.name = "#document-fragment"; + this.type = NodeType.DocumentFragment; + } + + return XMLDocumentFragment; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDummy.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDummy.js new file mode 100644 index 00000000..b26083a3 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLDummy.js @@ -0,0 +1,31 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDummy, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + module.exports = XMLDummy = (function(superClass) { + extend(XMLDummy, superClass); + + function XMLDummy(parent) { + XMLDummy.__super__.constructor.call(this, parent); + this.type = NodeType.Dummy; + } + + XMLDummy.prototype.clone = function() { + return Object.create(this); + }; + + XMLDummy.prototype.toString = function(options) { + return ''; + }; + + return XMLDummy; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLElement.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLElement.js new file mode 100644 index 00000000..c1657299 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLElement.js @@ -0,0 +1,298 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLAttribute, XMLElement, XMLNamedNodeMap, XMLNode, getValue, isFunction, isObject, ref, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue; + + XMLNode = require('./XMLNode'); + + NodeType = require('./NodeType'); + + XMLAttribute = require('./XMLAttribute'); + + XMLNamedNodeMap = require('./XMLNamedNodeMap'); + + module.exports = XMLElement = (function(superClass) { + extend(XMLElement, superClass); + + function XMLElement(parent, name, attributes) { + var child, j, len, ref1; + XMLElement.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing element name. " + this.debugInfo()); + } + this.name = this.stringify.name(name); + this.type = NodeType.Element; + this.attribs = {}; + this.schemaTypeInfo = null; + if (attributes != null) { + this.attribute(attributes); + } + if (parent.type === NodeType.Document) { + this.isRoot = true; + this.documentObject = parent; + parent.rootObject = this; + if (parent.children) { + ref1 = parent.children; + for (j = 0, len = ref1.length; j < len; j++) { + child = ref1[j]; + if (child.type === NodeType.DocType) { + child.name = this.name; + break; + } + } + } + } + } + + Object.defineProperty(XMLElement.prototype, 'tagName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLElement.prototype, 'namespaceURI', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLElement.prototype, 'prefix', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLElement.prototype, 'localName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLElement.prototype, 'id', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'className', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'classList', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'attributes', { + get: function() { + if (!this.attributeMap || !this.attributeMap.nodes) { + this.attributeMap = new XMLNamedNodeMap(this.attribs); + } + return this.attributeMap; + } + }); + + XMLElement.prototype.clone = function() { + var att, attName, clonedSelf, ref1; + clonedSelf = Object.create(this); + if (clonedSelf.isRoot) { + clonedSelf.documentObject = null; + } + clonedSelf.attribs = {}; + ref1 = this.attribs; + for (attName in ref1) { + if (!hasProp.call(ref1, attName)) continue; + att = ref1[attName]; + clonedSelf.attribs[attName] = att.clone(); + } + clonedSelf.children = []; + this.children.forEach(function(child) { + var clonedChild; + clonedChild = child.clone(); + clonedChild.parent = clonedSelf; + return clonedSelf.children.push(clonedChild); + }); + return clonedSelf; + }; + + XMLElement.prototype.attribute = function(name, value) { + var attName, attValue; + if (name != null) { + name = getValue(name); + } + if (isObject(name)) { + for (attName in name) { + if (!hasProp.call(name, attName)) continue; + attValue = name[attName]; + this.attribute(attName, attValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + if (this.options.keepNullAttributes && (value == null)) { + this.attribs[name] = new XMLAttribute(this, name, ""); + } else if (value != null) { + this.attribs[name] = new XMLAttribute(this, name, value); + } + } + return this; + }; + + XMLElement.prototype.removeAttribute = function(name) { + var attName, j, len; + if (name == null) { + throw new Error("Missing attribute name. " + this.debugInfo()); + } + name = getValue(name); + if (Array.isArray(name)) { + for (j = 0, len = name.length; j < len; j++) { + attName = name[j]; + delete this.attribs[attName]; + } + } else { + delete this.attribs[name]; + } + return this; + }; + + XMLElement.prototype.toString = function(options) { + return this.options.writer.element(this, this.options.writer.filterOptions(options)); + }; + + XMLElement.prototype.att = function(name, value) { + return this.attribute(name, value); + }; + + XMLElement.prototype.a = function(name, value) { + return this.attribute(name, value); + }; + + XMLElement.prototype.getAttribute = function(name) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name].value; + } else { + return null; + } + }; + + XMLElement.prototype.setAttribute = function(name, value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNode = function(name) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name]; + } else { + return null; + } + }; + + XMLElement.prototype.setAttributeNode = function(newAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.removeAttributeNode = function(oldAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagName = function(name) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.removeAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNodeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setAttributeNodeNS = function(newAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.hasAttribute = function(name) { + return this.attribs.hasOwnProperty(name); + }; + + XMLElement.prototype.hasAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setIdAttribute = function(name, isId) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name].isId; + } else { + return isId; + } + }; + + XMLElement.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setIdAttributeNode = function(idAttr, isId) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagName = function(tagname) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByClassName = function(classNames) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.isEqualNode = function(node) { + var i, j, ref1; + if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.namespaceURI !== this.namespaceURI) { + return false; + } + if (node.prefix !== this.prefix) { + return false; + } + if (node.localName !== this.localName) { + return false; + } + if (node.attribs.length !== this.attribs.length) { + return false; + } + for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) { + if (!this.attribs[i].isEqualNode(node.attribs[i])) { + return false; + } + } + return true; + }; + + return XMLElement; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js new file mode 100644 index 00000000..885402d0 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js @@ -0,0 +1,58 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLNamedNodeMap; + + module.exports = XMLNamedNodeMap = (function() { + function XMLNamedNodeMap(nodes) { + this.nodes = nodes; + } + + Object.defineProperty(XMLNamedNodeMap.prototype, 'length', { + get: function() { + return Object.keys(this.nodes).length || 0; + } + }); + + XMLNamedNodeMap.prototype.clone = function() { + return this.nodes = null; + }; + + XMLNamedNodeMap.prototype.getNamedItem = function(name) { + return this.nodes[name]; + }; + + XMLNamedNodeMap.prototype.setNamedItem = function(node) { + var oldNode; + oldNode = this.nodes[node.nodeName]; + this.nodes[node.nodeName] = node; + return oldNode || null; + }; + + XMLNamedNodeMap.prototype.removeNamedItem = function(name) { + var oldNode; + oldNode = this.nodes[name]; + delete this.nodes[name]; + return oldNode || null; + }; + + XMLNamedNodeMap.prototype.item = function(index) { + return this.nodes[Object.keys(this.nodes)[index]] || null; + }; + + XMLNamedNodeMap.prototype.getNamedItemNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented."); + }; + + XMLNamedNodeMap.prototype.setNamedItemNS = function(node) { + throw new Error("This DOM method is not implemented."); + }; + + XMLNamedNodeMap.prototype.removeNamedItemNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented."); + }; + + return XMLNamedNodeMap; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNode.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNode.js new file mode 100644 index 00000000..e2c7bb76 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNode.js @@ -0,0 +1,785 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var DocumentPosition, NodeType, XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLNamedNodeMap, XMLNode, XMLNodeList, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref1, + hasProp = {}.hasOwnProperty; + + ref1 = require('./Utility'), isObject = ref1.isObject, isFunction = ref1.isFunction, isEmpty = ref1.isEmpty, getValue = ref1.getValue; + + XMLElement = null; + + XMLCData = null; + + XMLComment = null; + + XMLDeclaration = null; + + XMLDocType = null; + + XMLRaw = null; + + XMLText = null; + + XMLProcessingInstruction = null; + + XMLDummy = null; + + NodeType = null; + + XMLNodeList = null; + + XMLNamedNodeMap = null; + + DocumentPosition = null; + + module.exports = XMLNode = (function() { + function XMLNode(parent1) { + this.parent = parent1; + if (this.parent) { + this.options = this.parent.options; + this.stringify = this.parent.stringify; + } + this.value = null; + this.children = []; + this.baseURI = null; + if (!XMLElement) { + XMLElement = require('./XMLElement'); + XMLCData = require('./XMLCData'); + XMLComment = require('./XMLComment'); + XMLDeclaration = require('./XMLDeclaration'); + XMLDocType = require('./XMLDocType'); + XMLRaw = require('./XMLRaw'); + XMLText = require('./XMLText'); + XMLProcessingInstruction = require('./XMLProcessingInstruction'); + XMLDummy = require('./XMLDummy'); + NodeType = require('./NodeType'); + XMLNodeList = require('./XMLNodeList'); + XMLNamedNodeMap = require('./XMLNamedNodeMap'); + DocumentPosition = require('./DocumentPosition'); + } + } + + Object.defineProperty(XMLNode.prototype, 'nodeName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLNode.prototype, 'nodeType', { + get: function() { + return this.type; + } + }); + + Object.defineProperty(XMLNode.prototype, 'nodeValue', { + get: function() { + return this.value; + } + }); + + Object.defineProperty(XMLNode.prototype, 'parentNode', { + get: function() { + return this.parent; + } + }); + + Object.defineProperty(XMLNode.prototype, 'childNodes', { + get: function() { + if (!this.childNodeList || !this.childNodeList.nodes) { + this.childNodeList = new XMLNodeList(this.children); + } + return this.childNodeList; + } + }); + + Object.defineProperty(XMLNode.prototype, 'firstChild', { + get: function() { + return this.children[0] || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'lastChild', { + get: function() { + return this.children[this.children.length - 1] || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'previousSibling', { + get: function() { + var i; + i = this.parent.children.indexOf(this); + return this.parent.children[i - 1] || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'nextSibling', { + get: function() { + var i; + i = this.parent.children.indexOf(this); + return this.parent.children[i + 1] || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'ownerDocument', { + get: function() { + return this.document() || null; + } + }); + + Object.defineProperty(XMLNode.prototype, 'textContent', { + get: function() { + var child, j, len, ref2, str; + if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) { + str = ''; + ref2 = this.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (child.textContent) { + str += child.textContent; + } + } + return str; + } else { + return null; + } + }, + set: function(value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + XMLNode.prototype.setParent = function(parent) { + var child, j, len, ref2, results; + this.parent = parent; + if (parent) { + this.options = parent.options; + this.stringify = parent.stringify; + } + ref2 = this.children; + results = []; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + results.push(child.setParent(this)); + } + return results; + }; + + XMLNode.prototype.element = function(name, attributes, text) { + var childNode, item, j, k, key, lastChild, len, len1, ref2, ref3, val; + lastChild = null; + if (attributes === null && (text == null)) { + ref2 = [{}, null], attributes = ref2[0], text = ref2[1]; + } + if (attributes == null) { + attributes = {}; + } + attributes = getValue(attributes); + if (!isObject(attributes)) { + ref3 = [attributes, text], text = ref3[0], attributes = ref3[1]; + } + if (name != null) { + name = getValue(name); + } + if (Array.isArray(name)) { + for (j = 0, len = name.length; j < len; j++) { + item = name[j]; + lastChild = this.element(item); + } + } else if (isFunction(name)) { + lastChild = this.element(name.apply()); + } else if (isObject(name)) { + for (key in name) { + if (!hasProp.call(name, key)) continue; + val = name[key]; + if (isFunction(val)) { + val = val.apply(); + } + if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) { + lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val); + } else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty(val)) { + lastChild = this.dummy(); + } else if (isObject(val) && isEmpty(val)) { + lastChild = this.element(key); + } else if (!this.options.keepNullNodes && (val == null)) { + lastChild = this.dummy(); + } else if (!this.options.separateArrayItems && Array.isArray(val)) { + for (k = 0, len1 = val.length; k < len1; k++) { + item = val[k]; + childNode = {}; + childNode[key] = item; + lastChild = this.element(childNode); + } + } else if (isObject(val)) { + if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) { + lastChild = this.element(val); + } else { + lastChild = this.element(key); + lastChild.element(val); + } + } else { + lastChild = this.element(key, val); + } + } + } else if (!this.options.keepNullNodes && text === null) { + lastChild = this.dummy(); + } else { + if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) { + lastChild = this.text(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) { + lastChild = this.cdata(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) { + lastChild = this.comment(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) { + lastChild = this.raw(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) { + lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text); + } else { + lastChild = this.node(name, attributes, text); + } + } + if (lastChild == null) { + throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo()); + } + return lastChild; + }; + + XMLNode.prototype.insertBefore = function(name, attributes, text) { + var child, i, newChild, refChild, removed; + if (name != null ? name.type : void 0) { + newChild = name; + refChild = attributes; + newChild.setParent(this); + if (refChild) { + i = children.indexOf(refChild); + removed = children.splice(i); + children.push(newChild); + Array.prototype.push.apply(children, removed); + } else { + children.push(newChild); + } + return newChild; + } else { + if (this.isRoot) { + throw new Error("Cannot insert elements at root level. " + this.debugInfo(name)); + } + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.element(name, attributes, text); + Array.prototype.push.apply(this.parent.children, removed); + return child; + } + }; + + XMLNode.prototype.insertAfter = function(name, attributes, text) { + var child, i, removed; + if (this.isRoot) { + throw new Error("Cannot insert elements at root level. " + this.debugInfo(name)); + } + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.element(name, attributes, text); + Array.prototype.push.apply(this.parent.children, removed); + return child; + }; + + XMLNode.prototype.remove = function() { + var i, ref2; + if (this.isRoot) { + throw new Error("Cannot remove the root element. " + this.debugInfo()); + } + i = this.parent.children.indexOf(this); + [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref2 = [])), ref2; + return this.parent; + }; + + XMLNode.prototype.node = function(name, attributes, text) { + var child, ref2; + if (name != null) { + name = getValue(name); + } + attributes || (attributes = {}); + attributes = getValue(attributes); + if (!isObject(attributes)) { + ref2 = [attributes, text], text = ref2[0], attributes = ref2[1]; + } + child = new XMLElement(this, name, attributes); + if (text != null) { + child.text(text); + } + this.children.push(child); + return child; + }; + + XMLNode.prototype.text = function(value) { + var child; + if (isObject(value)) { + this.element(value); + } + child = new XMLText(this, value); + this.children.push(child); + return this; + }; + + XMLNode.prototype.cdata = function(value) { + var child; + child = new XMLCData(this, value); + this.children.push(child); + return this; + }; + + XMLNode.prototype.comment = function(value) { + var child; + child = new XMLComment(this, value); + this.children.push(child); + return this; + }; + + XMLNode.prototype.commentBefore = function(value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.comment(value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; + + XMLNode.prototype.commentAfter = function(value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.comment(value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; + + XMLNode.prototype.raw = function(value) { + var child; + child = new XMLRaw(this, value); + this.children.push(child); + return this; + }; + + XMLNode.prototype.dummy = function() { + var child; + child = new XMLDummy(this); + return child; + }; + + XMLNode.prototype.instruction = function(target, value) { + var insTarget, insValue, instruction, j, len; + if (target != null) { + target = getValue(target); + } + if (value != null) { + value = getValue(value); + } + if (Array.isArray(target)) { + for (j = 0, len = target.length; j < len; j++) { + insTarget = target[j]; + this.instruction(insTarget); + } + } else if (isObject(target)) { + for (insTarget in target) { + if (!hasProp.call(target, insTarget)) continue; + insValue = target[insTarget]; + this.instruction(insTarget, insValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + instruction = new XMLProcessingInstruction(this, target, value); + this.children.push(instruction); + } + return this; + }; + + XMLNode.prototype.instructionBefore = function(target, value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.instruction(target, value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; + + XMLNode.prototype.instructionAfter = function(target, value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.instruction(target, value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; + + XMLNode.prototype.declaration = function(version, encoding, standalone) { + var doc, xmldec; + doc = this.document(); + xmldec = new XMLDeclaration(doc, version, encoding, standalone); + if (doc.children.length === 0) { + doc.children.unshift(xmldec); + } else if (doc.children[0].type === NodeType.Declaration) { + doc.children[0] = xmldec; + } else { + doc.children.unshift(xmldec); + } + return doc.root() || doc; + }; + + XMLNode.prototype.dtd = function(pubID, sysID) { + var child, doc, doctype, i, j, k, len, len1, ref2, ref3; + doc = this.document(); + doctype = new XMLDocType(doc, pubID, sysID); + ref2 = doc.children; + for (i = j = 0, len = ref2.length; j < len; i = ++j) { + child = ref2[i]; + if (child.type === NodeType.DocType) { + doc.children[i] = doctype; + return doctype; + } + } + ref3 = doc.children; + for (i = k = 0, len1 = ref3.length; k < len1; i = ++k) { + child = ref3[i]; + if (child.isRoot) { + doc.children.splice(i, 0, doctype); + return doctype; + } + } + doc.children.push(doctype); + return doctype; + }; + + XMLNode.prototype.up = function() { + if (this.isRoot) { + throw new Error("The root node has no parent. Use doc() if you need to get the document object."); + } + return this.parent; + }; + + XMLNode.prototype.root = function() { + var node; + node = this; + while (node) { + if (node.type === NodeType.Document) { + return node.rootObject; + } else if (node.isRoot) { + return node; + } else { + node = node.parent; + } + } + }; + + XMLNode.prototype.document = function() { + var node; + node = this; + while (node) { + if (node.type === NodeType.Document) { + return node; + } else { + node = node.parent; + } + } + }; + + XMLNode.prototype.end = function(options) { + return this.document().end(options); + }; + + XMLNode.prototype.prev = function() { + var i; + i = this.parent.children.indexOf(this); + if (i < 1) { + throw new Error("Already at the first node. " + this.debugInfo()); + } + return this.parent.children[i - 1]; + }; + + XMLNode.prototype.next = function() { + var i; + i = this.parent.children.indexOf(this); + if (i === -1 || i === this.parent.children.length - 1) { + throw new Error("Already at the last node. " + this.debugInfo()); + } + return this.parent.children[i + 1]; + }; + + XMLNode.prototype.importDocument = function(doc) { + var clonedRoot; + clonedRoot = doc.root().clone(); + clonedRoot.parent = this; + clonedRoot.isRoot = false; + this.children.push(clonedRoot); + return this; + }; + + XMLNode.prototype.debugInfo = function(name) { + var ref2, ref3; + name = name || this.name; + if ((name == null) && !((ref2 = this.parent) != null ? ref2.name : void 0)) { + return ""; + } else if (name == null) { + return "parent: <" + this.parent.name + ">"; + } else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) { + return "node: <" + name + ">"; + } else { + return "node: <" + name + ">, parent: <" + this.parent.name + ">"; + } + }; + + XMLNode.prototype.ele = function(name, attributes, text) { + return this.element(name, attributes, text); + }; + + XMLNode.prototype.nod = function(name, attributes, text) { + return this.node(name, attributes, text); + }; + + XMLNode.prototype.txt = function(value) { + return this.text(value); + }; + + XMLNode.prototype.dat = function(value) { + return this.cdata(value); + }; + + XMLNode.prototype.com = function(value) { + return this.comment(value); + }; + + XMLNode.prototype.ins = function(target, value) { + return this.instruction(target, value); + }; + + XMLNode.prototype.doc = function() { + return this.document(); + }; + + XMLNode.prototype.dec = function(version, encoding, standalone) { + return this.declaration(version, encoding, standalone); + }; + + XMLNode.prototype.e = function(name, attributes, text) { + return this.element(name, attributes, text); + }; + + XMLNode.prototype.n = function(name, attributes, text) { + return this.node(name, attributes, text); + }; + + XMLNode.prototype.t = function(value) { + return this.text(value); + }; + + XMLNode.prototype.d = function(value) { + return this.cdata(value); + }; + + XMLNode.prototype.c = function(value) { + return this.comment(value); + }; + + XMLNode.prototype.r = function(value) { + return this.raw(value); + }; + + XMLNode.prototype.i = function(target, value) { + return this.instruction(target, value); + }; + + XMLNode.prototype.u = function() { + return this.up(); + }; + + XMLNode.prototype.importXMLBuilder = function(doc) { + return this.importDocument(doc); + }; + + XMLNode.prototype.replaceChild = function(newChild, oldChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.removeChild = function(oldChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.appendChild = function(newChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.hasChildNodes = function() { + return this.children.length !== 0; + }; + + XMLNode.prototype.cloneNode = function(deep) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.normalize = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.isSupported = function(feature, version) { + return true; + }; + + XMLNode.prototype.hasAttributes = function() { + return this.attribs.length !== 0; + }; + + XMLNode.prototype.compareDocumentPosition = function(other) { + var ref, res; + ref = this; + if (ref === other) { + return 0; + } else if (this.document() !== other.document()) { + res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific; + if (Math.random() < 0.5) { + res |= DocumentPosition.Preceding; + } else { + res |= DocumentPosition.Following; + } + return res; + } else if (ref.isAncestor(other)) { + return DocumentPosition.Contains | DocumentPosition.Preceding; + } else if (ref.isDescendant(other)) { + return DocumentPosition.Contains | DocumentPosition.Following; + } else if (ref.isPreceding(other)) { + return DocumentPosition.Preceding; + } else { + return DocumentPosition.Following; + } + }; + + XMLNode.prototype.isSameNode = function(other) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.lookupPrefix = function(namespaceURI) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.isDefaultNamespace = function(namespaceURI) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.lookupNamespaceURI = function(prefix) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.isEqualNode = function(node) { + var i, j, ref2; + if (node.nodeType !== this.nodeType) { + return false; + } + if (node.children.length !== this.children.length) { + return false; + } + for (i = j = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j <= ref2 : j >= ref2; i = 0 <= ref2 ? ++j : --j) { + if (!this.children[i].isEqualNode(node.children[i])) { + return false; + } + } + return true; + }; + + XMLNode.prototype.getFeature = function(feature, version) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.setUserData = function(key, data, handler) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.getUserData = function(key) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLNode.prototype.contains = function(other) { + if (!other) { + return false; + } + return other === this || this.isDescendant(other); + }; + + XMLNode.prototype.isDescendant = function(node) { + var child, isDescendantChild, j, len, ref2; + ref2 = this.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (node === child) { + return true; + } + isDescendantChild = child.isDescendant(node); + if (isDescendantChild) { + return true; + } + } + return false; + }; + + XMLNode.prototype.isAncestor = function(node) { + return node.isDescendant(this); + }; + + XMLNode.prototype.isPreceding = function(node) { + var nodePos, thisPos; + nodePos = this.treePosition(node); + thisPos = this.treePosition(this); + if (nodePos === -1 || thisPos === -1) { + return false; + } else { + return nodePos < thisPos; + } + }; + + XMLNode.prototype.isFollowing = function(node) { + var nodePos, thisPos; + nodePos = this.treePosition(node); + thisPos = this.treePosition(this); + if (nodePos === -1 || thisPos === -1) { + return false; + } else { + return nodePos > thisPos; + } + }; + + XMLNode.prototype.treePosition = function(node) { + var found, pos; + pos = 0; + found = false; + this.foreachTreeNode(this.document(), function(childNode) { + pos++; + if (!found && childNode === node) { + return found = true; + } + }); + if (found) { + return pos; + } else { + return -1; + } + }; + + XMLNode.prototype.foreachTreeNode = function(node, func) { + var child, j, len, ref2, res; + node || (node = this.document()); + ref2 = node.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (res = func(child)) { + return res; + } else { + res = this.foreachTreeNode(child, func); + if (res) { + return res; + } + } + } + }; + + return XMLNode; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNodeFilter.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNodeFilter.js new file mode 100644 index 00000000..ce32fd59 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNodeFilter.js @@ -0,0 +1,48 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLNodeFilter; + + module.exports = XMLNodeFilter = (function() { + function XMLNodeFilter() {} + + XMLNodeFilter.prototype.FilterAccept = 1; + + XMLNodeFilter.prototype.FilterReject = 2; + + XMLNodeFilter.prototype.FilterSkip = 3; + + XMLNodeFilter.prototype.ShowAll = 0xffffffff; + + XMLNodeFilter.prototype.ShowElement = 0x1; + + XMLNodeFilter.prototype.ShowAttribute = 0x2; + + XMLNodeFilter.prototype.ShowText = 0x4; + + XMLNodeFilter.prototype.ShowCDataSection = 0x8; + + XMLNodeFilter.prototype.ShowEntityReference = 0x10; + + XMLNodeFilter.prototype.ShowEntity = 0x20; + + XMLNodeFilter.prototype.ShowProcessingInstruction = 0x40; + + XMLNodeFilter.prototype.ShowComment = 0x80; + + XMLNodeFilter.prototype.ShowDocument = 0x100; + + XMLNodeFilter.prototype.ShowDocumentType = 0x200; + + XMLNodeFilter.prototype.ShowDocumentFragment = 0x400; + + XMLNodeFilter.prototype.ShowNotation = 0x800; + + XMLNodeFilter.prototype.acceptNode = function(node) { + throw new Error("This DOM method is not implemented."); + }; + + return XMLNodeFilter; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNodeList.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNodeList.js new file mode 100644 index 00000000..3414a3e4 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLNodeList.js @@ -0,0 +1,28 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLNodeList; + + module.exports = XMLNodeList = (function() { + function XMLNodeList(nodes) { + this.nodes = nodes; + } + + Object.defineProperty(XMLNodeList.prototype, 'length', { + get: function() { + return this.nodes.length || 0; + } + }); + + XMLNodeList.prototype.clone = function() { + return this.nodes = null; + }; + + XMLNodeList.prototype.item = function(index) { + return this.nodes[index] || null; + }; + + return XMLNodeList; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js new file mode 100644 index 00000000..d4333d46 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js @@ -0,0 +1,49 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLCharacterData, XMLProcessingInstruction, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLCharacterData = require('./XMLCharacterData'); + + module.exports = XMLProcessingInstruction = (function(superClass) { + extend(XMLProcessingInstruction, superClass); + + function XMLProcessingInstruction(parent, target, value) { + XMLProcessingInstruction.__super__.constructor.call(this, parent); + if (target == null) { + throw new Error("Missing instruction target. " + this.debugInfo()); + } + this.type = NodeType.ProcessingInstruction; + this.target = this.stringify.insTarget(target); + this.name = this.target; + if (value) { + this.value = this.stringify.insValue(value); + } + } + + XMLProcessingInstruction.prototype.clone = function() { + return Object.create(this); + }; + + XMLProcessingInstruction.prototype.toString = function(options) { + return this.options.writer.processingInstruction(this, this.options.writer.filterOptions(options)); + }; + + XMLProcessingInstruction.prototype.isEqualNode = function(node) { + if (!XMLProcessingInstruction.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.target !== this.target) { + return false; + } + return true; + }; + + return XMLProcessingInstruction; + + })(XMLCharacterData); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLRaw.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLRaw.js new file mode 100644 index 00000000..b5928502 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLRaw.js @@ -0,0 +1,35 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLNode, XMLRaw, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLNode = require('./XMLNode'); + + module.exports = XMLRaw = (function(superClass) { + extend(XMLRaw, superClass); + + function XMLRaw(parent, text) { + XMLRaw.__super__.constructor.call(this, parent); + if (text == null) { + throw new Error("Missing raw text. " + this.debugInfo()); + } + this.type = NodeType.Raw; + this.value = this.stringify.raw(text); + } + + XMLRaw.prototype.clone = function() { + return Object.create(this); + }; + + XMLRaw.prototype.toString = function(options) { + return this.options.writer.raw(this, this.options.writer.filterOptions(options)); + }; + + return XMLRaw; + + })(XMLNode); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStreamWriter.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStreamWriter.js new file mode 100644 index 00000000..159dc6b6 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStreamWriter.js @@ -0,0 +1,176 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLStreamWriter, XMLWriterBase, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = require('./NodeType'); + + XMLWriterBase = require('./XMLWriterBase'); + + WriterState = require('./WriterState'); + + module.exports = XMLStreamWriter = (function(superClass) { + extend(XMLStreamWriter, superClass); + + function XMLStreamWriter(stream, options) { + this.stream = stream; + XMLStreamWriter.__super__.constructor.call(this, options); + } + + XMLStreamWriter.prototype.endline = function(node, options, level) { + if (node.isLastRootNode && options.state === WriterState.CloseTag) { + return ''; + } else { + return XMLStreamWriter.__super__.endline.call(this, node, options, level); + } + }; + + XMLStreamWriter.prototype.document = function(doc, options) { + var child, i, j, k, len, len1, ref, ref1, results; + ref = doc.children; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + child = ref[i]; + child.isLastRootNode = i === doc.children.length - 1; + } + options = this.filterOptions(options); + ref1 = doc.children; + results = []; + for (k = 0, len1 = ref1.length; k < len1; k++) { + child = ref1[k]; + results.push(this.writeChildNode(child, options, 0)); + } + return results; + }; + + XMLStreamWriter.prototype.attribute = function(att, options, level) { + return this.stream.write(XMLStreamWriter.__super__.attribute.call(this, att, options, level)); + }; + + XMLStreamWriter.prototype.cdata = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.cdata.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.comment = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.comment.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.declaration = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.declaration.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.docType = function(node, options, level) { + var child, j, len, ref; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + this.stream.write(this.indent(node, options, level)); + this.stream.write(' 0) { + this.stream.write(' ['); + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.InsideTag; + ref = node.children; + for (j = 0, len = ref.length; j < len; j++) { + child = ref[j]; + this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + this.stream.write(']'); + } + options.state = WriterState.CloseTag; + this.stream.write(options.spaceBeforeSlash + '>'); + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.None; + return this.closeNode(node, options, level); + }; + + XMLStreamWriter.prototype.element = function(node, options, level) { + var att, child, childNodeCount, firstChildNode, j, len, name, prettySuppressed, ref, ref1; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + this.stream.write(this.indent(node, options, level) + '<' + node.name); + ref = node.attribs; + for (name in ref) { + if (!hasProp.call(ref, name)) continue; + att = ref[name]; + this.attribute(att, options, level); + } + childNodeCount = node.children.length; + firstChildNode = childNodeCount === 0 ? null : node.children[0]; + if (childNodeCount === 0 || node.children.every(function(e) { + return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === ''; + })) { + if (options.allowEmpty) { + this.stream.write('>'); + options.state = WriterState.CloseTag; + this.stream.write(''); + } else { + options.state = WriterState.CloseTag; + this.stream.write(options.spaceBeforeSlash + '/>'); + } + } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) { + this.stream.write('>'); + options.state = WriterState.InsideTag; + options.suppressPrettyCount++; + prettySuppressed = true; + this.writeChildNode(firstChildNode, options, level + 1); + options.suppressPrettyCount--; + prettySuppressed = false; + options.state = WriterState.CloseTag; + this.stream.write(''); + } else { + this.stream.write('>' + this.endline(node, options, level)); + options.state = WriterState.InsideTag; + ref1 = node.children; + for (j = 0, len = ref1.length; j < len; j++) { + child = ref1[j]; + this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + this.stream.write(this.indent(node, options, level) + ''); + } + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.None; + return this.closeNode(node, options, level); + }; + + XMLStreamWriter.prototype.processingInstruction = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.processingInstruction.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.raw = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.raw.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.text = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.text.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.dtdAttList = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdAttList.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.dtdElement = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdElement.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.dtdEntity = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdEntity.call(this, node, options, level)); + }; + + XMLStreamWriter.prototype.dtdNotation = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdNotation.call(this, node, options, level)); + }; + + return XMLStreamWriter; + + })(XMLWriterBase); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStringWriter.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStringWriter.js new file mode 100644 index 00000000..71870170 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStringWriter.js @@ -0,0 +1,35 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLStringWriter, XMLWriterBase, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLWriterBase = require('./XMLWriterBase'); + + module.exports = XMLStringWriter = (function(superClass) { + extend(XMLStringWriter, superClass); + + function XMLStringWriter(options) { + XMLStringWriter.__super__.constructor.call(this, options); + } + + XMLStringWriter.prototype.document = function(doc, options) { + var child, i, len, r, ref; + options = this.filterOptions(options); + r = ''; + ref = doc.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + r += this.writeChildNode(child, options, 0); + } + if (options.pretty && r.slice(-options.newline.length) === options.newline) { + r = r.slice(0, -options.newline.length); + } + return r; + }; + + return XMLStringWriter; + + })(XMLWriterBase); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStringifier.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStringifier.js new file mode 100644 index 00000000..a39475c1 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/XMLStringifier.js @@ -0,0 +1,240 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLStringifier, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + hasProp = {}.hasOwnProperty; + + module.exports = XMLStringifier = (function() { + function XMLStringifier(options) { + this.assertLegalName = bind(this.assertLegalName, this); + this.assertLegalChar = bind(this.assertLegalChar, this); + var key, ref, value; + options || (options = {}); + this.options = options; + if (!this.options.version) { + this.options.version = '1.0'; + } + ref = options.stringify || {}; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this[key] = value; + } + } + + XMLStringifier.prototype.name = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalName('' + val || ''); + }; + + XMLStringifier.prototype.text = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar(this.textEscape('' + val || '')); + }; + + XMLStringifier.prototype.cdata = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + val = val.replace(']]>', ']]]]>'); + return this.assertLegalChar(val); + }; + + XMLStringifier.prototype.comment = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + if (val.match(/--/)) { + throw new Error("Comment text cannot contain double-hypen: " + val); + } + return this.assertLegalChar(val); + }; + + XMLStringifier.prototype.raw = function(val) { + if (this.options.noValidation) { + return val; + } + return '' + val || ''; + }; + + XMLStringifier.prototype.attValue = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar(this.attEscape(val = '' + val || '')); + }; + + XMLStringifier.prototype.insTarget = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.insValue = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + if (val.match(/\?>/)) { + throw new Error("Invalid processing instruction value: " + val); + } + return this.assertLegalChar(val); + }; + + XMLStringifier.prototype.xmlVersion = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + if (!val.match(/1\.[0-9]+/)) { + throw new Error("Invalid version number: " + val); + } + return val; + }; + + XMLStringifier.prototype.xmlEncoding = function(val) { + if (this.options.noValidation) { + return val; + } + val = '' + val || ''; + if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) { + throw new Error("Invalid encoding: " + val); + } + return this.assertLegalChar(val); + }; + + XMLStringifier.prototype.xmlStandalone = function(val) { + if (this.options.noValidation) { + return val; + } + if (val) { + return "yes"; + } else { + return "no"; + } + }; + + XMLStringifier.prototype.dtdPubID = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdSysID = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdElementValue = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdAttType = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdAttDefault = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdEntityValue = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.dtdNData = function(val) { + if (this.options.noValidation) { + return val; + } + return this.assertLegalChar('' + val || ''); + }; + + XMLStringifier.prototype.convertAttKey = '@'; + + XMLStringifier.prototype.convertPIKey = '?'; + + XMLStringifier.prototype.convertTextKey = '#text'; + + XMLStringifier.prototype.convertCDataKey = '#cdata'; + + XMLStringifier.prototype.convertCommentKey = '#comment'; + + XMLStringifier.prototype.convertRawKey = '#raw'; + + XMLStringifier.prototype.assertLegalChar = function(str) { + var regex, res; + if (this.options.noValidation) { + return str; + } + regex = ''; + if (this.options.version === '1.0') { + regex = /[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + if (res = str.match(regex)) { + throw new Error("Invalid character in string: " + str + " at index " + res.index); + } + } else if (this.options.version === '1.1') { + regex = /[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + if (res = str.match(regex)) { + throw new Error("Invalid character in string: " + str + " at index " + res.index); + } + } + return str; + }; + + XMLStringifier.prototype.assertLegalName = function(str) { + var regex; + if (this.options.noValidation) { + return str; + } + this.assertLegalChar(str); + regex = /^([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])([\x2D\.0-:A-Z_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/; + if (!str.match(regex)) { + throw new Error("Invalid character in name"); + } + return str; + }; + + XMLStringifier.prototype.textEscape = function(str) { + var ampregex; + if (this.options.noValidation) { + return str; + } + ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; + return str.replace(ampregex, '&').replace(//g, '>').replace(/\r/g, ' '); + }; + + XMLStringifier.prototype.attEscape = function(str) { + var ampregex; + if (this.options.noValidation) { + return str; + } + ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g; + return str.replace(ampregex, '&').replace(/ 0) { + return new Array(indentLevel).join(options.indent); + } + } + return ''; + }; + + XMLWriterBase.prototype.endline = function(node, options, level) { + if (!options.pretty || options.suppressPrettyCount) { + return ''; + } else { + return options.newline; + } + }; + + XMLWriterBase.prototype.attribute = function(att, options, level) { + var r; + this.openAttribute(att, options, level); + r = ' ' + att.name + '="' + att.value + '"'; + this.closeAttribute(att, options, level); + return r; + }; + + XMLWriterBase.prototype.cdata = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.comment = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.declaration = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + ''; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.docType = function(node, options, level) { + var child, i, len, r, ref; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + r += ' 0) { + r += ' ['; + r += this.endline(node, options, level); + options.state = WriterState.InsideTag; + ref = node.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + r += this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + r += ']'; + } + options.state = WriterState.CloseTag; + r += options.spaceBeforeSlash + '>'; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.element = function(node, options, level) { + var att, child, childNodeCount, firstChildNode, i, j, len, len1, name, prettySuppressed, r, ref, ref1, ref2; + level || (level = 0); + prettySuppressed = false; + r = ''; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r += this.indent(node, options, level) + '<' + node.name; + ref = node.attribs; + for (name in ref) { + if (!hasProp.call(ref, name)) continue; + att = ref[name]; + r += this.attribute(att, options, level); + } + childNodeCount = node.children.length; + firstChildNode = childNodeCount === 0 ? null : node.children[0]; + if (childNodeCount === 0 || node.children.every(function(e) { + return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === ''; + })) { + if (options.allowEmpty) { + r += '>'; + options.state = WriterState.CloseTag; + r += '' + this.endline(node, options, level); + } else { + options.state = WriterState.CloseTag; + r += options.spaceBeforeSlash + '/>' + this.endline(node, options, level); + } + } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) { + r += '>'; + options.state = WriterState.InsideTag; + options.suppressPrettyCount++; + prettySuppressed = true; + r += this.writeChildNode(firstChildNode, options, level + 1); + options.suppressPrettyCount--; + prettySuppressed = false; + options.state = WriterState.CloseTag; + r += '' + this.endline(node, options, level); + } else { + if (options.dontPrettyTextNodes) { + ref1 = node.children; + for (i = 0, len = ref1.length; i < len; i++) { + child = ref1[i]; + if ((child.type === NodeType.Text || child.type === NodeType.Raw) && (child.value != null)) { + options.suppressPrettyCount++; + prettySuppressed = true; + break; + } + } + } + r += '>' + this.endline(node, options, level); + options.state = WriterState.InsideTag; + ref2 = node.children; + for (j = 0, len1 = ref2.length; j < len1; j++) { + child = ref2[j]; + r += this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + r += this.indent(node, options, level) + ''; + if (prettySuppressed) { + options.suppressPrettyCount--; + } + r += this.endline(node, options, level); + options.state = WriterState.None; + } + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.writeChildNode = function(node, options, level) { + switch (node.type) { + case NodeType.CData: + return this.cdata(node, options, level); + case NodeType.Comment: + return this.comment(node, options, level); + case NodeType.Element: + return this.element(node, options, level); + case NodeType.Raw: + return this.raw(node, options, level); + case NodeType.Text: + return this.text(node, options, level); + case NodeType.ProcessingInstruction: + return this.processingInstruction(node, options, level); + case NodeType.Dummy: + return ''; + case NodeType.Declaration: + return this.declaration(node, options, level); + case NodeType.DocType: + return this.docType(node, options, level); + case NodeType.AttributeDeclaration: + return this.dtdAttList(node, options, level); + case NodeType.ElementDeclaration: + return this.dtdElement(node, options, level); + case NodeType.EntityDeclaration: + return this.dtdEntity(node, options, level); + case NodeType.NotationDeclaration: + return this.dtdNotation(node, options, level); + default: + throw new Error("Unknown XML node type: " + node.constructor.name); + } + }; + + XMLWriterBase.prototype.processingInstruction = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + ''; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.raw = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + options.state = WriterState.InsideTag; + r += node.value; + options.state = WriterState.CloseTag; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.text = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + options.state = WriterState.InsideTag; + r += node.value; + options.state = WriterState.CloseTag; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdAttList = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdElement = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdEntity = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdNotation = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.openNode = function(node, options, level) {}; + + XMLWriterBase.prototype.closeNode = function(node, options, level) {}; + + XMLWriterBase.prototype.openAttribute = function(att, options, level) {}; + + XMLWriterBase.prototype.closeAttribute = function(att, options, level) {}; + + return XMLWriterBase; + + })(); + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/index.js b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/index.js new file mode 100644 index 00000000..b1ed2636 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/lib/index.js @@ -0,0 +1,65 @@ +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref; + + ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction; + + XMLDOMImplementation = require('./XMLDOMImplementation'); + + XMLDocument = require('./XMLDocument'); + + XMLDocumentCB = require('./XMLDocumentCB'); + + XMLStringWriter = require('./XMLStringWriter'); + + XMLStreamWriter = require('./XMLStreamWriter'); + + NodeType = require('./NodeType'); + + WriterState = require('./WriterState'); + + module.exports.create = function(name, xmldec, doctype, options) { + var doc, root; + if (name == null) { + throw new Error("Root element needs a name."); + } + options = assign({}, xmldec, doctype, options); + doc = new XMLDocument(options); + root = doc.element(name); + if (!options.headless) { + doc.declaration(options); + if ((options.pubID != null) || (options.sysID != null)) { + doc.dtd(options); + } + } + return root; + }; + + module.exports.begin = function(options, onData, onEnd) { + var ref1; + if (isFunction(options)) { + ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1]; + options = {}; + } + if (onData) { + return new XMLDocumentCB(options, onData, onEnd); + } else { + return new XMLDocument(options); + } + }; + + module.exports.stringWriter = function(options) { + return new XMLStringWriter(options); + }; + + module.exports.streamWriter = function(stream, options) { + return new XMLStreamWriter(stream, options); + }; + + module.exports.implementation = new XMLDOMImplementation(); + + module.exports.nodeType = NodeType; + + module.exports.writerState = WriterState; + +}).call(this); diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/package.json b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/package.json new file mode 100644 index 00000000..512cd977 --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/package.json @@ -0,0 +1,39 @@ +{ + "name": "xmlbuilder", + "version": "11.0.1", + "keywords": [ + "xml", + "xmlbuilder" + ], + "homepage": "http://github.com/oozcitak/xmlbuilder-js", + "description": "An XML builder for node.js", + "author": "Ozgur Ozcitak ", + "contributors": [], + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/oozcitak/xmlbuilder-js.git" + }, + "bugs": { + "url": "http://github.com/oozcitak/xmlbuilder-js/issues" + }, + "main": "./lib/index", + "typings": "./typings/index.d.ts", + "engines": { + "node": ">=4.0" + }, + "dependencies": {}, + "devDependencies": { + "coffeescript": "1.*", + "mocha": "*", + "coffee-coverage": "2.*", + "istanbul": "*", + "coveralls": "*", + "xpath": "*" + }, + "scripts": { + "prepublishOnly": "coffee -co lib src", + "postpublish": "rm -rf lib", + "test": "mocha \"test/**/*.coffee\" && istanbul report text lcov" + } +} diff --git a/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/typings/index.d.ts b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/typings/index.d.ts new file mode 100644 index 00000000..3e0e5b0a --- /dev/null +++ b/node_modules/parse-bmfont-xml/node_modules/xmlbuilder/typings/index.d.ts @@ -0,0 +1,153 @@ +// Type definitions for xmlbuilder +// Project: https://github.com/oozcitak/xmlbuilder-js +// Definitions by: Wallymathieu +// : GaikwadPratik +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = xmlbuilder; + +declare namespace xmlbuilder { + + class XMLDocType { + clone(): XMLDocType; + element(name: string, value?: Object): XMLDocType; + attList(elementName: string, attributeName: string, attributeType: string, defaultValueType?: string, defaultValue?: any): XMLDocType; + entity(name: string, value: any): XMLDocType; + pEntity(name: string, value: any): XMLDocType; + notation(name: string, value: any): XMLDocType; + cdata(value: string): XMLDocType; + comment(value: string): XMLDocType; + instruction(target: string, value: any): XMLDocType; + root(): XMLDocType; + document(): any; + toString(options?: XMLToStringOptions, level?: Number): string; + + ele(name: string, value?: Object): XMLDocType; + att(elementName: string, attributeName: string, attributeType: string, defaultValueType?: string, defaultValue?: any): XMLDocType; + ent(name: string, value: any): XMLDocType; + pent(name: string, value: any): XMLDocType; + not(name: string, value: any): XMLDocType; + dat(value: string): XMLDocType; + com(value: string): XMLDocType; + ins(target: string, value: any): XMLDocType; + up(): XMLDocType; + doc(): any; + } + + class XMLElementOrXMLNode { + // XMLElement: + clone(): XMLElementOrXMLNode; + attribute(name: any, value?: any): XMLElementOrXMLNode; + att(name: any, value?: any): XMLElementOrXMLNode; + removeAttribute(name: string): XMLElementOrXMLNode; + instruction(target: string, value: any): XMLElementOrXMLNode; + instruction(array: Array): XMLElementOrXMLNode; + instruction(obj: Object): XMLElementOrXMLNode; + ins(target: string, value: any): XMLElementOrXMLNode; + ins(array: Array): XMLElementOrXMLNode; + ins(obj: Object): XMLElementOrXMLNode; + a(name: any, value?: any): XMLElementOrXMLNode; + i(target: string, value: any): XMLElementOrXMLNode; + i(array: Array): XMLElementOrXMLNode; + i(obj: Object): XMLElementOrXMLNode; + toString(options?: XMLToStringOptions, level?: Number): string; + // XMLNode: + element(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + ele(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + insertBefore(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + insertAfter(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + remove(): XMLElementOrXMLNode; + node(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + text(value: string): XMLElementOrXMLNode; + cdata(value: string): XMLElementOrXMLNode; + comment(value: string): XMLElementOrXMLNode; + raw(value: string): XMLElementOrXMLNode; + declaration(version: string, encoding: string, standalone: boolean): XMLElementOrXMLNode; + doctype(pubID: string, sysID: string): XMLDocType; + up(): XMLElementOrXMLNode; + importDocument(input: XMLElementOrXMLNode): XMLElementOrXMLNode; + root(): XMLElementOrXMLNode; + document(): any; + end(options?: XMLEndOptions): string; + prev(): XMLElementOrXMLNode; + next(): XMLElementOrXMLNode; + nod(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + txt(value: string): XMLElementOrXMLNode; + dat(value: string): XMLElementOrXMLNode; + com(value: string): XMLElementOrXMLNode; + doc(): XMLElementOrXMLNode; + dec(version: string, encoding: string, standalone: boolean): XMLElementOrXMLNode; + dtd(pubID: string, sysID: string): XMLDocType; + e(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + n(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; + t(value: string): XMLElementOrXMLNode; + d(value: string): XMLElementOrXMLNode; + c(value: string): XMLElementOrXMLNode; + r(value: string): XMLElementOrXMLNode; + u(): XMLElementOrXMLNode; + } + + interface XMLDec { + version?: string; + encoding?: string; + standalone?: boolean; + } + + interface XMLDtd { + pubID?: string; + sysID?: string; + } + + interface XMLStringifier { + [x: string]: ((v: any) => string) | string; + } + + interface XMLWriter { + [x: string]: ((e: XMLElementOrXMLNode, options: WriterOptions, level?: number) => void); + } + + interface XMLCreateOptions { + headless?: boolean; + keepNullNodes?: boolean; + keepNullAttributes?: boolean; + ignoreDecorators?: boolean; + separateArrayItems?: boolean; + noDoubleEncoding?: boolean; + stringify?: XMLStringifier; + } + + interface XMLToStringOptions { + pretty?: boolean; + indent?: string; + offset?: number; + newline?: string; + allowEmpty?: boolean; + spacebeforeslash?: string; + } + + interface XMLEndOptions extends XMLToStringOptions { + writer?: XMLWriter; + } + + interface WriterOptions { + pretty?: boolean; + indent?: string; + newline?: string; + offset?: number; + allowEmpty?: boolean; + dontPrettyTextNodes?: boolean; + spaceBeforeSlash?: string | boolean; + user? :any; + state?: WriterState; + } + + enum WriterState { + None = 0, + OpenTag = 1, + InsideTag = 2, + CloseTag = 3 + } + + function create(nameOrObjSpec: string | { [name: string]: Object }, xmldecOrOptions?: XMLDec | XMLCreateOptions, doctypeOrOptions?: XMLDtd | XMLCreateOptions, options?: XMLCreateOptions): XMLElementOrXMLNode; + function begin(): XMLElementOrXMLNode; +} \ No newline at end of file diff --git a/node_modules/parse-bmfont-xml/package.json b/node_modules/parse-bmfont-xml/package.json new file mode 100644 index 00000000..2668e900 --- /dev/null +++ b/node_modules/parse-bmfont-xml/package.json @@ -0,0 +1,56 @@ +{ + "name": "parse-bmfont-xml", + "version": "1.1.6", + "description": "parses XML BMFont files into a JavaScript object", + "main": "lib/index.js", + "browser": "lib/browser.js", + "license": "MIT", + "author": { + "name": "Matt DesLauriers", + "email": "dave.des@gmail.com", + "url": "https://github.com/mattdesl" + }, + "dependencies": { + "xml-parse-from-string": "^1.0.0", + "xml2js": "^0.5.0" + }, + "devDependencies": { + "brfs": "^1.4.0", + "browserify": "^9.0.3", + "faucet": "0.0.1", + "tape": "^3.5.0", + "testling": "^1.7.1", + "xhr": "^2.0.1" + }, + "scripts": { + "test-browser": "browserify test/test-browser.js -t brfs | testling | faucet", + "test-node": "node test/test.js | faucet", + "test": "npm run test-node && npm run test-browser" + }, + "keywords": [ + "xml", + "parse", + "convert", + "bmfont", + "bm", + "bitmap", + "font", + "bitmaps", + "angel", + "angelcode", + "code", + "text", + "gl", + "sprite", + "sprites", + "stackgl" + ], + "repository": { + "type": "git", + "url": "git://github.com/mattdesl/parse-bmfont-xml.git" + }, + "homepage": "https://github.com/mattdesl/parse-bmfont-xml", + "bugs": { + "url": "https://github.com/mattdesl/parse-bmfont-xml/issues" + } +} diff --git a/node_modules/parse-headers/.travis.yml b/node_modules/parse-headers/.travis.yml new file mode 100644 index 00000000..851fb952 --- /dev/null +++ b/node_modules/parse-headers/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: +- node diff --git a/node_modules/parse-headers/LICENCE b/node_modules/parse-headers/LICENCE new file mode 100644 index 00000000..6ca87bb1 --- /dev/null +++ b/node_modules/parse-headers/LICENCE @@ -0,0 +1,21 @@ +Copyright (c) 2014 David Björklund + +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/parse-headers/example.js b/node_modules/parse-headers/example.js new file mode 100644 index 00000000..1b028637 --- /dev/null +++ b/node_modules/parse-headers/example.js @@ -0,0 +1,11 @@ +var parse = require('./parse-headers') + + , headers = [ + 'Date: Sun, 17 Aug 2014 16:24:52 GMT' + , 'Content-Type: text/html; charset=utf-8' + , 'Transfer-Encoding: chunked' + , 'X-Custom-Header: beep' + , 'X-Custom-Header: boop' + ].join('\n') + +console.log(parse(headers)) \ No newline at end of file diff --git a/node_modules/parse-headers/index.d.ts b/node_modules/parse-headers/index.d.ts new file mode 100644 index 00000000..33566e50 --- /dev/null +++ b/node_modules/parse-headers/index.d.ts @@ -0,0 +1,4 @@ +declare module 'parse-headers' { + function parseHeaders(headers: string): Record + export = parseHeaders +} diff --git a/node_modules/parse-headers/package.json b/node_modules/parse-headers/package.json new file mode 100644 index 00000000..3c187d86 --- /dev/null +++ b/node_modules/parse-headers/package.json @@ -0,0 +1,28 @@ +{ + "name": "parse-headers", + "version": "2.0.6", + "description": "Parse http headers, works with browserify/xhr", + "main": "parse-headers.js", + "types": "index.d.ts", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/kesla/parse-headers.git" + }, + "keywords": [ + "http", + "headers" + ], + "author": "David Björklund ", + "license": "MIT", + "bugs": { + "url": "https://github.com/kesla/parse-headers/issues" + }, + "homepage": "https://github.com/kesla/parse-headers", + "devDependencies": { + "tape": "^4.10.1" + }, + "dependencies": {} +} diff --git a/node_modules/parse-headers/parse-headers.js b/node_modules/parse-headers/parse-headers.js new file mode 100644 index 00000000..707f3262 --- /dev/null +++ b/node_modules/parse-headers/parse-headers.js @@ -0,0 +1,32 @@ +var trim = function(string) { + return string.replace(/^\s+|\s+$/g, ''); +} + , isArray = function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + } + +module.exports = function (headers) { + if (!headers) + return {} + + var result = Object.create(null); + + var headersArr = trim(headers).split('\n') + + for (var i = 0; i < headersArr.length; i++) { + var row = headersArr[i] + var index = row.indexOf(':') + , key = trim(row.slice(0, index)).toLowerCase() + , value = trim(row.slice(index + 1)) + + if (typeof(result[key]) === 'undefined') { + result[key] = value + } else if (isArray(result[key])) { + result[key].push(value) + } else { + result[key] = [ result[key], value ] + } + } + + return result +} diff --git a/node_modules/parse-headers/readme.md b/node_modules/parse-headers/readme.md new file mode 100644 index 00000000..7c402476 --- /dev/null +++ b/node_modules/parse-headers/readme.md @@ -0,0 +1,70 @@ +# parse-headers[![build status](https://secure.travis-ci.org/kesla/parse-headers.svg)](http://travis-ci.org/kesla/parse-headers) + +Parse http headers, works with browserify/xhr + +[![NPM](https://nodei.co/npm/parse-headers.png?downloads&stars)](https://nodei.co/npm/parse-headers/) + +[![NPM](https://nodei.co/npm-dl/parse-headers.png)](https://nodei.co/npm/parse-headers/) + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/kesla-xhr-headers.svg)](https://saucelabs.com/u/kesla-xhr-headers) + +## Installation + +``` +npm install parse-headers +``` + +## Example + +### Input + +```javascript +var parse = require('./parse-headers') + + , headers = [ + 'Date: Sun, 17 Aug 2014 16:24:52 GMT' + , 'Content-Type: text/html; charset=utf-8' + , 'Transfer-Encoding: chunked' + , 'X-Custom-Header: beep' + , 'X-Custom-Header: boop' + ].join('\n') + +console.log(parse(headers)) +``` + +### Output + +``` +{ date: 'Sun, 17 Aug 2014 16:24:52 GMT', + 'content-type': 'text/html; charset=utf-8', + 'transfer-encoding': 'chunked', + 'x-custom-header': [ 'beep', 'boop' ] } +``` + +## Kudos + +Looked at https://github.com/watson/http-headers before creating this. + +## Licence + +Copyright (c) 2014 David Björklund + +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/parse-headers/test.js b/node_modules/parse-headers/test.js new file mode 100644 index 00000000..b324cedf --- /dev/null +++ b/node_modules/parse-headers/test.js @@ -0,0 +1,70 @@ +var test = require('tape') + , parse = require('./parse-headers') + + , headers1 = [ + '' + , 'Date: Sun, 17 Aug 2014 16:24:52 GMT' + , 'Content-Type: text/html; charset=utf-8' + , 'Transfer-Encoding: chunked' + , '' + ] + , headers2 = [ + '' + , 'Date: Sun, 17 Aug 2014 16:24:52 GMT' + , 'Content-Type: text/html; charset=utf-8' + , 'Transfer-Encoding: chunked' + , 'Set-Cookie: Foo' + , 'set-Cookie: bar' + , 'set-cookie: bong' + ] + +test('sanity check', function (t) { + + t.deepEqual(parse(), {}) + t.deepEqual(parse(''), {}) + t.end() +}) + +test('simple', function (t) { + t.deepEqual( + parse(headers1.join('\r\n')) + , { + date: 'Sun, 17 Aug 2014 16:24:52 GMT' + , 'content-type': 'text/html; charset=utf-8' + , 'transfer-encoding': 'chunked' + } + ) + t.deepEqual( + parse(headers1.join('\n')) + , { + date: 'Sun, 17 Aug 2014 16:24:52 GMT' + , 'content-type': 'text/html; charset=utf-8' + , 'transfer-encoding': 'chunked' + } + ) + + t.end() +}) + +test('duplicate keys', function (t) { + t.deepEqual( + parse(headers2.join('\r\n')) + , { + date: 'Sun, 17 Aug 2014 16:24:52 GMT' + , 'content-type': 'text/html; charset=utf-8' + , 'transfer-encoding': 'chunked' + , 'set-cookie': [ 'Foo', 'bar', 'bong' ] + } + ) + t.deepEqual( + parse(headers2.join('\n')) + , { + date: 'Sun, 17 Aug 2014 16:24:52 GMT' + , 'content-type': 'text/html; charset=utf-8' + , 'transfer-encoding': 'chunked' + , 'set-cookie': [ 'Foo', 'bar', 'bong' ] + } + ) + + t.end() +}) \ No newline at end of file diff --git a/node_modules/peek-readable/LICENSE b/node_modules/peek-readable/LICENSE new file mode 100644 index 00000000..9ba5f032 --- /dev/null +++ b/node_modules/peek-readable/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2010-2017 Borewit + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/peek-readable/README.md b/node_modules/peek-readable/README.md new file mode 100644 index 00000000..72221e1e --- /dev/null +++ b/node_modules/peek-readable/README.md @@ -0,0 +1,93 @@ +![Node.js CI](https://github.com/Borewit/peek-readable/workflows/Node.js%20CI/badge.svg) +[![NPM version](https://badge.fury.io/js/peek-readable.svg)](https://npmjs.org/package/peek-readable) +[![npm downloads](http://img.shields.io/npm/dm/peek-readable.svg)](https://npmcharts.com/compare/peek-readable?start=600&interval=30) +[![Coverage Status](https://coveralls.io/repos/github/Borewit/peek-readable/badge.svg?branch=master)](https://coveralls.io/github/Borewit/peek-readable?branch=master) +[![Codacy Badge](https://app.codacy.com/project/badge/Grade/d4b511481b3a4634b6ca5c0724407eb9)](https://www.codacy.com/gh/Borewit/peek-readable/dashboard?utm_source=github.com&utm_medium=referral&utm_content=Borewit/peek-readable&utm_campaign=Badge_Grade) +[![Total alerts](https://img.shields.io/lgtm/alerts/g/Borewit/peek-readable.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/peek-readable/alerts/) +[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Borewit/peek-readable.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/peek-readable/context:javascript) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/peek-readable/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/peek-readable?targetFile=package.json) + +# peek-readable + +A promise based asynchronous stream reader, which makes reading from a stream easy. + +Allows to read and peek from a [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams) + +Note that [peek-readable](https://github.com/Borewit/peek-readable) was formally released as [then-read-stream](https://github.com/Borewit/peek-readable). + +## Usage + +### Installation + +```shell script +npm install --save peek-readable +``` + +The `peek-readable` contains one class: `StreamReader`, which reads from a [stream.Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +### Compatibility + +NPM module is compliant with [ECMAScript 2018 (ES9)](https://en.wikipedia.org/wiki/ECMAScript#9th_Edition_%E2%80%93_ECMAScript_2018). + +## Examples + +In the following example we read the first 16 bytes from a stream and store them in our buffer. +Source code of examples can be found [here](test/examples.ts). + +```js +const fs = require('fs'); +const { StreamReader } = require('peek-readable'); + +(async () => { + const readable = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg'); + const streamReader = new StreamReader(readable); + const uint8Array = new Uint8Array(16); + const bytesRead = await streamReader.read(uint8Array, 0, 16);; + // buffer contains 16 bytes, if the end-of-stream has not been reached +})(); +``` + +End-of-stream detection: +```js +(async () => { + + const fileReadStream = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg'); + const streamReader = new StreamReader(fileReadStream); + const buffer = Buffer.alloc(16); // or use: new Uint8Array(16); + + try { + await streamReader.read(buffer, 0, 16); + // buffer contains 16 bytes, if the end-of-stream has not been reached + } catch(error) { + if (error instanceof EndOfStreamError) { + console.log('End-of-stream reached'); + } + } +})(); +``` + +With peek you can read ahead: +```js +const fs = require('fs'); +const { StreamReader } = require('peek-readable'); + +const fileReadStream = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg'); +const streamReader = new StreamReader(fileReadStream); +const buffer = Buffer.alloc(20); + +(async () => { + let bytesRead = await streamReader.peek(buffer, 0, 3); + if (bytesRead === 3 && buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) { + console.log('This is a JPEG file'); + } else { + throw Error('Expected a JPEG file'); + } + + bytesRead = await streamReader.read(buffer, 0, 20); // Read JPEG header + if (bytesRead === 20) { + console.log('Got the JPEG header'); + } else { + throw Error('Failed to read JPEG header'); + } +})(); +``` diff --git a/node_modules/peek-readable/lib/Deferred.d.ts b/node_modules/peek-readable/lib/Deferred.d.ts new file mode 100644 index 00000000..b7294492 --- /dev/null +++ b/node_modules/peek-readable/lib/Deferred.d.ts @@ -0,0 +1,6 @@ +export declare class Deferred { + promise: Promise; + resolve: (value: T) => void; + reject: (reason: any) => void; + constructor(); +} diff --git a/node_modules/peek-readable/lib/Deferred.js b/node_modules/peek-readable/lib/Deferred.js new file mode 100644 index 00000000..84c42b31 --- /dev/null +++ b/node_modules/peek-readable/lib/Deferred.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Deferred = void 0; +class Deferred { + constructor() { + this.resolve = () => null; + this.reject = () => null; + this.promise = new Promise((resolve, reject) => { + this.reject = reject; + this.resolve = resolve; + }); + } +} +exports.Deferred = Deferred; diff --git a/node_modules/peek-readable/lib/EndOfFileStream.d.ts b/node_modules/peek-readable/lib/EndOfFileStream.d.ts new file mode 100644 index 00000000..1081cb06 --- /dev/null +++ b/node_modules/peek-readable/lib/EndOfFileStream.d.ts @@ -0,0 +1,7 @@ +export declare const defaultMessages = "End-Of-Stream"; +/** + * Thrown on read operation of the end of file or stream has been reached + */ +export declare class EndOfStreamError extends Error { + constructor(); +} diff --git a/node_modules/peek-readable/lib/EndOfFileStream.js b/node_modules/peek-readable/lib/EndOfFileStream.js new file mode 100644 index 00000000..6ae832ed --- /dev/null +++ b/node_modules/peek-readable/lib/EndOfFileStream.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EndOfStreamError = exports.defaultMessages = void 0; +exports.defaultMessages = 'End-Of-Stream'; +/** + * Thrown on read operation of the end of file or stream has been reached + */ +class EndOfStreamError extends Error { + constructor() { + super(exports.defaultMessages); + } +} +exports.EndOfStreamError = EndOfStreamError; diff --git a/node_modules/peek-readable/lib/StreamReader.d.ts b/node_modules/peek-readable/lib/StreamReader.d.ts new file mode 100644 index 00000000..114c9689 --- /dev/null +++ b/node_modules/peek-readable/lib/StreamReader.d.ts @@ -0,0 +1,47 @@ +/// +import { Readable } from 'stream'; +export { EndOfStreamError } from './EndOfFileStream'; +export declare class StreamReader { + private s; + /** + * Deferred used for postponed read request (as not data is yet available to read) + */ + private deferred; + private endOfStream; + /** + * Store peeked data + * @type {Array} + */ + private peekQueue; + constructor(s: Readable); + /** + * Read ahead (peek) from stream. Subsequent read or peeks will return the same data + * @param uint8Array - Uint8Array (or Buffer) to store data read from stream in + * @param offset - Offset target + * @param length - Number of bytes to read + * @returns Number of bytes peeked + */ + peek(uint8Array: Uint8Array, offset: number, length: number): Promise; + /** + * Read chunk from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param offset - Offset target + * @param length - Number of bytes to read + * @returns Number of bytes read + */ + read(buffer: Uint8Array, offset: number, length: number): Promise; + /** + * Read chunk from stream + * @param buffer Target Uint8Array (or Buffer) to store data read from stream in + * @param offset Offset target + * @param length Number of bytes to read + * @returns Number of bytes read + */ + private readFromStream; + /** + * Process deferred read request + * @param request Deferred read request + */ + private readDeferred; + private reject; +} diff --git a/node_modules/peek-readable/lib/StreamReader.js b/node_modules/peek-readable/lib/StreamReader.js new file mode 100644 index 00000000..1a812624 --- /dev/null +++ b/node_modules/peek-readable/lib/StreamReader.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamReader = exports.EndOfStreamError = void 0; +const EndOfFileStream_1 = require("./EndOfFileStream"); +const Deferred_1 = require("./Deferred"); +var EndOfFileStream_2 = require("./EndOfFileStream"); +Object.defineProperty(exports, "EndOfStreamError", { enumerable: true, get: function () { return EndOfFileStream_2.EndOfStreamError; } }); +const maxStreamReadSize = 1 * 1024 * 1024; // Maximum request length on read-stream operation +class StreamReader { + constructor(s) { + this.s = s; + /** + * Deferred used for postponed read request (as not data is yet available to read) + */ + this.deferred = null; + this.endOfStream = false; + /** + * Store peeked data + * @type {Array} + */ + this.peekQueue = []; + if (!s.read || !s.once) { + throw new Error('Expected an instance of stream.Readable'); + } + this.s.once('end', () => this.reject(new EndOfFileStream_1.EndOfStreamError())); + this.s.once('error', err => this.reject(err)); + this.s.once('close', () => this.reject(new Error('Stream closed'))); + } + /** + * Read ahead (peek) from stream. Subsequent read or peeks will return the same data + * @param uint8Array - Uint8Array (or Buffer) to store data read from stream in + * @param offset - Offset target + * @param length - Number of bytes to read + * @returns Number of bytes peeked + */ + async peek(uint8Array, offset, length) { + const bytesRead = await this.read(uint8Array, offset, length); + this.peekQueue.push(uint8Array.subarray(offset, offset + bytesRead)); // Put read data back to peek buffer + return bytesRead; + } + /** + * Read chunk from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param offset - Offset target + * @param length - Number of bytes to read + * @returns Number of bytes read + */ + async read(buffer, offset, length) { + if (length === 0) { + return 0; + } + if (this.peekQueue.length === 0 && this.endOfStream) { + throw new EndOfFileStream_1.EndOfStreamError(); + } + let remaining = length; + let bytesRead = 0; + // consume peeked data first + while (this.peekQueue.length > 0 && remaining > 0) { + const peekData = this.peekQueue.pop(); // Front of queue + if (!peekData) + throw new Error('peekData should be defined'); + const lenCopy = Math.min(peekData.length, remaining); + buffer.set(peekData.subarray(0, lenCopy), offset + bytesRead); + bytesRead += lenCopy; + remaining -= lenCopy; + if (lenCopy < peekData.length) { + // remainder back to queue + this.peekQueue.push(peekData.subarray(lenCopy)); + } + } + // continue reading from stream if required + while (remaining > 0 && !this.endOfStream) { + const reqLen = Math.min(remaining, maxStreamReadSize); + const chunkLen = await this.readFromStream(buffer, offset + bytesRead, reqLen); + bytesRead += chunkLen; + if (chunkLen < reqLen) + break; + remaining -= chunkLen; + } + return bytesRead; + } + /** + * Read chunk from stream + * @param buffer Target Uint8Array (or Buffer) to store data read from stream in + * @param offset Offset target + * @param length Number of bytes to read + * @returns Number of bytes read + */ + async readFromStream(buffer, offset, length) { + const readBuffer = this.s.read(length); + if (readBuffer) { + buffer.set(readBuffer, offset); + return readBuffer.length; + } + else { + const request = { + buffer, + offset, + length, + deferred: new Deferred_1.Deferred() + }; + this.deferred = request.deferred; + this.s.once('readable', () => { + this.readDeferred(request); + }); + return request.deferred.promise; + } + } + /** + * Process deferred read request + * @param request Deferred read request + */ + readDeferred(request) { + const readBuffer = this.s.read(request.length); + if (readBuffer) { + request.buffer.set(readBuffer, request.offset); + request.deferred.resolve(readBuffer.length); + this.deferred = null; + } + else { + this.s.once('readable', () => { + this.readDeferred(request); + }); + } + } + reject(err) { + this.endOfStream = true; + if (this.deferred) { + this.deferred.reject(err); + this.deferred = null; + } + } +} +exports.StreamReader = StreamReader; diff --git a/node_modules/peek-readable/lib/index.d.ts b/node_modules/peek-readable/lib/index.d.ts new file mode 100644 index 00000000..764e4fae --- /dev/null +++ b/node_modules/peek-readable/lib/index.d.ts @@ -0,0 +1,2 @@ +export { EndOfStreamError } from './EndOfFileStream'; +export { StreamReader } from './StreamReader'; diff --git a/node_modules/peek-readable/lib/index.js b/node_modules/peek-readable/lib/index.js new file mode 100644 index 00000000..34cd7654 --- /dev/null +++ b/node_modules/peek-readable/lib/index.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamReader = exports.EndOfStreamError = void 0; +var EndOfFileStream_1 = require("./EndOfFileStream"); +Object.defineProperty(exports, "EndOfStreamError", { enumerable: true, get: function () { return EndOfFileStream_1.EndOfStreamError; } }); +var StreamReader_1 = require("./StreamReader"); +Object.defineProperty(exports, "StreamReader", { enumerable: true, get: function () { return StreamReader_1.StreamReader; } }); diff --git a/node_modules/peek-readable/package.json b/node_modules/peek-readable/package.json new file mode 100644 index 00000000..d460956b --- /dev/null +++ b/node_modules/peek-readable/package.json @@ -0,0 +1,87 @@ +{ + "name": "peek-readable", + "version": "4.1.0", + "description": "Read and peek from a readable stream", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "scripts": { + "clean": "del-cli lib/**/*.js lib/**/*.js.map lib/**/*.d.ts test/**/*.js test/**/*.js.map coverage .nyc_output", + "build": "npm run clean && npm run compile", + "compile-src": "tsc -p lib", + "compile-test": "tsc -p test", + "compile": "npm run compile-src && yarn run compile-test", + "eslint": "eslint lib test --ext .ts --ignore-pattern *.d.ts", + "lint-md": "remark -u preset-lint-recommended .", + "lint": "npm run lint-md && npm run eslint", + "test": "mocha --require ts-node/register --require source-map-support/register --full-trace test/*.ts", + "test-coverage": "nyc npm run test", + "send-coveralls": "nyc report --reporter=text-lcov | coveralls", + "start": "npm run compile && npm run lint && npm run cover-test" + }, + "engines": { + "node": ">=8" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Borewit/peek-readable" + }, + "license": "MIT", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "bugs": { + "url": "https://github.com/Borewit/peek-readable/issues" + }, + "files": [ + "lib/**/*.js", + "lib/**/*.d.ts" + ], + "devDependencies": { + "@types/chai": "^4.3.0", + "@types/mocha": "^9.1.0", + "@types/node": "^17.0.0", + "@typescript-eslint/eslint-plugin": "^4.33.0", + "@typescript-eslint/parser": "^4.33.0", + "add": "^2.0.6", + "chai": "^4.3.6", + "coveralls": "^3.1.1", + "del-cli": "^4.0.1", + "eslint": "^7.32.0", + "eslint-config-prettier": "^8.3.0", + "eslint-import-resolver-typescript": "^2.5.0", + "eslint-plugin-import": "^2.25.4", + "eslint-plugin-jsdoc": "^37.7.1", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-unicorn": "^40.1.0", + "mocha": "^9.2.0", + "nyc": "^15.1.0", + "remark-cli": "^10.0.1", + "remark-preset-lint-recommended": "^6.1.2", + "ts-node": "^10.4.0", + "typescript": "^4.5.5" + }, + "keywords": [ + "readable", + "buffer", + "stream", + "read" + ], + "nyc": { + "check-coverage": true, + "extension": [ + ".ts" + ], + "sourceMap": true, + "instrument": true, + "reporter": [ + "lcov", + "text" + ], + "report-dir": "coverage" + } +} diff --git a/node_modules/phin/LICENSE b/node_modules/phin/LICENSE new file mode 100644 index 00000000..a8aee327 --- /dev/null +++ b/node_modules/phin/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Ethan Davis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/phin/README.md b/node_modules/phin/README.md new file mode 100644 index 00000000..11c734e1 --- /dev/null +++ b/node_modules/phin/README.md @@ -0,0 +1,129 @@ +

phin logo

+ +--- + +> The lightweight Node.js HTTP client + +[Full documentation](https://ethanent.github.io/phin/global.html) | [GitHub](https://github.com/ethanent/phin) | [NPM](https://www.npmjs.com/package/phin) + +## Deprecated + +This package is deprecated and should not be used. Please see [#91](https://github.com/ethanent/phin/issues/91) for more information. + +## Simple Usage + +```javascript +const p = require('phin') + +const res = await p('https://ethanent.me') + +console.log(res.body) +``` + +Note that the above should be in an async context! Phin also provides an unpromisified version of the library. + + +## Install + +``` +npm install phin +``` + + +## Why Phin? + +Phin is relied upon by important projects and large companies. The hundreds of contributors at [Less](https://github.com/less/less.js), for example, depend on Phin as part of their development process. + +Also, Phin is very lightweight. To compare to other libraries, see [Phin vs. the Competition](https://github.com/ethanent/phin/blob/master/README.md#phin-vs-the-competition). + +## Quick Demos + +Simple POST: + +```js +await p({ + url: 'https://ethanent.me', + method: 'POST', + data: { + hey: 'hi' + } +}) +``` + +### Unpromisified Usage + +```js +const p = require('phin').unpromisified + +p('https://ethanent.me', (err, res) => { + if (!err) console.log(res.body) +}) +``` + +Simple parsing of JSON: + +```js +// (In async function in this case.) + +const res = await p({ + 'url': 'https://ethanent.me/name', + 'parse': 'json' +}) + +console.log(res.body.first) +``` + +### Default Options + +```js +const ppostjson = p.defaults({ + 'method': 'POST', + 'parse': 'json', + 'timeout': 2000 +}) + +// In async function... + +const res = await ppostjson('https://ethanent.me/somejson') +// ^ An options object could also be used here to set other options. + +// Do things with res.body? +``` + +### Custom Core HTTP Options + +Phin allows you to set [core HTTP options](https://nodejs.org/api/http.html#http_http_request_url_options_callback). + +```js +await p({ + 'url': 'https://ethanent.me/name', + 'core': { + 'agent': myAgent // Assuming you'd already created myAgent earlier. + } +}) +``` + + +## Full Documentation + +There's a lot more which can be done with the Phin library. + +See [the Phin documentation](https://ethanent.github.io/phin/global.html). + + +## Phin vs. the Competition + +Phin is a very lightweight library, yet it contains all of the common HTTP client features included in competing libraries! + +Here's a size comparison table: + +Package | Size +--- | --- +request | [![request package size](https://packagephobia.now.sh/badge?p=request)](https://packagephobia.now.sh/result?p=request) +superagent | [![superagent package size](https://packagephobia.now.sh/badge?p=superagent)](https://packagephobia.now.sh/result?p=superagent) +got | [![got package size](https://packagephobia.now.sh/badge?p=got)](https://packagephobia.now.sh/result?p=got) +axios | [![axios package size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) +isomorphic-fetch | [![isomorphic-fetch package size](https://packagephobia.now.sh/badge?p=isomorphic-fetch)](https://packagephobia.now.sh/result?p=isomorphic-fetch) +r2 | [![r2 package size](https://packagephobia.now.sh/badge?p=r2)](https://packagephobia.now.sh/result?p=r2) +node-fetch | [![node-fetch package size](https://packagephobia.now.sh/badge?p=node-fetch)](https://packagephobia.now.sh/result?p=node-fetch) +phin | [![phin package size](https://packagephobia.now.sh/badge?p=phin)](https://packagephobia.now.sh/result?p=phin) diff --git a/node_modules/phin/lib/phin.js b/node_modules/phin/lib/phin.js new file mode 100644 index 00000000..ae9cbe3e --- /dev/null +++ b/node_modules/phin/lib/phin.js @@ -0,0 +1,121 @@ +const {URL} = require('url') + +const centra = require('centra') + +const unspecifiedFollowRedirectsDefault = 20 + +/** +* phin options object. phin also supports all options from http.request(options, callback) by passing them on to this method (or similar). +* @typedef {Object} phinOptions +* @property {string} url - URL to request (autodetect infers from this URL) +* @property {string} [method=GET] - Request method ('GET', 'POST', etc.) +* @property {string|Buffer|object} [data] - Data to send as request body (phin may attempt to convert this data to a string if it isn't already) +* @property {Object} [form] - Object to send as form data (sets 'Content-Type' and 'Content-Length' headers, as well as request body) (overwrites 'data' option if present) +* @property {Object} [headers={}] - Request headers +* @property {Object} [core={}] - Custom core HTTP options +* @property {string} [parse=none] - Response parsing. Errors will be given if the response can't be parsed. 'none' returns body as a `Buffer`, 'json' attempts to parse the body as JSON, and 'string' attempts to parse the body as a string +* @property {boolean} [followRedirects=false] - Enable HTTP redirect following +* @property {boolean} [stream=false] - Enable streaming of response. (Removes body property) +* @property {boolean} [compression=false] - Enable compression for request +* @property {?number} [timeout=null] - Request timeout in milliseconds +* @property {string} [hostname=autodetect] - URL hostname +* @property {Number} [port=autodetect] - URL port +* @property {string} [path=autodetect] - URL path +*/ + +/** +* Response data +* @callback phinResponseCallback +* @param {?(Error|string)} error - Error if any occurred in request, otherwise null. +* @param {?http.serverResponse} phinResponse - phin response object. Like http.ServerResponse but has a body property containing response body, unless stream. If stream option is enabled, a stream property will be provided to callback with a readable stream. +*/ + +/** +* Sends an HTTP request +* @param {phinOptions|string} options - phin options object (or string for auto-detection) +* @returns {Promise} - phin-adapted response object +*/ +const phin = async (opts) => { + if (typeof(opts) !== 'string') { + if (!opts.hasOwnProperty('url')) { + throw new Error('Missing url option from options for request method.') + } + } + + const req = centra(typeof opts === 'object' ? opts.url : opts, opts.method || 'GET') + + if (opts.headers) req.header(opts.headers) + if (opts.stream) req.stream() + if (opts.timeout) req.timeout(opts.timeout) + if (opts.data) req.body(opts.data) + if (opts.form) req.body(opts.form, 'form') + if (opts.compression) req.compress() + + if (opts.followRedirects) { + if (opts.followRedirects === true) { + req.followRedirects(unspecifiedFollowRedirectsDefault) + } else if (typeof opts.followRedirects === 'number') { + req.followRedirects(opts.followRedirects) + } + } + + if (typeof opts.core === 'object') { + Object.keys(opts.core).forEach((optName) => { + req.option(optName, opts.core[optName]) + }) + } + + const res = await req.send() + + if (opts.stream) { + res.stream = res + + return res + } + else { + res.coreRes.body = res.body + + if (opts.parse) { + if (opts.parse === 'json') { + res.coreRes.body = await res.json() + + return res.coreRes + } + else if (opts.parse === 'string') { + res.coreRes.body = res.coreRes.body.toString() + + return res.coreRes + } + } + + return res.coreRes + } +} + +// If we're running Node.js 8+, let's promisify it + +phin.promisified = phin + +phin.unpromisified = (opts, cb) => { + phin(opts).then((data) => { + if (cb) cb(null, data) + }).catch((err) => { + if (cb) cb(err, null) + }) +} + +// Defaults + +phin.defaults = (defaultOpts) => async (opts) => { + const nops = typeof opts === 'string' ? {'url': opts} : opts + + Object.keys(defaultOpts).forEach((doK) => { + if (!nops.hasOwnProperty(doK) || nops[doK] === null) { + nops[doK] = defaultOpts[doK] + } + }) + + return await phin(nops) +} + +module.exports = phin diff --git a/node_modules/phin/package.json b/node_modules/phin/package.json new file mode 100644 index 00000000..600ebad3 --- /dev/null +++ b/node_modules/phin/package.json @@ -0,0 +1,40 @@ +{ + "name": "phin", + "version": "3.7.1", + "description": "The ultra-lightweight Node.js HTTP client", + "main": "lib/phin.js", + "types": "types.d.ts", + "scripts": { + "test": "node ./tests/test.js", + "prepublishOnly": "npm test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ethanent/phin.git" + }, + "keywords": [ + "http", + "https", + "request", + "fetch", + "ajax", + "url", + "uri" + ], + "author": "Ethan Davis", + "license": "MIT", + "bugs": { + "url": "https://github.com/ethanent/phin/issues" + }, + "homepage": "https://github.com/ethanent/phin", + "files": [ + "lib/phin.js", + "types.d.ts" + ], + "engines": { + "node": ">= 8" + }, + "dependencies": { + "centra": "^2.7.0" + } +} diff --git a/node_modules/phin/types.d.ts b/node_modules/phin/types.d.ts new file mode 100644 index 00000000..b1d9e1bb --- /dev/null +++ b/node_modules/phin/types.d.ts @@ -0,0 +1,122 @@ +// Default Options feature is not supported because it's basically impossible to write strongly-typed definitions for it. + +import * as http from 'http' +import { URL } from 'url'; + +interface IOptionsBase { + url: string | URL + method?: string + headers?: object + core?: http.ClientRequestArgs + followRedirects?: boolean + stream?: boolean + compression?: boolean + timeout?: number + hostname?: string + port?: number + path?: string +} + +declare function phin(options: + phin.IJSONResponseOptions | + phin.IWithData | + phin.IWithForm): Promise> + +declare function phin(options: + phin.IStringResponseOptions | + phin.IWithData | + phin.IWithForm): Promise + +declare function phin(options: + phin.IStreamResponseOptions | + phin.IWithData | + phin.IWithForm): Promise + +declare function phin(options: + phin.IOptions | + phin.IWithData | + phin.IWithForm | + string): Promise + +declare namespace phin { + // Form and data property has been written this way so they're mutually exclusive. + export type IWithData = T & { + data: string | Buffer | object; + } + + export type IWithForm = T & { + form: { + [index: string]: string + } + } + + export interface IJSONResponseOptions extends IOptionsBase { + parse: 'json' + } + + export interface IStringResponseOptions extends IOptionsBase { + parse: 'string'; + } + + export interface IStreamResponseOptions extends IOptionsBase { + stream: true + } + + export interface IOptions extends IOptionsBase { + parse?: 'none' + } + + export interface IJSONResponse extends http.IncomingMessage { + body: T + } + + export interface IStringResponse extends http.IncomingMessage { + body: string; + } + + export interface IStreamResponse extends http.IncomingMessage { + stream: http.IncomingMessage + } + + export interface IResponse extends http.IncomingMessage { + body: Buffer; + } + + // NOTE: Typescript cannot infer type of union callback on the consumer side + // https://github.com/Microsoft/TypeScript/pull/17819#issuecomment-363636904 + type IErrorCallback = (error: Error | string, response: null) => void + type ICallback = (error: null, response: NonNullable) => void + + export let promisified: typeof phin + + export function unpromisified( + options: + IJSONResponseOptions | + IWithData | + IWithForm, + callback: IErrorCallback | ICallback>): void + + export function unpromisified( + options: + IStringResponseOptions | + IWithData | + IWithForm, + callback: IErrorCallback | ICallback): void + + export function unpromisified( + options: + IStreamResponseOptions | + IWithData | + IWithForm, + callback: IErrorCallback | ICallback): void + + export function unpromisified( + options: + IOptions | + IWithData | + IWithForm | + string, + callback: IErrorCallback | ICallback): void +} + +export = phin diff --git a/node_modules/pixelmatch/.npmignore b/node_modules/pixelmatch/.npmignore new file mode 100644 index 00000000..7e864c79 --- /dev/null +++ b/node_modules/pixelmatch/.npmignore @@ -0,0 +1,6 @@ +*.log +node_modules +.DS_Store +.nyc_output +coverage +tmp diff --git a/node_modules/pixelmatch/.travis.yml b/node_modules/pixelmatch/.travis.yml new file mode 100644 index 00000000..bfab9632 --- /dev/null +++ b/node_modules/pixelmatch/.travis.yml @@ -0,0 +1,4 @@ +sudo: false +language: node_js +node_js: + - "0.12" diff --git a/node_modules/pixelmatch/LICENSE b/node_modules/pixelmatch/LICENSE new file mode 100644 index 00000000..8bafb577 --- /dev/null +++ b/node_modules/pixelmatch/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2015, Mapbox + +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/pixelmatch/README.md b/node_modules/pixelmatch/README.md new file mode 100644 index 00000000..cc3f92cb --- /dev/null +++ b/node_modules/pixelmatch/README.md @@ -0,0 +1,109 @@ +## pixelmatch + +[![Build Status](https://travis-ci.org/mapbox/pixelmatch.svg?branch=master)](https://travis-ci.org/mapbox/pixelmatch) +[![Coverage Status](https://coveralls.io/repos/mapbox/pixelmatch/badge.svg?branch=master&service=github)](https://coveralls.io/github/mapbox/pixelmatch?branch=master) +[![](https://img.shields.io/badge/simply-awesome-brightgreen.svg)](https://github.com/mourner/projects) + +The smallest, simplest and fastest JavaScript pixel-level image comparison library, +originally created to compare screenshots in tests. + +Features accurate **anti-aliased pixels detection** +and **perceptual color difference metrics**. + +Inspired by [Resemble.js](https://github.com/Huddle/Resemble.js) +and [Blink-diff](https://github.com/yahoo/blink-diff). +Unlike these libraries, pixelmatch is around **90 lines of code**, +has **no dependencies**, and works on **raw arrays** of image data, +so it's **blazing fast** and can be used in **any environment** (Node or browsers). + +```js +var numDiffPixels = pixelmatch(img1, img2, diff, 800, 600, {threshold: 0.1}); +``` + +Implements ideas from the following papers: + +- [Measuring perceived color difference using YIQ NTSC transmission color space in mobile applications](http://www.progmat.uaem.mx:8080/artVol2Num2/Articulo3Vol2Num2.pdf) (2010, Yuriy Kotsarenko, Fernando Ramos) +- [Anti-aliased pixel and intensity slope detector](http://www.ee.ktu.lt/journal/2009/7/25_ISSN_1392-1215_Anti-aliased%20Pxel%20and%20Intensity%20Slope%20Detector.pdf) (2009, Vytautas Vyšniauskas) + +### Example output + +| expected | actual | diff | +| --- | --- | --- | +| ![](test/fixtures/4a.png) | ![](test/fixtures/4b.png) | ![1diff](test/fixtures/4diff.png) | +| ![](test/fixtures/3a.png) | ![](test/fixtures/3b.png) | ![1diff](test/fixtures/3diff.png) | +| ![](test/fixtures/1a.png) | ![](test/fixtures/1b.png) | ![1diff](test/fixtures/1diff.png) | + +### API + +#### pixelmatch(img1, img2, output, width, height[, options]) + +- `img1`, `img2` — Image data of the images to compare (`Buffer` or `Uint8Array`). +- `output` — Image data to write the diff to, or `null` if don't need a diff image. +- `width`, `height` — Width and height of the images. Note that _all three images_ need to have the same dimensions. + +`options` is an object literal with the following properties: + +- `threshold` — Matching threshold, ranges from `0` to `1`. Smaller values make the comparison more sensitive. `0.1` by default. +- `includeAA` — If `true`, disables detecting and ignoring anti-aliased pixels. `false` by default. + +Compares two images, writes the output diff and returns the number of mismatched pixels. + +### Command line + +Pixelmatch comes with a binary that works with PNG images: + +```bash +pixelmatch image1.png image2.png output.png 0.1 +``` + +### Example usage + +#### Node.js + +```js +var fs = require('fs'), + PNG = require('pngjs').PNG, + pixelmatch = require('pixelmatch'); + +var img1 = fs.createReadStream('img1.png').pipe(new PNG()).on('parsed', doneReading), + img2 = fs.createReadStream('img2.png').pipe(new PNG()).on('parsed', doneReading), + filesRead = 0; + +function doneReading() { + if (++filesRead < 2) return; + var diff = new PNG({width: img1.width, height: img1.height}); + + pixelmatch(img1.data, img2.data, diff.data, img1.width, img1.height, {threshold: 0.1}); + + diff.pack().pipe(fs.createWriteStream('diff.png')); +} +``` + +#### Browsers + +```js +var img1 = img1Ctx.getImageData(0, 0, width, height), + img2 = img2Ctx.getImageData(0, 0, width, height), + diff = diffCtx.createImageData(width, height); + +pixelmatch(img1.data, img2.data, diff.data, width, height, {threshold: 0.1}); + +diffCtx.putImageData(diff, 0, 0); +``` + +### Install + +Install with NPM: + +```bash +npm install pixelmatch +``` + +To build a browser-compatible version, clone the repository locally, then run: + +```bash +npm install -g browserify +browserify -s pixelmatch index.js > pixelmatch.js +``` + +### [Changelog](https://github.com/mapbox/pixelmatch/releases) diff --git a/node_modules/pixelmatch/bin/pixelmatch b/node_modules/pixelmatch/bin/pixelmatch new file mode 100644 index 00000000..960457f0 --- /dev/null +++ b/node_modules/pixelmatch/bin/pixelmatch @@ -0,0 +1,35 @@ +#!/usr/bin/env node +'use strict'; + +var PNG = require('pngjs').PNG, + fs = require('fs'), + match = require('../.'); + +if (process.argv.length < 5) { + console.log('Usage: imagematch image1.png image2.png output.png [threshold=0.005] [includeAA=false]'); + return; +} + +var threshold = isNaN(+process.argv[5]) ? undefined : +process.argv[5], + includeAA = process.argv[6] === 'true'; + +var img1 = fs.createReadStream(process.argv[2]).pipe(new PNG()).on('parsed', doneReading); +var img2 = fs.createReadStream(process.argv[3]).pipe(new PNG()).on('parsed', doneReading); + +function doneReading() { + if (!img1.data || !img2.data) return; + + var diff = new PNG({width: img1.width, height: img1.height}); + + console.time('match'); + var diffs = match(img1.data, img2.data, diff.data, diff.width, diff.height, { + threshold: threshold, + includeAA: includeAA + }); + console.timeEnd('match'); + + diff.pack().pipe(fs.createWriteStream(process.argv[4])); + + console.log('different pixels: ' + diffs); + console.log('error: ' + (Math.round(100 * 100 * diffs / (diff.width * diff.height)) / 100) + '%'); +} diff --git a/node_modules/pixelmatch/index.js b/node_modules/pixelmatch/index.js new file mode 100644 index 00000000..4af9de6d --- /dev/null +++ b/node_modules/pixelmatch/index.js @@ -0,0 +1,158 @@ +'use strict'; + +module.exports = pixelmatch; + +function pixelmatch(img1, img2, output, width, height, options) { + + if (!options) options = {}; + + var threshold = options.threshold === undefined ? 0.1 : options.threshold; + + // maximum acceptable square distance between two colors; + // 35215 is the maximum possible value for the YIQ difference metric + var maxDelta = 35215 * threshold * threshold, + diff = 0; + + // compare each pixel of one image against the other one + for (var y = 0; y < height; y++) { + for (var x = 0; x < width; x++) { + + var pos = (y * width + x) * 4; + + // squared YUV distance between colors at this pixel position + var delta = colorDelta(img1, img2, pos, pos); + + // the color difference is above the threshold + if (delta > maxDelta) { + // check it's a real rendering difference or just anti-aliasing + if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || + antialiased(img2, x, y, width, height, img1))) { + // one of the pixels is anti-aliasing; draw as yellow and do not count as difference + if (output) drawPixel(output, pos, 255, 255, 0); + + } else { + // found substantial difference not caused by anti-aliasing; draw it as red + if (output) drawPixel(output, pos, 255, 0, 0); + diff++; + } + + } else if (output) { + // pixels are similar; draw background as grayscale image blended with white + var val = blend(grayPixel(img1, pos), 0.1); + drawPixel(output, pos, val, val, val); + } + } + } + + // return the number of different pixels + return diff; +} + +// check if a pixel is likely a part of anti-aliasing; +// based on "Anti-aliased Pixel and Intensity Slope Detector" paper by V. Vysniauskas, 2009 + +function antialiased(img, x1, y1, width, height, img2) { + var x0 = Math.max(x1 - 1, 0), + y0 = Math.max(y1 - 1, 0), + x2 = Math.min(x1 + 1, width - 1), + y2 = Math.min(y1 + 1, height - 1), + pos = (y1 * width + x1) * 4, + zeroes = 0, + positives = 0, + negatives = 0, + min = 0, + max = 0, + minX, minY, maxX, maxY; + + // go through 8 adjacent pixels + for (var x = x0; x <= x2; x++) { + for (var y = y0; y <= y2; y++) { + if (x === x1 && y === y1) continue; + + // brightness delta between the center pixel and adjacent one + var delta = colorDelta(img, img, pos, (y * width + x) * 4, true); + + // count the number of equal, darker and brighter adjacent pixels + if (delta === 0) zeroes++; + else if (delta < 0) negatives++; + else if (delta > 0) positives++; + + // if found more than 2 equal siblings, it's definitely not anti-aliasing + if (zeroes > 2) return false; + + if (!img2) continue; + + // remember the darkest pixel + if (delta < min) { + min = delta; + minX = x; + minY = y; + } + // remember the brightest pixel + if (delta > max) { + max = delta; + maxX = x; + maxY = y; + } + } + } + + if (!img2) return true; + + // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing + if (negatives === 0 || positives === 0) return false; + + // if either the darkest or the brightest pixel has more than 2 equal siblings in both images + // (definitely not anti-aliased), this pixel is anti-aliased + return (!antialiased(img, minX, minY, width, height) && !antialiased(img2, minX, minY, width, height)) || + (!antialiased(img, maxX, maxY, width, height) && !antialiased(img2, maxX, maxY, width, height)); +} + +// calculate color difference according to the paper "Measuring perceived color difference +// using YIQ NTSC transmission color space in mobile applications" by Y. Kotsarenko and F. Ramos + +function colorDelta(img1, img2, k, m, yOnly) { + var a1 = img1[k + 3] / 255, + a2 = img2[m + 3] / 255, + + r1 = blend(img1[k + 0], a1), + g1 = blend(img1[k + 1], a1), + b1 = blend(img1[k + 2], a1), + + r2 = blend(img2[m + 0], a2), + g2 = blend(img2[m + 1], a2), + b2 = blend(img2[m + 2], a2), + + y = rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2); + + if (yOnly) return y; // brightness difference only + + var i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2), + q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2); + + return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q; +} + +function rgb2y(r, g, b) { return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; } +function rgb2i(r, g, b) { return r * 0.59597799 - g * 0.27417610 - b * 0.32180189; } +function rgb2q(r, g, b) { return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; } + +// blend semi-transparent color with white +function blend(c, a) { + return 255 + (c - 255) * a; +} + +function drawPixel(output, pos, r, g, b) { + output[pos + 0] = r; + output[pos + 1] = g; + output[pos + 2] = b; + output[pos + 3] = 255; +} + +function grayPixel(img, i) { + var a = img[i + 3] / 255, + r = blend(img[i + 0], a), + g = blend(img[i + 1], a), + b = blend(img[i + 2], a); + return rgb2y(r, g, b); +} diff --git a/node_modules/pixelmatch/package.json b/node_modules/pixelmatch/package.json new file mode 100644 index 00000000..8f292b6e --- /dev/null +++ b/node_modules/pixelmatch/package.json @@ -0,0 +1,39 @@ +{ + "name": "pixelmatch", + "version": "4.0.2", + "description": "The smallest and fastest pixel-level image comparison library.", + "main": "index.js", + "bin": { + "pixelmatch": "bin/pixelmatch" + }, + "dependencies": { + "pngjs": "^3.0.0" + }, + "devDependencies": { + "eslint": "^3.2.2", + "eslint-config-mourner": "^2.0.1", + "tap": "^6.3.0" + }, + "scripts": { + "pretest": "eslint index.js bin/pixelmatch test/test.js", + "test": "tap test/test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/mapbox/pixelmatch.git" + }, + "keywords": [ + "image", + "comparison", + "diff" + ], + "eslintConfig": { + "extends": "mourner" + }, + "author": "Vladimir Agafonkin", + "license": "ISC", + "bugs": { + "url": "https://github.com/mapbox/pixelmatch/issues" + }, + "homepage": "https://github.com/mapbox/pixelmatch#readme" +} diff --git a/node_modules/pixelmatch/pixelmatch.sublime-project b/node_modules/pixelmatch/pixelmatch.sublime-project new file mode 100644 index 00000000..24db3031 --- /dev/null +++ b/node_modules/pixelmatch/pixelmatch.sublime-project @@ -0,0 +1,8 @@ +{ + "folders": + [ + { + "path": "." + } + ] +} diff --git a/node_modules/pixelmatch/pixelmatch.sublime-workspace b/node_modules/pixelmatch/pixelmatch.sublime-workspace new file mode 100644 index 00000000..3d3842c9 --- /dev/null +++ b/node_modules/pixelmatch/pixelmatch.sublime-workspace @@ -0,0 +1,756 @@ +{ + "auto_complete": + { + "selected_items": + [ + [ + "rgb", + "rgb2y" + ], + [ + "gra", + "grayPixel" + ], + [ + "remove", + "removeNode" + ], + [ + "maxT", + "maxTX" + ], + [ + "min", + "minTX" + ], + [ + "or", + "orient" + ], + [ + "left", + "leftmost" + ], + [ + "hole", + "holeNode" + ], + [ + "draw", + "drawRing" + ], + [ + "outer", + "outerNode" + ], + [ + "_upda", + "_updateTransform" + ], + [ + "_remove", + "_removeAllTiles" + ], + [ + "_reset", + "_resetAll" + ], + [ + "_update", + "_updateTransform" + ], + [ + "pane", + "panePos" + ], + [ + "fun", + "function" + ] + ] + }, + "buffers": + [ + { + "file": "index.js", + "settings": + { + "buffer_size": 5476, + "line_ending": "Unix" + } + }, + { + "file": "README.md", + "settings": + { + "buffer_size": 3963, + "line_ending": "Unix" + } + }, + { + "file": ".travis.yml", + "settings": + { + "buffer_size": 50, + "line_ending": "Unix" + } + }, + { + "file": "test/test.js", + "settings": + { + "buffer_size": 1789, + "line_ending": "Unix" + } + } + ], + "build_system": "", + "build_system_choices": + [ + ], + "build_varint": "", + "command_palette": + { + "height": 392.0, + "last_filter": "spac", + "selected_items": + [ + [ + "spac", + "Indentation: Convert to Spaces" + ], + [ + "spa", + "Indentation: Convert to Spaces" + ], + [ + "java", + "Set Syntax: JavaScript" + ], + [ + "insta", + "Package Control: Install Package" + ], + [ + "install ", + "Package Control: Install Package" + ], + [ + "packa", + "Package Control: Install Package" + ] + ], + "width": 467.0 + }, + "console": + { + "height": 126.0, + "history": + [ + "import urllib.request,os,hashlib; h = 'eb2297e1a458f27d836c04bb0cbaf282' + 'd0e7a3098092775ccb37ca9d6b2e4b7d'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)" + ] + }, + "distraction_free": + { + "menu_visible": true, + "show_minimap": false, + "show_open_files": false, + "show_tabs": false, + "side_bar_visible": false, + "status_bar_visible": false + }, + "expanded_folders": + [ + "/Users/mourner/projects/pixelmatch", + "/Users/mourner/projects/pixelmatch/test", + "/Users/mourner/projects/pixelmatch/test/fixtures", + "/Users/mourner/projects/pixelmatch/tmp" + ], + "file_history": + [ + "/Users/mourner/projects/pixelmatch/max.js", + "/Users/mourner/projects/pixelmatch/test/fixtures/4diff.png", + "/Users/mourner/projects/pixelmatch/tmp/1.png", + "/Users/mourner/projects/pixelmatch/tmp/2.png", + "/Users/mourner/projects/pixelmatch/test/fixtures/3diff.png", + "/Users/mourner/projects/pixelmatch/test/fixtures/3diff2.png", + "/Users/mourner/projects/pixelmatch/test/fixtures/1diff.png", + "/Users/mourner/projects/pixelmatch/test/fixtures/1diff2.png", + "/Users/mourner/projects/pixelmatch/tmp/diff2.png", + "/Users/mourner/projects/pixelmatch/tmp/diff.png", + "/Users/mourner/projects/pixelmatch/test/fixtures/4diff2.png", + "/Users/mourner/projects/earcut/viz/viz.js", + "/Users/mourner/projects/earcut/viz/index.html", + "/Users/mourner/projects/earcut/test/fixtures/issue35.json", + "/Users/mourner/projects/earcut/test/fixtures/issue34.json", + "/Users/mourner/projects/earcut/src/earcut.js", + "/Users/mourner/projects/earcut/test/fixtures/dude.json", + "/Users/mourner/projects/earcut/bench/basic.js", + "/Users/mourner/projects/earcut/test/fixtures/empty-square.json", + "/Users/mourner/projects/earcut/test/fixtures/issue29.json", + "/Users/mourner/projects/earcut/test/test.js", + "/Users/mourner/projects/earcut/README.md", + "/Users/mourner/projects/earcut/bench/bench.js", + "/Users/mourner/projects/earcut/.travis.yml", + "/Users/mourner/projects/earcut/package.json", + "/Users/mourner/projects/earcut/.eslintrc", + "/Users/mourner/projects/geojson-vt/debug/debug.js", + "/Users/mourner/projects/geojson-vt/src/simplify.js", + "/Users/mourner/projects/geojson-vt/src/transform.js", + "/Users/mourner/projects/geojson-vt/debug/index.html", + "/Users/mourner/projects/geojson-vt/LICENSE", + "/Users/mourner/projects/geojson-vt/package.json", + "/Users/mourner/Library/Application Support/Sublime Text 3/Packages/Default/Preferences.sublime-settings", + "/Users/mourner/Library/Application Support/Sublime Text 3/Packages/User/Preferences.sublime-settings", + "/Users/mourner/projects/Leaflet/CHANGELOG.md", + "/usr/local/Library/Formula/node.rb", + "/Users/mourner/projects/Leaflet/package.json", + "/Users/mourner/projects/Leaflet/src/layer/tile/GridLayer.js", + "/Users/mourner/projects/Leaflet/Leaflet.sublime-project", + "/Users/mourner/projects/Leaflet/.eslintrc", + "/Users/mourner/projects/Leaflet/src/layer/marker/Icon.js", + "/Users/mourner/.inputrc", + "/Users/mourner/.bash_profile", + "/Users/mourner/.gitignore" + ], + "find": + { + "height": 35.0 + }, + "find_in_files": + { + "height": 93.0, + "where_history": + [ + "" + ] + }, + "find_state": + { + "case_sensitive": false, + "find_history": + [ + "17", + "1", + "r", + "1", + "255", + "blend", + " / 255", + "j", + "i", + "a1", + "img1", + "15", + "10", + "rgb2i", + "rgb2y", + "img2", + "rgba", + "rgba2y", + "= 5", + "5", + "10", + "++", + "1", + "r1", + ">", + "],[", + "],", + ">= 0", + "3600", + "3400", + ",[[", + "findHoleB", + "]],", + "32767", + ".next.prev", + "remove", + "break", + "ear", + "cureLocalIntersections", + "splitPolygon", + "32767", + "(maxX - minX)", + ", minX, minY, maxX, maxY", + "minX, minY, maxX, maxY", + "32767", + "node.z", + "65535", + "0x3ff", + "65535", + "1023", + "console.log", + "console.log\\", + "minX, minY, size", + "minX, minY, ", + "1023", + "1024", + "x", + "size", + "1024", + "100000", + "0x0000ffff", + "100000", + "1000", + "100000", + "x = ", + "1024", + "1000", + "10", + "1024 * ", + "ceil", + "1000", + "x++", + " | 0", + "zOrder", + "1000", + ".z", + "1000", + "1024", + "1000", + "zorder(", + "cureLocalIntersections", + "py", + "px", + " && ((s && t) || (s && k) || (t && k))", + "splitearcut", + "orient", + ">= 0", + ">=", + "poly", + "cureLocalIntersections", + "splitEarcut", + "2958", + "}", + "{", + "nextZ", + "node", + "c.i", + "a.i", + "node.i", + "i", + "node.i", + "prevZ ", + "data, ", + "indexCurve", + "p", + "data, ", + "data[b]", + "data[a]", + "data[b + 1]", + "data[a + 1]", + "data, ", + "eliminateHoles", + "data, ", + "data[i]", + "data, ", + "data", + "filterPoints(data, ", + "filterpoints", + "cureLocalIntersections", + "intersects(", + "intersects", + "locallyInside", + "middleInside", + "middleinside", + "data[a]", + "start", + "intersectsPolygon", + "orient(data, " + ], + "highlight": true, + "in_selection": false, + "preserve_case": false, + "regex": false, + "replace_history": + [ + "]", + "[", + "]", + "[" + ], + "reverse": false, + "show_context": true, + "use_buffer2": true, + "whole_word": false, + "wrap": true + }, + "groups": + [ + { + "selected": 2, + "sheets": + [ + { + "buffer": 0, + "file": "index.js", + "semi_transient": false, + "settings": + { + "buffer_size": 5476, + "regions": + { + }, + "selection": + [ + [ + 567, + 567 + ] + ], + "settings": + { + "syntax": "Packages/JavaScript/JavaScript.sublime-syntax", + "tab_size": 4, + "translate_tabs_to_spaces": true + }, + "translation.x": 0.0, + "translation.y": 0.0, + "zoom_level": 1.0 + }, + "stack_index": 2, + "type": "text" + }, + { + "buffer": 1, + "file": "README.md", + "semi_transient": false, + "settings": + { + "buffer_size": 3963, + "regions": + { + }, + "selection": + [ + [ + 301, + 301 + ] + ], + "settings": + { + "syntax": "Packages/Markdown/Markdown.sublime-syntax", + "tab_size": 4, + "translate_tabs_to_spaces": true + }, + "translation.x": 0.0, + "translation.y": 0.0, + "zoom_level": 1.0 + }, + "stack_index": 1, + "type": "text" + }, + { + "buffer": 2, + "file": ".travis.yml", + "semi_transient": true, + "settings": + { + "buffer_size": 50, + "regions": + { + }, + "selection": + [ + [ + 0, + 50 + ] + ], + "settings": + { + "syntax": "Packages/YAML/YAML.sublime-syntax" + }, + "translation.x": 0.0, + "translation.y": 0.0, + "zoom_level": 1.0 + }, + "stack_index": 0, + "type": "text" + }, + { + "buffer": 3, + "file": "test/test.js", + "semi_transient": false, + "settings": + { + "buffer_size": 1789, + "regions": + { + }, + "selection": + [ + [ + 0, + 0 + ] + ], + "settings": + { + "syntax": "Packages/JavaScript/JavaScript.sublime-syntax", + "tab_size": 4, + "translate_tabs_to_spaces": true + }, + "translation.x": 0.0, + "translation.y": 0.0, + "zoom_level": 1.0 + }, + "stack_index": 3, + "type": "text" + } + ] + } + ], + "incremental_find": + { + "height": 23.0 + }, + "input": + { + "height": 31.0 + }, + "layout": + { + "cells": + [ + [ + 0, + 0, + 1, + 1 + ] + ], + "cols": + [ + 0.0, + 1.0 + ], + "rows": + [ + 0.0, + 1.0 + ] + }, + "menu_visible": true, + "output.find_results": + { + "height": 0.0 + }, + "pinned_build_system": "", + "project": "pixelmatch.sublime-project", + "replace": + { + "height": 42.0 + }, + "save_all_on_build": true, + "select_file": + { + "height": 0.0, + "last_filter": "", + "selected_items": + [ + [ + "in", + "index.js" + ], + [ + "ear", + "src/earcut.js" + ], + [ + "viz", + "viz/viz.js" + ], + [ + "ben", + "bench/bench.js" + ], + [ + "test", + "test/test.js" + ], + [ + "du", + "test/fixtures/dude.json" + ], + [ + "vi", + "viz/viz.js" + ], + [ + "ind", + "viz/index.html" + ], + [ + "popu", + "src/layer/Popup.js" + ], + [ + "rend", + "src/layer/vector/Renderer.js" + ], + [ + "image", + "src/layer/ImageOverlay.js" + ], + [ + "path", + "src/layer/vector/Path.js" + ], + [ + "render", + "src/layer/vector/Renderer.js" + ], + [ + "marker", + "src/layer/marker/Marker.js" + ], + [ + "fl", + "src/map/anim/Map.FlyTo.js" + ], + [ + "grid", + "src/layer/tile/GridLayer.js" + ], + [ + "map", + "src/map/Map.js" + ], + [ + "polyli", + "src/layer/vector/Polyline.js" + ], + [ + "mapsp", + "spec/suites/map/MapSpec.js" + ], + [ + "popup", + "src/layer/Popup.js" + ], + [ + "crs", + "src/geo/crs/CRS.js" + ], + [ + "touch", + "src/map/handler/Map.TouchZoom.js" + ], + [ + "poly", + "src/layer/vector/Polyline.js" + ], + [ + "leafl", + "dist/leaflet.css" + ], + [ + "zoompa", + "debug/map/zoompan.html" + ], + [ + "map.dra", + "src/map/handler/Map.Drag.js" + ], + [ + "chan", + "CHANGELOG.md" + ], + [ + "domut", + "src/dom/DomUtil.js" + ], + [ + "scroll", + "src/map/handler/Map.ScrollWheelZoom.js" + ], + [ + "leaf", + "dist/leaflet.css" + ], + [ + "dom", + "src/dom/DomUtil.js" + ], + [ + "sv", + "src/layer/vector/SVG.js" + ], + [ + "re", + "src/layer/vector/Renderer.js" + ], + [ + "ren", + "src/layer/vector/Renderer.js" + ], + [ + "svg", + "src/layer/vector/SVG.js" + ], + [ + "even", + "src/core/Events.js" + ], + [ + "iamge", + "src/layer/ImageOverlay.js" + ], + [ + "icon", + "src/layer/marker/Icon.js" + ], + [ + "drag", + "src/map/handler/Map.Drag.js" + ] + ], + "width": 0.0 + }, + "select_project": + { + "height": 500.0, + "last_filter": "", + "selected_items": + [ + [ + "gl", + "~/projects/mapbox-gl-js/mapbox-gl-js.sublime-project" + ], + [ + "le", + "~/projects/Leaflet/Leaflet.sublime-project" + ], + [ + "", + "~/projects/rbush/rbush.sublime-project" + ] + ], + "width": 380.0 + }, + "select_symbol": + { + "height": 0.0, + "last_filter": "", + "selected_items": + [ + ], + "width": 0.0 + }, + "selected_group": 0, + "settings": + { + }, + "show_minimap": true, + "show_open_files": false, + "show_tabs": true, + "side_bar_visible": true, + "side_bar_width": 249.0, + "status_bar_visible": true, + "template_settings": + { + } +} diff --git a/node_modules/pixelmatch/test/fixtures/1a.png b/node_modules/pixelmatch/test/fixtures/1a.png new file mode 100644 index 00000000..78f37146 Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/1a.png differ diff --git a/node_modules/pixelmatch/test/fixtures/1b.png b/node_modules/pixelmatch/test/fixtures/1b.png new file mode 100644 index 00000000..645046ad Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/1b.png differ diff --git a/node_modules/pixelmatch/test/fixtures/1diff.png b/node_modules/pixelmatch/test/fixtures/1diff.png new file mode 100644 index 00000000..bf874ebf Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/1diff.png differ diff --git a/node_modules/pixelmatch/test/fixtures/2a.png b/node_modules/pixelmatch/test/fixtures/2a.png new file mode 100644 index 00000000..b3aa8794 Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/2a.png differ diff --git a/node_modules/pixelmatch/test/fixtures/2b.png b/node_modules/pixelmatch/test/fixtures/2b.png new file mode 100644 index 00000000..8320b0c9 Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/2b.png differ diff --git a/node_modules/pixelmatch/test/fixtures/2diff.png b/node_modules/pixelmatch/test/fixtures/2diff.png new file mode 100644 index 00000000..f075b7dd Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/2diff.png differ diff --git a/node_modules/pixelmatch/test/fixtures/3a.png b/node_modules/pixelmatch/test/fixtures/3a.png new file mode 100644 index 00000000..70d0ebe7 Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/3a.png differ diff --git a/node_modules/pixelmatch/test/fixtures/3b.png b/node_modules/pixelmatch/test/fixtures/3b.png new file mode 100644 index 00000000..33caab63 Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/3b.png differ diff --git a/node_modules/pixelmatch/test/fixtures/3diff.png b/node_modules/pixelmatch/test/fixtures/3diff.png new file mode 100644 index 00000000..6a9c82b0 Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/3diff.png differ diff --git a/node_modules/pixelmatch/test/fixtures/4a.png b/node_modules/pixelmatch/test/fixtures/4a.png new file mode 100644 index 00000000..7ed33d17 Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/4a.png differ diff --git a/node_modules/pixelmatch/test/fixtures/4b.png b/node_modules/pixelmatch/test/fixtures/4b.png new file mode 100644 index 00000000..357790ae Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/4b.png differ diff --git a/node_modules/pixelmatch/test/fixtures/4diff.png b/node_modules/pixelmatch/test/fixtures/4diff.png new file mode 100644 index 00000000..ce533ece Binary files /dev/null and b/node_modules/pixelmatch/test/fixtures/4diff.png differ diff --git a/node_modules/pixelmatch/test/test.js b/node_modules/pixelmatch/test/test.js new file mode 100644 index 00000000..4d09c587 --- /dev/null +++ b/node_modules/pixelmatch/test/test.js @@ -0,0 +1,47 @@ +'use strict'; + +var PNG = require('pngjs').PNG, + fs = require('fs'), + test = require('tap').test, + path = require('path'), + match = require('../.'); + +diffTest('1a', '1b', '1diff', 0.05, false, 143); +diffTest('2a', '2b', '2diff', 0.05, false, 12439); +diffTest('3a', '3b', '3diff', 0.05, false, 212); +diffTest('4a', '4b', '4diff', 0.05, false, 36089); + +function diffTest(imgPath1, imgPath2, diffPath, threshold, includeAA, expectedMismatch) { + var name = 'comparing ' + imgPath1 + ' to ' + imgPath2 + + ', threshold: ' + threshold + ', includeAA: ' + includeAA; + + test(name, function (t) { + var img1 = readImage(imgPath1, function () { + var img2 = readImage(imgPath2, function () { + var expectedDiff = readImage(diffPath, function () { + var diff = new PNG({width: img1.width, height: img1.height}); + + var mismatch = match(img1.data, img2.data, diff.data, diff.width, diff.height, { + threshold: threshold, + includeAA: includeAA + }); + + var mismatch2 = match(img1.data, img2.data, null, diff.width, diff.height, { + threshold: threshold, + includeAA: includeAA + }); + + t.same(diff.data, expectedDiff.data, 'diff image'); + t.same(mismatch, expectedMismatch, 'number of mismatched pixels'); + t.same(mismatch, mismatch2, 'number of mismatched pixels'); + + t.end(); + }); + }); + }); + }); +} + +function readImage(name, done) { + return fs.createReadStream(path.join(__dirname, '/fixtures/' + name + '.png')).pipe(new PNG()).on('parsed', done); +} diff --git a/node_modules/process/.eslintrc b/node_modules/process/.eslintrc new file mode 100644 index 00000000..1e7aab73 --- /dev/null +++ b/node_modules/process/.eslintrc @@ -0,0 +1,21 @@ +{ +extends: "eslint:recommended", + "env": { + "node": true, + "browser": true, + "es6" : true, + "mocha": true + }, + "rules": { + "indent": [2, 4], + "brace-style": [2, "1tbs"], + "quotes": [2, "single"], + "no-console": 0, + "no-shadow": 0, + "no-use-before-define": [2, "nofunc"], + "no-underscore-dangle": 0, + "no-constant-condition": 0, + "space-after-function-name": 0, + "consistent-return": 0 + } +} diff --git a/node_modules/process/LICENSE b/node_modules/process/LICENSE new file mode 100644 index 00000000..b8c1246c --- /dev/null +++ b/node_modules/process/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Roman Shtylman + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/process/README.md b/node_modules/process/README.md new file mode 100644 index 00000000..6570729b --- /dev/null +++ b/node_modules/process/README.md @@ -0,0 +1,26 @@ +# process + +```require('process');``` just like any other module. + +Works in node.js and browsers via the browser.js shim provided with the module. + +## browser implementation + +The goal of this module is not to be a full-fledged alternative to the builtin process module. This module mostly exists to provide the nextTick functionality and little more. We keep this module lean because it will often be included by default by tools like browserify when it detects a module has used the `process` global. + +It also exposes a "browser" member (i.e. `process.browser`) which is `true` in this implementation but `undefined` in node. This can be used in isomorphic code that adjusts it's behavior depending on which environment it's running in. + +If you are looking to provide other process methods, I suggest you monkey patch them onto the process global in your app. A list of user created patches is below. + +* [hrtime](https://github.com/kumavis/browser-process-hrtime) +* [stdout](https://github.com/kumavis/browser-stdout) + +## package manager notes + +If you are writing a bundler to package modules for client side use, make sure you use the ```browser``` field hint in package.json. + +See https://gist.github.com/4339901 for details. + +The [browserify](https://github.com/substack/node-browserify) module will properly handle this field when bundling your files. + + diff --git a/node_modules/process/browser.js b/node_modules/process/browser.js new file mode 100644 index 00000000..d0593623 --- /dev/null +++ b/node_modules/process/browser.js @@ -0,0 +1,184 @@ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; diff --git a/node_modules/process/index.js b/node_modules/process/index.js new file mode 100644 index 00000000..8d8ed7df --- /dev/null +++ b/node_modules/process/index.js @@ -0,0 +1,2 @@ +// for now just expose the builtin process global from node.js +module.exports = global.process; diff --git a/node_modules/process/package.json b/node_modules/process/package.json new file mode 100644 index 00000000..d2cfaade --- /dev/null +++ b/node_modules/process/package.json @@ -0,0 +1,27 @@ +{ + "author": "Roman Shtylman ", + "name": "process", + "description": "process information for node.js and browsers", + "keywords": [ + "process" + ], + "scripts": { + "test": "mocha test.js", + "browser": "zuul --no-coverage --ui mocha-bdd --local 8080 -- test.js" + }, + "version": "0.11.10", + "repository": { + "type": "git", + "url": "git://github.com/shtylman/node-process.git" + }, + "license": "MIT", + "browser": "./browser.js", + "main": "./index.js", + "engines": { + "node": ">= 0.6.0" + }, + "devDependencies": { + "mocha": "2.2.1", + "zuul": "^3.10.3" + } +} diff --git a/node_modules/process/test.js b/node_modules/process/test.js new file mode 100644 index 00000000..8ba579c0 --- /dev/null +++ b/node_modules/process/test.js @@ -0,0 +1,199 @@ +var assert = require('assert'); +var ourProcess = require('./browser'); +describe('test against our process', function () { + test(ourProcess); +}); +if (!process.browser) { + describe('test against node', function () { + test(process); + }); + vmtest(); +} +function test (ourProcess) { + describe('test arguments', function () { + it ('works', function (done) { + var order = 0; + + + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'first one works'); + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'recursive one is 4th'); + }, 3); + }, 0); + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'second one starts'); + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'this is third'); + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'this is last'); + done(); + }, 5); + }, 4); + }, 1); + ourProcess.nextTick(function (num) { + + assert.equal(num, order++, '3rd schedualed happens after the error'); + }, 2); + }); + }); +if (!process.browser) { + describe('test errors', function (t) { + it ('works', function (done) { + var order = 0; + process.removeAllListeners('uncaughtException'); + process.once('uncaughtException', function(err) { + assert.equal(2, order++, 'error is third'); + ourProcess.nextTick(function () { + assert.equal(5, order++, 'schedualed in error is last'); + done(); + }); + }); + ourProcess.nextTick(function () { + assert.equal(0, order++, 'first one works'); + ourProcess.nextTick(function () { + assert.equal(4, order++, 'recursive one is 4th'); + }); + }); + ourProcess.nextTick(function () { + assert.equal(1, order++, 'second one starts'); + throw(new Error('an error is thrown')); + }); + ourProcess.nextTick(function () { + assert.equal(3, order++, '3rd schedualed happens after the error'); + }); + }); + }); +} + describe('rename globals', function (t) { + var oldTimeout = setTimeout; + var oldClear = clearTimeout; + + it('clearTimeout', function (done){ + + var ok = true; + clearTimeout = function () { + ok = false; + } + var ran = false; + function cleanup() { + clearTimeout = oldClear; + var err; + try { + assert.ok(ok, 'fake clearTimeout ran'); + assert.ok(ran, 'should have run'); + } catch (e) { + err = e; + } + done(err); + } + setTimeout(cleanup, 1000); + ourProcess.nextTick(function () { + ran = true; + }); + }); + it('just setTimeout', function (done){ + + + setTimeout = function () { + setTimeout = oldTimeout; + try { + assert.ok(false, 'fake setTimeout called') + } catch (e) { + done(e); + } + + } + + ourProcess.nextTick(function () { + setTimeout = oldTimeout; + done(); + }); + }); + }); +} +function vmtest() { + var vm = require('vm'); + var fs = require('fs'); + var process = fs.readFileSync('./browser.js', {encoding: 'utf8'}); + + + describe('should work in vm in strict mode with no globals', function () { + it('should parse', function (done) { + var str = '"use strict";var module = {exports:{}};'; + str += process; + str += 'this.works = process.browser;'; + var script = new vm.Script(str); + var context = { + works: false + }; + script.runInNewContext(context); + assert.ok(context.works); + done(); + }); + it('setTimeout throws error', function (done) { + var str = '"use strict";var module = {exports:{}};'; + str += process; + str += 'try {process.nextTick(function () {})} catch (e){this.works = e;}'; + var script = new vm.Script(str); + var context = { + works: false + }; + script.runInNewContext(context); + assert.ok(context.works); + done(); + }); + it('should generally work', function (done) { + var str = '"use strict";var module = {exports:{}};'; + str += process; + str += 'process.nextTick(function () {assert.ok(true);done();})'; + var script = new vm.Script(str); + var context = { + clearTimeout: clearTimeout, + setTimeout: setTimeout, + done: done, + assert: assert + }; + script.runInNewContext(context); + }); + it('late defs setTimeout', function (done) { + var str = '"use strict";var module = {exports:{}};'; + str += process; + str += 'var setTimeout = hiddenSetTimeout;process.nextTick(function () {assert.ok(true);done();})'; + var script = new vm.Script(str); + var context = { + clearTimeout: clearTimeout, + hiddenSetTimeout: setTimeout, + done: done, + assert: assert + }; + script.runInNewContext(context); + }); + it('late defs clearTimeout', function (done) { + var str = '"use strict";var module = {exports:{}};'; + str += process; + str += 'var clearTimeout = hiddenClearTimeout;process.nextTick(function () {assert.ok(true);done();})'; + var script = new vm.Script(str); + var context = { + hiddenClearTimeout: clearTimeout, + setTimeout: setTimeout, + done: done, + assert: assert + }; + script.runInNewContext(context); + }); + it('late defs setTimeout and then redefine', function (done) { + var str = '"use strict";var module = {exports:{}};'; + str += process; + str += 'var setTimeout = hiddenSetTimeout;process.nextTick(function () {setTimeout = function (){throw new Error("foo")};hiddenSetTimeout(function(){process.nextTick(function (){assert.ok(true);done();});});});'; + var script = new vm.Script(str); + var context = { + clearTimeout: clearTimeout, + hiddenSetTimeout: setTimeout, + done: done, + assert: assert + }; + script.runInNewContext(context); + }); + }); +} diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 00000000..2873b3b2 --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md new file mode 100644 index 00000000..339af1b6 --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,116 @@ +# readable-stream + +**_Node.js core streams for userland_** + +[![npm status](https://img.shields.io/npm/v/readable-stream.svg)](https://npm.im/readable-stream) +[![node](https://img.shields.io/node/v/readable-stream.svg)](https://www.npmjs.org/package/readable-stream) +[![Node.js Build](https://github.com/nodejs/readable-stream/workflows/Node.js/badge.svg)](https://github.com/nodejs/readable-stream/actions?query=workflow%3ANode.js) +[![Browsers Build](https://github.com/nodejs/readable-stream/workflows/Browsers/badge.svg)](https://github.com/nodejs/readable-stream/actions?query=workflow%3ABrowsers) + +```bash +npm install readable-stream +``` + +This package is a mirror of the streams implementations in Node.js 18.19.0. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v18.19.0/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** _only_ and avoid the _"stream"_ module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 4.x.x + +v4.x.x of `readable-stream` is a cut from Node 18. This version supports Node 12, 14, 16 and 18, as well as evergreen browsers. +The breaking changes introduced by v4 are composed of the combined breaking changes in: +* [Node v12](https://nodejs.org/en/blog/release/v12.0.0/) +* [Node v13](https://nodejs.org/en/blog/release/v13.0.0/) +* [Node v14](https://nodejs.org/en/blog/release/v14.0.0/) +* [Node v15](https://nodejs.org/en/blog/release/v15.0.0/) +* [Node v16](https://nodejs.org/en/blog/release/v16.0.0/) +* [Node v17](https://nodejs.org/en/blog/release/v17.0.0/) +* [Node v18](https://nodejs.org/en/blog/release/v18.0.0/) + +This also includes _many_ new features. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x + +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +``` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +## Usage In Browsers + +You will need a bundler like [`browserify`](https://github.com/browserify/browserify#readme), [`webpack`](https://webpack.js.org/), [`parcel`](https://github.com/parcel-bundler/parcel#readme) or similar. Polyfills are no longer required since version 4.2.0. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +- Addressing stream issues on the Node.js issue tracker. +- Authoring and editing stream documentation within the Node.js project. +- Reviewing changes to stream subclasses within the Node.js project. +- Redirecting changes to streams from the Node.js project to this + project. +- Assisting in the implementation of stream providers within Node.js. +- Recommending versions of `readable-stream` to be included in Node.js. +- Messaging about the future of streams to give the community advance + notice of changes. + + + +## Team Members + +- **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +- **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +- **Robert Nagy** ([@ronag](https://github.com/ronag)) <ronagy@icloud.com> +- **Vincent Weevers** ([@vweevers](https://github.com/vweevers)) <mail@vincentweevers.nl> diff --git a/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 00000000..e03c6bf5 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,4 @@ +'use strict' + +// Keep this file as an alias for the full stream module. +module.exports = require('./stream').Duplex diff --git a/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 00000000..1206dc45 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,4 @@ +'use strict' + +// Keep this file as an alias for the full stream module. +module.exports = require('./stream').PassThrough diff --git a/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 00000000..49416586 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,4 @@ +'use strict' + +// Keep this file as an alias for the full stream module. +module.exports = require('./stream').Readable diff --git a/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 00000000..ef227b12 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,4 @@ +'use strict' + +// Keep this file as an alias for the full stream module. +module.exports = require('./stream').Transform diff --git a/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 00000000..00c7b037 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,4 @@ +'use strict' + +// Keep this file as an alias for the full stream module. +module.exports = require('./stream').Writable diff --git a/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js b/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js new file mode 100644 index 00000000..3475b6e0 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js @@ -0,0 +1,52 @@ +'use strict' + +const { SymbolDispose } = require('../../ours/primordials') +const { AbortError, codes } = require('../../ours/errors') +const { isNodeStream, isWebStream, kControllerErrorFunction } = require('./utils') +const eos = require('./end-of-stream') +const { ERR_INVALID_ARG_TYPE } = codes +let addAbortListener + +// This method is inlined here for readable-stream +// It also does not allow for signal to not exist on the stream +// https://github.com/nodejs/node/pull/36061#discussion_r533718029 +const validateAbortSignal = (signal, name) => { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) + } +} +module.exports.addAbortSignal = function addAbortSignal(signal, stream) { + validateAbortSignal(signal, 'signal') + if (!isNodeStream(stream) && !isWebStream(stream)) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) + } + return module.exports.addAbortSignalNoValidate(signal, stream) +} +module.exports.addAbortSignalNoValidate = function (signal, stream) { + if (typeof signal !== 'object' || !('aborted' in signal)) { + return stream + } + const onAbort = isNodeStream(stream) + ? () => { + stream.destroy( + new AbortError(undefined, { + cause: signal.reason + }) + ) + } + : () => { + stream[kControllerErrorFunction]( + new AbortError(undefined, { + cause: signal.reason + }) + ) + } + if (signal.aborted) { + onAbort() + } else { + addAbortListener = addAbortListener || require('../../ours/util').addAbortListener + const disposable = addAbortListener(signal, onAbort) + eos(stream, disposable[SymbolDispose]) + } + return stream +} diff --git a/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 00000000..b55e35cf --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,157 @@ +'use strict' + +const { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = require('../../ours/primordials') +const { Buffer } = require('buffer') +const { inspect } = require('../../ours/util') +module.exports = class BufferList { + constructor() { + this.head = null + this.tail = null + this.length = 0 + } + push(v) { + const entry = { + data: v, + next: null + } + if (this.length > 0) this.tail.next = entry + else this.head = entry + this.tail = entry + ++this.length + } + unshift(v) { + const entry = { + data: v, + next: this.head + } + if (this.length === 0) this.tail = entry + this.head = entry + ++this.length + } + shift() { + if (this.length === 0) return + const ret = this.head.data + if (this.length === 1) this.head = this.tail = null + else this.head = this.head.next + --this.length + return ret + } + clear() { + this.head = this.tail = null + this.length = 0 + } + join(s) { + if (this.length === 0) return '' + let p = this.head + let ret = '' + p.data + while ((p = p.next) !== null) ret += s + p.data + return ret + } + concat(n) { + if (this.length === 0) return Buffer.alloc(0) + const ret = Buffer.allocUnsafe(n >>> 0) + let p = this.head + let i = 0 + while (p) { + TypedArrayPrototypeSet(ret, p.data, i) + i += p.data.length + p = p.next + } + return ret + } + + // Consumes a specified amount of bytes or characters from the buffered data. + consume(n, hasStrings) { + const data = this.head.data + if (n < data.length) { + // `slice` is the same for buffers and strings. + const slice = data.slice(0, n) + this.head.data = data.slice(n) + return slice + } + if (n === data.length) { + // First chunk is a perfect match. + return this.shift() + } + // Result spans more than one buffer. + return hasStrings ? this._getString(n) : this._getBuffer(n) + } + first() { + return this.head.data + } + *[SymbolIterator]() { + for (let p = this.head; p; p = p.next) { + yield p.data + } + } + + // Consumes a specified amount of characters from the buffered data. + _getString(n) { + let ret = '' + let p = this.head + let c = 0 + do { + const str = p.data + if (n > str.length) { + ret += str + n -= str.length + } else { + if (n === str.length) { + ret += str + ++c + if (p.next) this.head = p.next + else this.head = this.tail = null + } else { + ret += StringPrototypeSlice(str, 0, n) + this.head = p + p.data = StringPrototypeSlice(str, n) + } + break + } + ++c + } while ((p = p.next) !== null) + this.length -= c + return ret + } + + // Consumes a specified amount of bytes from the buffered data. + _getBuffer(n) { + const ret = Buffer.allocUnsafe(n) + const retLen = n + let p = this.head + let c = 0 + do { + const buf = p.data + if (n > buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n) + n -= buf.length + } else { + if (n === buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n) + ++c + if (p.next) this.head = p.next + else this.head = this.tail = null + } else { + TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n) + this.head = p + p.data = buf.slice(n) + } + break + } + ++c + } while ((p = p.next) !== null) + this.length -= c + return ret + } + + // Make sure the linked list only shows the minimal necessary information. + [Symbol.for('nodejs.util.inspect.custom')](_, options) { + return inspect(this, { + ...options, + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + }) + } +} diff --git a/node_modules/readable-stream/lib/internal/streams/compose.js b/node_modules/readable-stream/lib/internal/streams/compose.js new file mode 100644 index 00000000..b399d540 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/compose.js @@ -0,0 +1,194 @@ +'use strict' + +const { pipeline } = require('./pipeline') +const Duplex = require('./duplex') +const { destroyer } = require('./destroy') +const { + isNodeStream, + isReadable, + isWritable, + isWebStream, + isTransformStream, + isWritableStream, + isReadableStream +} = require('./utils') +const { + AbortError, + codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } +} = require('../../ours/errors') +const eos = require('./end-of-stream') +module.exports = function compose(...streams) { + if (streams.length === 0) { + throw new ERR_MISSING_ARGS('streams') + } + if (streams.length === 1) { + return Duplex.from(streams[0]) + } + const orgStreams = [...streams] + if (typeof streams[0] === 'function') { + streams[0] = Duplex.from(streams[0]) + } + if (typeof streams[streams.length - 1] === 'function') { + const idx = streams.length - 1 + streams[idx] = Duplex.from(streams[idx]) + } + for (let n = 0; n < streams.length; ++n) { + if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { + // TODO(ronag): Add checks for non streams. + continue + } + if ( + n < streams.length - 1 && + !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n])) + ) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable') + } + if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable') + } + } + let ondrain + let onfinish + let onreadable + let onclose + let d + function onfinished(err) { + const cb = onclose + onclose = null + if (cb) { + cb(err) + } else if (err) { + d.destroy(err) + } else if (!readable && !writable) { + d.destroy() + } + } + const head = streams[0] + const tail = pipeline(streams, onfinished) + const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)) + const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)) + + // TODO(ronag): Avoid double buffering. + // Implement Writable/Readable/Duplex traits. + // See, https://github.com/nodejs/node/pull/33515. + d = new Duplex({ + // TODO (ronag): highWaterMark? + writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode), + readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode), + writable, + readable + }) + if (writable) { + if (isNodeStream(head)) { + d._write = function (chunk, encoding, callback) { + if (head.write(chunk, encoding)) { + callback() + } else { + ondrain = callback + } + } + d._final = function (callback) { + head.end() + onfinish = callback + } + head.on('drain', function () { + if (ondrain) { + const cb = ondrain + ondrain = null + cb() + } + }) + } else if (isWebStream(head)) { + const writable = isTransformStream(head) ? head.writable : head + const writer = writable.getWriter() + d._write = async function (chunk, encoding, callback) { + try { + await writer.ready + writer.write(chunk).catch(() => {}) + callback() + } catch (err) { + callback(err) + } + } + d._final = async function (callback) { + try { + await writer.ready + writer.close().catch(() => {}) + onfinish = callback + } catch (err) { + callback(err) + } + } + } + const toRead = isTransformStream(tail) ? tail.readable : tail + eos(toRead, () => { + if (onfinish) { + const cb = onfinish + onfinish = null + cb() + } + }) + } + if (readable) { + if (isNodeStream(tail)) { + tail.on('readable', function () { + if (onreadable) { + const cb = onreadable + onreadable = null + cb() + } + }) + tail.on('end', function () { + d.push(null) + }) + d._read = function () { + while (true) { + const buf = tail.read() + if (buf === null) { + onreadable = d._read + return + } + if (!d.push(buf)) { + return + } + } + } + } else if (isWebStream(tail)) { + const readable = isTransformStream(tail) ? tail.readable : tail + const reader = readable.getReader() + d._read = async function () { + while (true) { + try { + const { value, done } = await reader.read() + if (!d.push(value)) { + return + } + if (done) { + d.push(null) + return + } + } catch { + return + } + } + } + } + } + d._destroy = function (err, callback) { + if (!err && onclose !== null) { + err = new AbortError() + } + onreadable = null + ondrain = null + onfinish = null + if (onclose === null) { + callback(err) + } else { + onclose = callback + if (isNodeStream(tail)) { + destroyer(tail, err) + } + } + } + return d +} diff --git a/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 00000000..38292315 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,290 @@ +'use strict' + +/* replacement start */ + +const process = require('process/') + +/* replacement end */ + +const { + aggregateTwoErrors, + codes: { ERR_MULTIPLE_CALLBACK }, + AbortError +} = require('../../ours/errors') +const { Symbol } = require('../../ours/primordials') +const { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require('./utils') +const kDestroy = Symbol('kDestroy') +const kConstruct = Symbol('kConstruct') +function checkError(err, w, r) { + if (err) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + err.stack // eslint-disable-line no-unused-expressions + + if (w && !w.errored) { + w.errored = err + } + if (r && !r.errored) { + r.errored = err + } + } +} + +// Backwards compat. cb() is undocumented and unused in core but +// unfortunately might be used by modules. +function destroy(err, cb) { + const r = this._readableState + const w = this._writableState + // With duplex streams we use the writable side for state. + const s = w || r + if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { + if (typeof cb === 'function') { + cb() + } + return this + } + + // We set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + checkError(err, w, r) + if (w) { + w.destroyed = true + } + if (r) { + r.destroyed = true + } + + // If still constructing then defer calling _destroy. + if (!s.constructed) { + this.once(kDestroy, function (er) { + _destroy(this, aggregateTwoErrors(er, err), cb) + }) + } else { + _destroy(this, err, cb) + } + return this +} +function _destroy(self, err, cb) { + let called = false + function onDestroy(err) { + if (called) { + return + } + called = true + const r = self._readableState + const w = self._writableState + checkError(err, w, r) + if (w) { + w.closed = true + } + if (r) { + r.closed = true + } + if (typeof cb === 'function') { + cb(err) + } + if (err) { + process.nextTick(emitErrorCloseNT, self, err) + } else { + process.nextTick(emitCloseNT, self) + } + } + try { + self._destroy(err || null, onDestroy) + } catch (err) { + onDestroy(err) + } +} +function emitErrorCloseNT(self, err) { + emitErrorNT(self, err) + emitCloseNT(self) +} +function emitCloseNT(self) { + const r = self._readableState + const w = self._writableState + if (w) { + w.closeEmitted = true + } + if (r) { + r.closeEmitted = true + } + if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) { + self.emit('close') + } +} +function emitErrorNT(self, err) { + const r = self._readableState + const w = self._writableState + if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) { + return + } + if (w) { + w.errorEmitted = true + } + if (r) { + r.errorEmitted = true + } + self.emit('error', err) +} +function undestroy() { + const r = this._readableState + const w = this._writableState + if (r) { + r.constructed = true + r.closed = false + r.closeEmitted = false + r.destroyed = false + r.errored = null + r.errorEmitted = false + r.reading = false + r.ended = r.readable === false + r.endEmitted = r.readable === false + } + if (w) { + w.constructed = true + w.destroyed = false + w.closed = false + w.closeEmitted = false + w.errored = null + w.errorEmitted = false + w.finalCalled = false + w.prefinished = false + w.ended = w.writable === false + w.ending = w.writable === false + w.finished = w.writable === false + } +} +function errorOrDestroy(stream, err, sync) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + const r = stream._readableState + const w = stream._writableState + if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { + return this + } + if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy)) + stream.destroy(err) + else if (err) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + err.stack // eslint-disable-line no-unused-expressions + + if (w && !w.errored) { + w.errored = err + } + if (r && !r.errored) { + r.errored = err + } + if (sync) { + process.nextTick(emitErrorNT, stream, err) + } else { + emitErrorNT(stream, err) + } + } +} +function construct(stream, cb) { + if (typeof stream._construct !== 'function') { + return + } + const r = stream._readableState + const w = stream._writableState + if (r) { + r.constructed = false + } + if (w) { + w.constructed = false + } + stream.once(kConstruct, cb) + if (stream.listenerCount(kConstruct) > 1) { + // Duplex + return + } + process.nextTick(constructNT, stream) +} +function constructNT(stream) { + let called = false + function onConstruct(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK()) + return + } + called = true + const r = stream._readableState + const w = stream._writableState + const s = w || r + if (r) { + r.constructed = true + } + if (w) { + w.constructed = true + } + if (s.destroyed) { + stream.emit(kDestroy, err) + } else if (err) { + errorOrDestroy(stream, err, true) + } else { + process.nextTick(emitConstructNT, stream) + } + } + try { + stream._construct((err) => { + process.nextTick(onConstruct, err) + }) + } catch (err) { + process.nextTick(onConstruct, err) + } +} +function emitConstructNT(stream) { + stream.emit(kConstruct) +} +function isRequest(stream) { + return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function' +} +function emitCloseLegacy(stream) { + stream.emit('close') +} +function emitErrorCloseLegacy(stream, err) { + stream.emit('error', err) + process.nextTick(emitCloseLegacy, stream) +} + +// Normalize destroy for legacy. +function destroyer(stream, err) { + if (!stream || isDestroyed(stream)) { + return + } + if (!err && !isFinished(stream)) { + err = new AbortError() + } + + // TODO: Remove isRequest branches. + if (isServerRequest(stream)) { + stream.socket = null + stream.destroy(err) + } else if (isRequest(stream)) { + stream.abort() + } else if (isRequest(stream.req)) { + stream.req.abort() + } else if (typeof stream.destroy === 'function') { + stream.destroy(err) + } else if (typeof stream.close === 'function') { + // TODO: Don't lose err? + stream.close() + } else if (err) { + process.nextTick(emitErrorCloseLegacy, stream, err) + } else { + process.nextTick(emitCloseLegacy, stream) + } + if (!stream.destroyed) { + stream[kIsDestroyed] = true + } +} +module.exports = { + construct, + destroyer, + destroy, + undestroy, + errorOrDestroy +} diff --git a/node_modules/readable-stream/lib/internal/streams/duplex.js b/node_modules/readable-stream/lib/internal/streams/duplex.js new file mode 100644 index 00000000..dd083967 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/duplex.js @@ -0,0 +1,143 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototype inheritance, this class +// prototypically inherits from Readable, and then parasitically from +// Writable. + +'use strict' + +const { + ObjectDefineProperties, + ObjectGetOwnPropertyDescriptor, + ObjectKeys, + ObjectSetPrototypeOf +} = require('../../ours/primordials') +module.exports = Duplex +const Readable = require('./readable') +const Writable = require('./writable') +ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype) +ObjectSetPrototypeOf(Duplex, Readable) +{ + const keys = ObjectKeys(Writable.prototype) + // Allow the keys array to be GC'ed. + for (let i = 0; i < keys.length; i++) { + const method = keys[i] + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method] + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options) + Readable.call(this, options) + Writable.call(this, options) + if (options) { + this.allowHalfOpen = options.allowHalfOpen !== false + if (options.readable === false) { + this._readableState.readable = false + this._readableState.ended = true + this._readableState.endEmitted = true + } + if (options.writable === false) { + this._writableState.writable = false + this._writableState.ending = true + this._writableState.ended = true + this._writableState.finished = true + } + } else { + this.allowHalfOpen = true + } +} +ObjectDefineProperties(Duplex.prototype, { + writable: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable') + }, + writableHighWaterMark: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark') + }, + writableObjectMode: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode') + }, + writableBuffer: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer') + }, + writableLength: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength') + }, + writableFinished: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished') + }, + writableCorked: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked') + }, + writableEnded: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded') + }, + writableNeedDrain: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain') + }, + destroyed: { + __proto__: null, + get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false + } + return this._readableState.destroyed && this._writableState.destroyed + }, + set(value) { + // Backward compatibility, the user is explicitly + // managing destroyed. + if (this._readableState && this._writableState) { + this._readableState.destroyed = value + this._writableState.destroyed = value + } + } + } +}) +let webStreamsAdapters + +// Lazy to avoid circular references +function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {} + return webStreamsAdapters +} +Duplex.fromWeb = function (pair, options) { + return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options) +} +Duplex.toWeb = function (duplex) { + return lazyWebStreams().newReadableWritablePairFromDuplex(duplex) +} +let duplexify +Duplex.from = function (body) { + if (!duplexify) { + duplexify = require('./duplexify') + } + return duplexify(body, 'body') +} diff --git a/node_modules/readable-stream/lib/internal/streams/duplexify.js b/node_modules/readable-stream/lib/internal/streams/duplexify.js new file mode 100644 index 00000000..05740d70 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/duplexify.js @@ -0,0 +1,378 @@ +/* replacement start */ + +const process = require('process/') + +/* replacement end */ + +;('use strict') +const bufferModule = require('buffer') +const { + isReadable, + isWritable, + isIterable, + isNodeStream, + isReadableNodeStream, + isWritableNodeStream, + isDuplexNodeStream, + isReadableStream, + isWritableStream +} = require('./utils') +const eos = require('./end-of-stream') +const { + AbortError, + codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE } +} = require('../../ours/errors') +const { destroyer } = require('./destroy') +const Duplex = require('./duplex') +const Readable = require('./readable') +const Writable = require('./writable') +const { createDeferredPromise } = require('../../ours/util') +const from = require('./from') +const Blob = globalThis.Blob || bufferModule.Blob +const isBlob = + typeof Blob !== 'undefined' + ? function isBlob(b) { + return b instanceof Blob + } + : function isBlob(b) { + return false + } +const AbortController = globalThis.AbortController || require('abort-controller').AbortController +const { FunctionPrototypeCall } = require('../../ours/primordials') + +// This is needed for pre node 17. +class Duplexify extends Duplex { + constructor(options) { + super(options) + + // https://github.com/nodejs/node/pull/34385 + + if ((options === null || options === undefined ? undefined : options.readable) === false) { + this._readableState.readable = false + this._readableState.ended = true + this._readableState.endEmitted = true + } + if ((options === null || options === undefined ? undefined : options.writable) === false) { + this._writableState.writable = false + this._writableState.ending = true + this._writableState.ended = true + this._writableState.finished = true + } + } +} +module.exports = function duplexify(body, name) { + if (isDuplexNodeStream(body)) { + return body + } + if (isReadableNodeStream(body)) { + return _duplexify({ + readable: body + }) + } + if (isWritableNodeStream(body)) { + return _duplexify({ + writable: body + }) + } + if (isNodeStream(body)) { + return _duplexify({ + writable: false, + readable: false + }) + } + if (isReadableStream(body)) { + return _duplexify({ + readable: Readable.fromWeb(body) + }) + } + if (isWritableStream(body)) { + return _duplexify({ + writable: Writable.fromWeb(body) + }) + } + if (typeof body === 'function') { + const { value, write, final, destroy } = fromAsyncGen(body) + if (isIterable(value)) { + return from(Duplexify, value, { + // TODO (ronag): highWaterMark? + objectMode: true, + write, + final, + destroy + }) + } + const then = value === null || value === undefined ? undefined : value.then + if (typeof then === 'function') { + let d + const promise = FunctionPrototypeCall( + then, + value, + (val) => { + if (val != null) { + throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val) + } + }, + (err) => { + destroyer(d, err) + } + ) + return (d = new Duplexify({ + // TODO (ronag): highWaterMark? + objectMode: true, + readable: false, + write, + final(cb) { + final(async () => { + try { + await promise + process.nextTick(cb, null) + } catch (err) { + process.nextTick(cb, err) + } + }) + }, + destroy + })) + } + throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value) + } + if (isBlob(body)) { + return duplexify(body.arrayBuffer()) + } + if (isIterable(body)) { + return from(Duplexify, body, { + // TODO (ronag): highWaterMark? + objectMode: true, + writable: false + }) + } + if ( + isReadableStream(body === null || body === undefined ? undefined : body.readable) && + isWritableStream(body === null || body === undefined ? undefined : body.writable) + ) { + return Duplexify.fromWeb(body) + } + if ( + typeof (body === null || body === undefined ? undefined : body.writable) === 'object' || + typeof (body === null || body === undefined ? undefined : body.readable) === 'object' + ) { + const readable = + body !== null && body !== undefined && body.readable + ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable) + ? body === null || body === undefined + ? undefined + : body.readable + : duplexify(body.readable) + : undefined + const writable = + body !== null && body !== undefined && body.writable + ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable) + ? body === null || body === undefined + ? undefined + : body.writable + : duplexify(body.writable) + : undefined + return _duplexify({ + readable, + writable + }) + } + const then = body === null || body === undefined ? undefined : body.then + if (typeof then === 'function') { + let d + FunctionPrototypeCall( + then, + body, + (val) => { + if (val != null) { + d.push(val) + } + d.push(null) + }, + (err) => { + destroyer(d, err) + } + ) + return (d = new Duplexify({ + objectMode: true, + writable: false, + read() {} + })) + } + throw new ERR_INVALID_ARG_TYPE( + name, + [ + 'Blob', + 'ReadableStream', + 'WritableStream', + 'Stream', + 'Iterable', + 'AsyncIterable', + 'Function', + '{ readable, writable } pair', + 'Promise' + ], + body + ) +} +function fromAsyncGen(fn) { + let { promise, resolve } = createDeferredPromise() + const ac = new AbortController() + const signal = ac.signal + const value = fn( + (async function* () { + while (true) { + const _promise = promise + promise = null + const { chunk, done, cb } = await _promise + process.nextTick(cb) + if (done) return + if (signal.aborted) + throw new AbortError(undefined, { + cause: signal.reason + }) + ;({ promise, resolve } = createDeferredPromise()) + yield chunk + } + })(), + { + signal + } + ) + return { + value, + write(chunk, encoding, cb) { + const _resolve = resolve + resolve = null + _resolve({ + chunk, + done: false, + cb + }) + }, + final(cb) { + const _resolve = resolve + resolve = null + _resolve({ + done: true, + cb + }) + }, + destroy(err, cb) { + ac.abort() + cb(err) + } + } +} +function _duplexify(pair) { + const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable + const w = pair.writable + let readable = !!isReadable(r) + let writable = !!isWritable(w) + let ondrain + let onfinish + let onreadable + let onclose + let d + function onfinished(err) { + const cb = onclose + onclose = null + if (cb) { + cb(err) + } else if (err) { + d.destroy(err) + } + } + + // TODO(ronag): Avoid double buffering. + // Implement Writable/Readable/Duplex traits. + // See, https://github.com/nodejs/node/pull/33515. + d = new Duplexify({ + // TODO (ronag): highWaterMark? + readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode), + writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode), + readable, + writable + }) + if (writable) { + eos(w, (err) => { + writable = false + if (err) { + destroyer(r, err) + } + onfinished(err) + }) + d._write = function (chunk, encoding, callback) { + if (w.write(chunk, encoding)) { + callback() + } else { + ondrain = callback + } + } + d._final = function (callback) { + w.end() + onfinish = callback + } + w.on('drain', function () { + if (ondrain) { + const cb = ondrain + ondrain = null + cb() + } + }) + w.on('finish', function () { + if (onfinish) { + const cb = onfinish + onfinish = null + cb() + } + }) + } + if (readable) { + eos(r, (err) => { + readable = false + if (err) { + destroyer(r, err) + } + onfinished(err) + }) + r.on('readable', function () { + if (onreadable) { + const cb = onreadable + onreadable = null + cb() + } + }) + r.on('end', function () { + d.push(null) + }) + d._read = function () { + while (true) { + const buf = r.read() + if (buf === null) { + onreadable = d._read + return + } + if (!d.push(buf)) { + return + } + } + } + } + d._destroy = function (err, callback) { + if (!err && onclose !== null) { + err = new AbortError() + } + onreadable = null + ondrain = null + onfinish = null + if (onclose === null) { + callback(err) + } else { + onclose = callback + destroyer(w, err) + destroyer(r, err) + } + } + return d +} diff --git a/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 00000000..94d18321 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,286 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict' + +/* replacement start */ + +const process = require('process/') + +/* replacement end */ + +const { AbortError, codes } = require('../../ours/errors') +const { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes +const { kEmptyObject, once } = require('../../ours/util') +const { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require('../validators') +const { Promise, PromisePrototypeThen, SymbolDispose } = require('../../ours/primordials') +const { + isClosed, + isReadable, + isReadableNodeStream, + isReadableStream, + isReadableFinished, + isReadableErrored, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableFinished, + isWritableErrored, + isNodeStream, + willEmitClose: _willEmitClose, + kIsClosedPromise +} = require('./utils') +let addAbortListener +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function' +} +const nop = () => {} +function eos(stream, options, callback) { + var _options$readable, _options$writable + if (arguments.length === 2) { + callback = options + options = kEmptyObject + } else if (options == null) { + options = kEmptyObject + } else { + validateObject(options, 'options') + } + validateFunction(callback, 'callback') + validateAbortSignal(options.signal, 'options.signal') + callback = once(callback) + if (isReadableStream(stream) || isWritableStream(stream)) { + return eosWeb(stream, options, callback) + } + if (!isNodeStream(stream)) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) + } + const readable = + (_options$readable = options.readable) !== null && _options$readable !== undefined + ? _options$readable + : isReadableNodeStream(stream) + const writable = + (_options$writable = options.writable) !== null && _options$writable !== undefined + ? _options$writable + : isWritableNodeStream(stream) + const wState = stream._writableState + const rState = stream._readableState + const onlegacyfinish = () => { + if (!stream.writable) { + onfinish() + } + } + + // TODO (ronag): Improve soft detection to include core modules and + // common ecosystem modules that do properly emit 'close' but fail + // this generic check. + let willEmitClose = + _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable + let writableFinished = isWritableFinished(stream, false) + const onfinish = () => { + writableFinished = true + // Stream should not be destroyed here. If it is that + // means that user space is doing something differently and + // we cannot trust willEmitClose. + if (stream.destroyed) { + willEmitClose = false + } + if (willEmitClose && (!stream.readable || readable)) { + return + } + if (!readable || readableFinished) { + callback.call(stream) + } + } + let readableFinished = isReadableFinished(stream, false) + const onend = () => { + readableFinished = true + // Stream should not be destroyed here. If it is that + // means that user space is doing something differently and + // we cannot trust willEmitClose. + if (stream.destroyed) { + willEmitClose = false + } + if (willEmitClose && (!stream.writable || writable)) { + return + } + if (!writable || writableFinished) { + callback.call(stream) + } + } + const onerror = (err) => { + callback.call(stream, err) + } + let closed = isClosed(stream) + const onclose = () => { + closed = true + const errored = isWritableErrored(stream) || isReadableErrored(stream) + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored) + } + if (readable && !readableFinished && isReadableNodeStream(stream, true)) { + if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) + } + if (writable && !writableFinished) { + if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) + } + callback.call(stream) + } + const onclosed = () => { + closed = true + const errored = isWritableErrored(stream) || isReadableErrored(stream) + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored) + } + callback.call(stream) + } + const onrequest = () => { + stream.req.on('finish', onfinish) + } + if (isRequest(stream)) { + stream.on('complete', onfinish) + if (!willEmitClose) { + stream.on('abort', onclose) + } + if (stream.req) { + onrequest() + } else { + stream.on('request', onrequest) + } + } else if (writable && !wState) { + // legacy streams + stream.on('end', onlegacyfinish) + stream.on('close', onlegacyfinish) + } + + // Not all streams will emit 'close' after 'aborted'. + if (!willEmitClose && typeof stream.aborted === 'boolean') { + stream.on('aborted', onclose) + } + stream.on('end', onend) + stream.on('finish', onfinish) + if (options.error !== false) { + stream.on('error', onerror) + } + stream.on('close', onclose) + if (closed) { + process.nextTick(onclose) + } else if ( + (wState !== null && wState !== undefined && wState.errorEmitted) || + (rState !== null && rState !== undefined && rState.errorEmitted) + ) { + if (!willEmitClose) { + process.nextTick(onclosed) + } + } else if ( + !readable && + (!willEmitClose || isReadable(stream)) && + (writableFinished || isWritable(stream) === false) + ) { + process.nextTick(onclosed) + } else if ( + !writable && + (!willEmitClose || isWritable(stream)) && + (readableFinished || isReadable(stream) === false) + ) { + process.nextTick(onclosed) + } else if (rState && stream.req && stream.aborted) { + process.nextTick(onclosed) + } + const cleanup = () => { + callback = nop + stream.removeListener('aborted', onclose) + stream.removeListener('complete', onfinish) + stream.removeListener('abort', onclose) + stream.removeListener('request', onrequest) + if (stream.req) stream.req.removeListener('finish', onfinish) + stream.removeListener('end', onlegacyfinish) + stream.removeListener('close', onlegacyfinish) + stream.removeListener('finish', onfinish) + stream.removeListener('end', onend) + stream.removeListener('error', onerror) + stream.removeListener('close', onclose) + } + if (options.signal && !closed) { + const abort = () => { + // Keep it because cleanup removes it. + const endCallback = callback + cleanup() + endCallback.call( + stream, + new AbortError(undefined, { + cause: options.signal.reason + }) + ) + } + if (options.signal.aborted) { + process.nextTick(abort) + } else { + addAbortListener = addAbortListener || require('../../ours/util').addAbortListener + const disposable = addAbortListener(options.signal, abort) + const originalCallback = callback + callback = once((...args) => { + disposable[SymbolDispose]() + originalCallback.apply(stream, args) + }) + } + } + return cleanup +} +function eosWeb(stream, options, callback) { + let isAborted = false + let abort = nop + if (options.signal) { + abort = () => { + isAborted = true + callback.call( + stream, + new AbortError(undefined, { + cause: options.signal.reason + }) + ) + } + if (options.signal.aborted) { + process.nextTick(abort) + } else { + addAbortListener = addAbortListener || require('../../ours/util').addAbortListener + const disposable = addAbortListener(options.signal, abort) + const originalCallback = callback + callback = once((...args) => { + disposable[SymbolDispose]() + originalCallback.apply(stream, args) + }) + } + } + const resolverFn = (...args) => { + if (!isAborted) { + process.nextTick(() => callback.apply(stream, args)) + } + } + PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn) + return nop +} +function finished(stream, opts) { + var _opts + let autoCleanup = false + if (opts === null) { + opts = kEmptyObject + } + if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) { + validateBoolean(opts.cleanup, 'cleanup') + autoCleanup = opts.cleanup + } + return new Promise((resolve, reject) => { + const cleanup = eos(stream, opts, (err) => { + if (autoCleanup) { + cleanup() + } + if (err) { + reject(err) + } else { + resolve() + } + }) + }) +} +module.exports = eos +module.exports.finished = finished diff --git a/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 00000000..c7e75314 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,98 @@ +'use strict' + +/* replacement start */ + +const process = require('process/') + +/* replacement end */ + +const { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require('../../ours/primordials') +const { Buffer } = require('buffer') +const { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = require('../../ours/errors').codes +function from(Readable, iterable, opts) { + let iterator + if (typeof iterable === 'string' || iterable instanceof Buffer) { + return new Readable({ + objectMode: true, + ...opts, + read() { + this.push(iterable) + this.push(null) + } + }) + } + let isAsync + if (iterable && iterable[SymbolAsyncIterator]) { + isAsync = true + iterator = iterable[SymbolAsyncIterator]() + } else if (iterable && iterable[SymbolIterator]) { + isAsync = false + iterator = iterable[SymbolIterator]() + } else { + throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable) + } + const readable = new Readable({ + objectMode: true, + highWaterMark: 1, + // TODO(ronag): What options should be allowed? + ...opts + }) + + // Flag to protect against _read + // being called before last iteration completion. + let reading = false + readable._read = function () { + if (!reading) { + reading = true + next() + } + } + readable._destroy = function (error, cb) { + PromisePrototypeThen( + close(error), + () => process.nextTick(cb, error), + // nextTick is here in case cb throws + (e) => process.nextTick(cb, e || error) + ) + } + async function close(error) { + const hadError = error !== undefined && error !== null + const hasThrow = typeof iterator.throw === 'function' + if (hadError && hasThrow) { + const { value, done } = await iterator.throw(error) + await value + if (done) { + return + } + } + if (typeof iterator.return === 'function') { + const { value } = await iterator.return() + await value + } + } + async function next() { + for (;;) { + try { + const { value, done } = isAsync ? await iterator.next() : iterator.next() + if (done) { + readable.push(null) + } else { + const res = value && typeof value.then === 'function' ? await value : value + if (res === null) { + reading = false + throw new ERR_STREAM_NULL_VALUES() + } else if (readable.push(res)) { + continue + } else { + reading = false + } + } + } catch (err) { + readable.destroy(err) + } + break + } + } + return readable +} +module.exports = from diff --git a/node_modules/readable-stream/lib/internal/streams/lazy_transform.js b/node_modules/readable-stream/lib/internal/streams/lazy_transform.js new file mode 100644 index 00000000..439461a1 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/lazy_transform.js @@ -0,0 +1,51 @@ +// LazyTransform is a special type of Transform stream that is lazily loaded. +// This is used for performance with bi-API-ship: when two APIs are available +// for the stream, one conventional and one non-conventional. +'use strict' + +const { ObjectDefineProperties, ObjectDefineProperty, ObjectSetPrototypeOf } = require('../../ours/primordials') +const stream = require('../../stream') +const { getDefaultEncoding } = require('../crypto/util') +module.exports = LazyTransform +function LazyTransform(options) { + this._options = options +} +ObjectSetPrototypeOf(LazyTransform.prototype, stream.Transform.prototype) +ObjectSetPrototypeOf(LazyTransform, stream.Transform) +function makeGetter(name) { + return function () { + stream.Transform.call(this, this._options) + this._writableState.decodeStrings = false + if (!this._options || !this._options.defaultEncoding) { + this._writableState.defaultEncoding = getDefaultEncoding() + } + return this[name] + } +} +function makeSetter(name) { + return function (val) { + ObjectDefineProperty(this, name, { + __proto__: null, + value: val, + enumerable: true, + configurable: true, + writable: true + }) + } +} +ObjectDefineProperties(LazyTransform.prototype, { + _readableState: { + __proto__: null, + get: makeGetter('_readableState'), + set: makeSetter('_readableState'), + configurable: true, + enumerable: true + }, + _writableState: { + __proto__: null, + get: makeGetter('_writableState'), + set: makeSetter('_writableState'), + configurable: true, + enumerable: true + } +}) diff --git a/node_modules/readable-stream/lib/internal/streams/legacy.js b/node_modules/readable-stream/lib/internal/streams/legacy.js new file mode 100644 index 00000000..d492f7ff --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/legacy.js @@ -0,0 +1,89 @@ +'use strict' + +const { ArrayIsArray, ObjectSetPrototypeOf } = require('../../ours/primordials') +const { EventEmitter: EE } = require('events') +function Stream(opts) { + EE.call(this, opts) +} +ObjectSetPrototypeOf(Stream.prototype, EE.prototype) +ObjectSetPrototypeOf(Stream, EE) +Stream.prototype.pipe = function (dest, options) { + const source = this + function ondata(chunk) { + if (dest.writable && dest.write(chunk) === false && source.pause) { + source.pause() + } + } + source.on('data', ondata) + function ondrain() { + if (source.readable && source.resume) { + source.resume() + } + } + dest.on('drain', ondrain) + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend) + source.on('close', onclose) + } + let didOnEnd = false + function onend() { + if (didOnEnd) return + didOnEnd = true + dest.end() + } + function onclose() { + if (didOnEnd) return + didOnEnd = true + if (typeof dest.destroy === 'function') dest.destroy() + } + + // Don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup() + if (EE.listenerCount(this, 'error') === 0) { + this.emit('error', er) + } + } + prependListener(source, 'error', onerror) + prependListener(dest, 'error', onerror) + + // Remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata) + dest.removeListener('drain', ondrain) + source.removeListener('end', onend) + source.removeListener('close', onclose) + source.removeListener('error', onerror) + dest.removeListener('error', onerror) + source.removeListener('end', cleanup) + source.removeListener('close', cleanup) + dest.removeListener('close', cleanup) + } + source.on('end', cleanup) + source.on('close', cleanup) + dest.on('close', cleanup) + dest.emit('pipe', source) + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest +} +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn) + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn) + else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn) + else emitter._events[event] = [fn, emitter._events[event]] +} +module.exports = { + Stream, + prependListener +} diff --git a/node_modules/readable-stream/lib/internal/streams/operators.js b/node_modules/readable-stream/lib/internal/streams/operators.js new file mode 100644 index 00000000..7eff1104 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/operators.js @@ -0,0 +1,457 @@ +'use strict' + +const AbortController = globalThis.AbortController || require('abort-controller').AbortController +const { + codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, + AbortError +} = require('../../ours/errors') +const { validateAbortSignal, validateInteger, validateObject } = require('../validators') +const kWeakHandler = require('../../ours/primordials').Symbol('kWeak') +const kResistStopPropagation = require('../../ours/primordials').Symbol('kResistStopPropagation') +const { finished } = require('./end-of-stream') +const staticCompose = require('./compose') +const { addAbortSignalNoValidate } = require('./add-abort-signal') +const { isWritable, isNodeStream } = require('./utils') +const { deprecate } = require('../../ours/util') +const { + ArrayPrototypePush, + Boolean, + MathFloor, + Number, + NumberIsNaN, + Promise, + PromiseReject, + PromiseResolve, + PromisePrototypeThen, + Symbol +} = require('../../ours/primordials') +const kEmpty = Symbol('kEmpty') +const kEof = Symbol('kEof') +function compose(stream, options) { + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + if (isNodeStream(stream) && !isWritable(stream)) { + throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable') + } + const composedStream = staticCompose(this, stream) + if (options !== null && options !== undefined && options.signal) { + // Not validating as we already validated before + addAbortSignalNoValidate(options.signal, composedStream) + } + return composedStream +} +function map(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + let concurrency = 1 + if ((options === null || options === undefined ? undefined : options.concurrency) != null) { + concurrency = MathFloor(options.concurrency) + } + let highWaterMark = concurrency - 1 + if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) { + highWaterMark = MathFloor(options.highWaterMark) + } + validateInteger(concurrency, 'options.concurrency', 1) + validateInteger(highWaterMark, 'options.highWaterMark', 0) + highWaterMark += concurrency + return async function* map() { + const signal = require('../../ours/util').AbortSignalAny( + [options === null || options === undefined ? undefined : options.signal].filter(Boolean) + ) + const stream = this + const queue = [] + const signalOpt = { + signal + } + let next + let resume + let done = false + let cnt = 0 + function onCatch() { + done = true + afterItemProcessed() + } + function afterItemProcessed() { + cnt -= 1 + maybeResume() + } + function maybeResume() { + if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { + resume() + resume = null + } + } + async function pump() { + try { + for await (let val of stream) { + if (done) { + return + } + if (signal.aborted) { + throw new AbortError() + } + try { + val = fn(val, signalOpt) + if (val === kEmpty) { + continue + } + val = PromiseResolve(val) + } catch (err) { + val = PromiseReject(err) + } + cnt += 1 + PromisePrototypeThen(val, afterItemProcessed, onCatch) + queue.push(val) + if (next) { + next() + next = null + } + if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { + await new Promise((resolve) => { + resume = resolve + }) + } + } + queue.push(kEof) + } catch (err) { + const val = PromiseReject(err) + PromisePrototypeThen(val, afterItemProcessed, onCatch) + queue.push(val) + } finally { + done = true + if (next) { + next() + next = null + } + } + } + pump() + try { + while (true) { + while (queue.length > 0) { + const val = await queue[0] + if (val === kEof) { + return + } + if (signal.aborted) { + throw new AbortError() + } + if (val !== kEmpty) { + yield val + } + queue.shift() + maybeResume() + } + await new Promise((resolve) => { + next = resolve + }) + } + } finally { + done = true + if (resume) { + resume() + resume = null + } + } + }.call(this) +} +function asIndexedPairs(options = undefined) { + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + return async function* asIndexedPairs() { + let index = 0 + for await (const val of this) { + var _options$signal + if ( + options !== null && + options !== undefined && + (_options$signal = options.signal) !== null && + _options$signal !== undefined && + _options$signal.aborted + ) { + throw new AbortError({ + cause: options.signal.reason + }) + } + yield [index++, val] + } + }.call(this) +} +async function some(fn, options = undefined) { + for await (const unused of filter.call(this, fn, options)) { + return true + } + return false +} +async function every(fn, options = undefined) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + // https://en.wikipedia.org/wiki/De_Morgan%27s_laws + return !(await some.call( + this, + async (...args) => { + return !(await fn(...args)) + }, + options + )) +} +async function find(fn, options) { + for await (const result of filter.call(this, fn, options)) { + return result + } + return undefined +} +async function forEach(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + async function forEachFn(value, options) { + await fn(value, options) + return kEmpty + } + // eslint-disable-next-line no-unused-vars + for await (const unused of map.call(this, forEachFn, options)); +} +function filter(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + async function filterFn(value, options) { + if (await fn(value, options)) { + return value + } + return kEmpty + } + return map.call(this, filterFn, options) +} + +// Specific to provide better error to reduce since the argument is only +// missing if the stream has no items in it - but the code is still appropriate +class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS { + constructor() { + super('reduce') + this.message = 'Reduce of an empty stream requires an initial value' + } +} +async function reduce(reducer, initialValue, options) { + var _options$signal2 + if (typeof reducer !== 'function') { + throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer) + } + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + let hasInitialValue = arguments.length > 1 + if ( + options !== null && + options !== undefined && + (_options$signal2 = options.signal) !== null && + _options$signal2 !== undefined && + _options$signal2.aborted + ) { + const err = new AbortError(undefined, { + cause: options.signal.reason + }) + this.once('error', () => {}) // The error is already propagated + await finished(this.destroy(err)) + throw err + } + const ac = new AbortController() + const signal = ac.signal + if (options !== null && options !== undefined && options.signal) { + const opts = { + once: true, + [kWeakHandler]: this, + [kResistStopPropagation]: true + } + options.signal.addEventListener('abort', () => ac.abort(), opts) + } + let gotAnyItemFromStream = false + try { + for await (const value of this) { + var _options$signal3 + gotAnyItemFromStream = true + if ( + options !== null && + options !== undefined && + (_options$signal3 = options.signal) !== null && + _options$signal3 !== undefined && + _options$signal3.aborted + ) { + throw new AbortError() + } + if (!hasInitialValue) { + initialValue = value + hasInitialValue = true + } else { + initialValue = await reducer(initialValue, value, { + signal + }) + } + } + if (!gotAnyItemFromStream && !hasInitialValue) { + throw new ReduceAwareErrMissingArgs() + } + } finally { + ac.abort() + } + return initialValue +} +async function toArray(options) { + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + const result = [] + for await (const val of this) { + var _options$signal4 + if ( + options !== null && + options !== undefined && + (_options$signal4 = options.signal) !== null && + _options$signal4 !== undefined && + _options$signal4.aborted + ) { + throw new AbortError(undefined, { + cause: options.signal.reason + }) + } + ArrayPrototypePush(result, val) + } + return result +} +function flatMap(fn, options) { + const values = map.call(this, fn, options) + return async function* flatMap() { + for await (const val of values) { + yield* val + } + }.call(this) +} +function toIntegerOrInfinity(number) { + // We coerce here to align with the spec + // https://github.com/tc39/proposal-iterator-helpers/issues/169 + number = Number(number) + if (NumberIsNaN(number)) { + return 0 + } + if (number < 0) { + throw new ERR_OUT_OF_RANGE('number', '>= 0', number) + } + return number +} +function drop(number, options = undefined) { + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + number = toIntegerOrInfinity(number) + return async function* drop() { + var _options$signal5 + if ( + options !== null && + options !== undefined && + (_options$signal5 = options.signal) !== null && + _options$signal5 !== undefined && + _options$signal5.aborted + ) { + throw new AbortError() + } + for await (const val of this) { + var _options$signal6 + if ( + options !== null && + options !== undefined && + (_options$signal6 = options.signal) !== null && + _options$signal6 !== undefined && + _options$signal6.aborted + ) { + throw new AbortError() + } + if (number-- <= 0) { + yield val + } + } + }.call(this) +} +function take(number, options = undefined) { + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + number = toIntegerOrInfinity(number) + return async function* take() { + var _options$signal7 + if ( + options !== null && + options !== undefined && + (_options$signal7 = options.signal) !== null && + _options$signal7 !== undefined && + _options$signal7.aborted + ) { + throw new AbortError() + } + for await (const val of this) { + var _options$signal8 + if ( + options !== null && + options !== undefined && + (_options$signal8 = options.signal) !== null && + _options$signal8 !== undefined && + _options$signal8.aborted + ) { + throw new AbortError() + } + if (number-- > 0) { + yield val + } + + // Don't get another item from iterator in case we reached the end + if (number <= 0) { + return + } + } + }.call(this) +} +module.exports.streamReturningOperators = { + asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'), + drop, + filter, + flatMap, + map, + take, + compose +} +module.exports.promiseReturningOperators = { + every, + forEach, + reduce, + toArray, + some, + find +} diff --git a/node_modules/readable-stream/lib/internal/streams/passthrough.js b/node_modules/readable-stream/lib/internal/streams/passthrough.js new file mode 100644 index 00000000..ed4f486c --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/passthrough.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict' + +const { ObjectSetPrototypeOf } = require('../../ours/primordials') +module.exports = PassThrough +const Transform = require('./transform') +ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype) +ObjectSetPrototypeOf(PassThrough, Transform) +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options) + Transform.call(this, options) +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk) +} diff --git a/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 00000000..a2bab880 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,471 @@ +/* replacement start */ + +const process = require('process/') + +/* replacement end */ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +;('use strict') +const { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = require('../../ours/primordials') +const eos = require('./end-of-stream') +const { once } = require('../../ours/util') +const destroyImpl = require('./destroy') +const Duplex = require('./duplex') +const { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_RETURN_VALUE, + ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED, + ERR_STREAM_PREMATURE_CLOSE + }, + AbortError +} = require('../../ours/errors') +const { validateFunction, validateAbortSignal } = require('../validators') +const { + isIterable, + isReadable, + isReadableNodeStream, + isNodeStream, + isTransformStream, + isWebStream, + isReadableStream, + isReadableFinished +} = require('./utils') +const AbortController = globalThis.AbortController || require('abort-controller').AbortController +let PassThrough +let Readable +let addAbortListener +function destroyer(stream, reading, writing) { + let finished = false + stream.on('close', () => { + finished = true + }) + const cleanup = eos( + stream, + { + readable: reading, + writable: writing + }, + (err) => { + finished = !err + } + ) + return { + destroy: (err) => { + if (finished) return + finished = true + destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe')) + }, + cleanup + } +} +function popCallback(streams) { + // Streams should never be an empty array. It should always contain at least + // a single stream. Therefore optimize for the average case instead of + // checking for length === 0 as well. + validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]') + return streams.pop() +} +function makeAsyncIterable(val) { + if (isIterable(val)) { + return val + } else if (isReadableNodeStream(val)) { + // Legacy streams are not Iterable. + return fromReadable(val) + } + throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val) +} +async function* fromReadable(val) { + if (!Readable) { + Readable = require('./readable') + } + yield* Readable.prototype[SymbolAsyncIterator].call(val) +} +async function pumpToNode(iterable, writable, finish, { end }) { + let error + let onresolve = null + const resume = (err) => { + if (err) { + error = err + } + if (onresolve) { + const callback = onresolve + onresolve = null + callback() + } + } + const wait = () => + new Promise((resolve, reject) => { + if (error) { + reject(error) + } else { + onresolve = () => { + if (error) { + reject(error) + } else { + resolve() + } + } + } + }) + writable.on('drain', resume) + const cleanup = eos( + writable, + { + readable: false + }, + resume + ) + try { + if (writable.writableNeedDrain) { + await wait() + } + for await (const chunk of iterable) { + if (!writable.write(chunk)) { + await wait() + } + } + if (end) { + writable.end() + await wait() + } + finish() + } catch (err) { + finish(error !== err ? aggregateTwoErrors(error, err) : err) + } finally { + cleanup() + writable.off('drain', resume) + } +} +async function pumpToWeb(readable, writable, finish, { end }) { + if (isTransformStream(writable)) { + writable = writable.writable + } + // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure + const writer = writable.getWriter() + try { + for await (const chunk of readable) { + await writer.ready + writer.write(chunk).catch(() => {}) + } + await writer.ready + if (end) { + await writer.close() + } + finish() + } catch (err) { + try { + await writer.abort(err) + finish(err) + } catch (err) { + finish(err) + } + } +} +function pipeline(...streams) { + return pipelineImpl(streams, once(popCallback(streams))) +} +function pipelineImpl(streams, callback, opts) { + if (streams.length === 1 && ArrayIsArray(streams[0])) { + streams = streams[0] + } + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams') + } + const ac = new AbortController() + const signal = ac.signal + const outerSignal = opts === null || opts === undefined ? undefined : opts.signal + + // Need to cleanup event listeners if last stream is readable + // https://github.com/nodejs/node/issues/35452 + const lastStreamCleanup = [] + validateAbortSignal(outerSignal, 'options.signal') + function abort() { + finishImpl(new AbortError()) + } + addAbortListener = addAbortListener || require('../../ours/util').addAbortListener + let disposable + if (outerSignal) { + disposable = addAbortListener(outerSignal, abort) + } + let error + let value + const destroys = [] + let finishCount = 0 + function finish(err) { + finishImpl(err, --finishCount === 0) + } + function finishImpl(err, final) { + var _disposable + if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) { + error = err + } + if (!error && !final) { + return + } + while (destroys.length) { + destroys.shift()(error) + } + ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]() + ac.abort() + if (final) { + if (!error) { + lastStreamCleanup.forEach((fn) => fn()) + } + process.nextTick(callback, error, value) + } + } + let ret + for (let i = 0; i < streams.length; i++) { + const stream = streams[i] + const reading = i < streams.length - 1 + const writing = i > 0 + const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false + const isLastStream = i === streams.length - 1 + if (isNodeStream(stream)) { + if (end) { + const { destroy, cleanup } = destroyer(stream, reading, writing) + destroys.push(destroy) + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(cleanup) + } + } + + // Catch stream errors that occur after pipe/pump has completed. + function onError(err) { + if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + finish(err) + } + } + stream.on('error', onError) + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(() => { + stream.removeListener('error', onError) + }) + } + } + if (i === 0) { + if (typeof stream === 'function') { + ret = stream({ + signal + }) + if (!isIterable(ret)) { + throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret) + } + } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) { + ret = stream + } else { + ret = Duplex.from(stream) + } + } else if (typeof stream === 'function') { + if (isTransformStream(ret)) { + var _ret + ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable) + } else { + ret = makeAsyncIterable(ret) + } + ret = stream(ret, { + signal + }) + if (reading) { + if (!isIterable(ret, true)) { + throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret) + } + } else { + var _ret2 + if (!PassThrough) { + PassThrough = require('./passthrough') + } + + // If the last argument to pipeline is not a stream + // we must create a proxy stream so that pipeline(...) + // always returns a stream which can be further + // composed through `.pipe(stream)`. + + const pt = new PassThrough({ + objectMode: true + }) + + // Handle Promises/A+ spec, `then` could be a getter that throws on + // second use. + const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then + if (typeof then === 'function') { + finishCount++ + then.call( + ret, + (val) => { + value = val + if (val != null) { + pt.write(val) + } + if (end) { + pt.end() + } + process.nextTick(finish) + }, + (err) => { + pt.destroy(err) + process.nextTick(finish, err) + } + ) + } else if (isIterable(ret, true)) { + finishCount++ + pumpToNode(ret, pt, finish, { + end + }) + } else if (isReadableStream(ret) || isTransformStream(ret)) { + const toRead = ret.readable || ret + finishCount++ + pumpToNode(toRead, pt, finish, { + end + }) + } else { + throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret) + } + ret = pt + const { destroy, cleanup } = destroyer(ret, false, true) + destroys.push(destroy) + if (isLastStream) { + lastStreamCleanup.push(cleanup) + } + } + } else if (isNodeStream(stream)) { + if (isReadableNodeStream(ret)) { + finishCount += 2 + const cleanup = pipe(ret, stream, finish, { + end + }) + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(cleanup) + } + } else if (isTransformStream(ret) || isReadableStream(ret)) { + const toRead = ret.readable || ret + finishCount++ + pumpToNode(toRead, stream, finish, { + end + }) + } else if (isIterable(ret)) { + finishCount++ + pumpToNode(ret, stream, finish, { + end + }) + } else { + throw new ERR_INVALID_ARG_TYPE( + 'val', + ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], + ret + ) + } + ret = stream + } else if (isWebStream(stream)) { + if (isReadableNodeStream(ret)) { + finishCount++ + pumpToWeb(makeAsyncIterable(ret), stream, finish, { + end + }) + } else if (isReadableStream(ret) || isIterable(ret)) { + finishCount++ + pumpToWeb(ret, stream, finish, { + end + }) + } else if (isTransformStream(ret)) { + finishCount++ + pumpToWeb(ret.readable, stream, finish, { + end + }) + } else { + throw new ERR_INVALID_ARG_TYPE( + 'val', + ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], + ret + ) + } + ret = stream + } else { + ret = Duplex.from(stream) + } + } + if ( + (signal !== null && signal !== undefined && signal.aborted) || + (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted) + ) { + process.nextTick(abort) + } + return ret +} +function pipe(src, dst, finish, { end }) { + let ended = false + dst.on('close', () => { + if (!ended) { + // Finish if the destination closes before the source has completed. + finish(new ERR_STREAM_PREMATURE_CLOSE()) + } + }) + src.pipe(dst, { + end: false + }) // If end is true we already will have a listener to end dst. + + if (end) { + // Compat. Before node v10.12.0 stdio used to throw an error so + // pipe() did/does not end() stdio destinations. + // Now they allow it but "secretly" don't close the underlying fd. + + function endFn() { + ended = true + dst.end() + } + if (isReadableFinished(src)) { + // End the destination if the source has already ended. + process.nextTick(endFn) + } else { + src.once('end', endFn) + } + } else { + finish() + } + eos( + src, + { + readable: true, + writable: false + }, + (err) => { + const rState = src._readableState + if ( + err && + err.code === 'ERR_STREAM_PREMATURE_CLOSE' && + rState && + rState.ended && + !rState.errored && + !rState.errorEmitted + ) { + // Some readable streams will emit 'close' before 'end'. However, since + // this is on the readable side 'end' should still be emitted if the + // stream has been ended and no error emitted. This should be allowed in + // favor of backwards compatibility. Since the stream is piped to a + // destination this should not result in any observable difference. + // We don't need to check if this is a writable premature close since + // eos will only fail with premature close on the reading side for + // duplex streams. + src.once('end', finish).once('error', finish) + } else { + finish(err) + } + } + ) + return eos( + dst, + { + readable: false, + writable: true + }, + finish + ) +} +module.exports = { + pipelineImpl, + pipeline +} diff --git a/node_modules/readable-stream/lib/internal/streams/readable.js b/node_modules/readable-stream/lib/internal/streams/readable.js new file mode 100644 index 00000000..90c73160 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/readable.js @@ -0,0 +1,1290 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict' + +/* replacement start */ + +const process = require('process/') + +/* replacement end */ + +const { + ArrayPrototypeIndexOf, + NumberIsInteger, + NumberIsNaN, + NumberParseInt, + ObjectDefineProperties, + ObjectKeys, + ObjectSetPrototypeOf, + Promise, + SafeSet, + SymbolAsyncDispose, + SymbolAsyncIterator, + Symbol +} = require('../../ours/primordials') +module.exports = Readable +Readable.ReadableState = ReadableState +const { EventEmitter: EE } = require('events') +const { Stream, prependListener } = require('./legacy') +const { Buffer } = require('buffer') +const { addAbortSignal } = require('./add-abort-signal') +const eos = require('./end-of-stream') +let debug = require('../../ours/util').debuglog('stream', (fn) => { + debug = fn +}) +const BufferList = require('./buffer_list') +const destroyImpl = require('./destroy') +const { getHighWaterMark, getDefaultHighWaterMark } = require('./state') +const { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_OUT_OF_RANGE, + ERR_STREAM_PUSH_AFTER_EOF, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT + }, + AbortError +} = require('../../ours/errors') +const { validateObject } = require('../validators') +const kPaused = Symbol('kPaused') +const { StringDecoder } = require('string_decoder/') +const from = require('./from') +ObjectSetPrototypeOf(Readable.prototype, Stream.prototype) +ObjectSetPrototypeOf(Readable, Stream) +const nop = () => {} +const { errorOrDestroy } = destroyImpl +const kObjectMode = 1 << 0 +const kEnded = 1 << 1 +const kEndEmitted = 1 << 2 +const kReading = 1 << 3 +const kConstructed = 1 << 4 +const kSync = 1 << 5 +const kNeedReadable = 1 << 6 +const kEmittedReadable = 1 << 7 +const kReadableListening = 1 << 8 +const kResumeScheduled = 1 << 9 +const kErrorEmitted = 1 << 10 +const kEmitClose = 1 << 11 +const kAutoDestroy = 1 << 12 +const kDestroyed = 1 << 13 +const kClosed = 1 << 14 +const kCloseEmitted = 1 << 15 +const kMultiAwaitDrain = 1 << 16 +const kReadingMore = 1 << 17 +const kDataEmitted = 1 << 18 + +// TODO(benjamingr) it is likely slower to do it this way than with free functions +function makeBitMapDescriptor(bit) { + return { + enumerable: false, + get() { + return (this.state & bit) !== 0 + }, + set(value) { + if (value) this.state |= bit + else this.state &= ~bit + } + } +} +ObjectDefineProperties(ReadableState.prototype, { + objectMode: makeBitMapDescriptor(kObjectMode), + ended: makeBitMapDescriptor(kEnded), + endEmitted: makeBitMapDescriptor(kEndEmitted), + reading: makeBitMapDescriptor(kReading), + // Stream is still being constructed and cannot be + // destroyed until construction finished or failed. + // Async construction is opt in, therefore we start as + // constructed. + constructed: makeBitMapDescriptor(kConstructed), + // A flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + sync: makeBitMapDescriptor(kSync), + // Whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + needReadable: makeBitMapDescriptor(kNeedReadable), + emittedReadable: makeBitMapDescriptor(kEmittedReadable), + readableListening: makeBitMapDescriptor(kReadableListening), + resumeScheduled: makeBitMapDescriptor(kResumeScheduled), + // True if the error was already emitted and should not be thrown again. + errorEmitted: makeBitMapDescriptor(kErrorEmitted), + emitClose: makeBitMapDescriptor(kEmitClose), + autoDestroy: makeBitMapDescriptor(kAutoDestroy), + // Has it been destroyed. + destroyed: makeBitMapDescriptor(kDestroyed), + // Indicates whether the stream has finished destroying. + closed: makeBitMapDescriptor(kClosed), + // True if close has been emitted or would have been emitted + // depending on emitClose. + closeEmitted: makeBitMapDescriptor(kCloseEmitted), + multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), + // If true, a maybeReadMore has been scheduled. + readingMore: makeBitMapDescriptor(kReadingMore), + dataEmitted: makeBitMapDescriptor(kDataEmitted) +}) +function ReadableState(options, stream, isDuplex) { + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex') + + // Bit map field to store ReadableState more effciently with 1 bit per field + // instead of a V8 slot per field. + this.state = kEmitClose | kAutoDestroy | kConstructed | kSync + // Object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away. + if (options && options.objectMode) this.state |= kObjectMode + if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode + + // The point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = options + ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex) + : getDefaultHighWaterMark(false) + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift(). + this.buffer = new BufferList() + this.length = 0 + this.pipes = [] + this.flowing = null + this[kPaused] = null + + // Should close be emitted on destroy. Defaults to true. + if (options && options.emitClose === false) this.state &= ~kEmitClose + + // Should .destroy() be called after 'end' (and potentially 'finish'). + if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy + + // Indicates whether the stream has errored. When true no further + // _read calls, 'data' or 'readable' events should occur. This is needed + // since when autoDestroy is disabled we need a way to tell whether the + // stream has failed. + this.errored = null + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' + + // Ref the piped dest which we need a drain event on it + // type: null | Writable | Set. + this.awaitDrainWriters = null + this.decoder = null + this.encoding = null + if (options && options.encoding) { + this.decoder = new StringDecoder(options.encoding) + this.encoding = options.encoding + } +} +function Readable(options) { + if (!(this instanceof Readable)) return new Readable(options) + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5. + const isDuplex = this instanceof require('./duplex') + this._readableState = new ReadableState(options, this, isDuplex) + if (options) { + if (typeof options.read === 'function') this._read = options.read + if (typeof options.destroy === 'function') this._destroy = options.destroy + if (typeof options.construct === 'function') this._construct = options.construct + if (options.signal && !isDuplex) addAbortSignal(options.signal, this) + } + Stream.call(this, options) + destroyImpl.construct(this, () => { + if (this._readableState.needReadable) { + maybeReadMore(this, this._readableState) + } + }) +} +Readable.prototype.destroy = destroyImpl.destroy +Readable.prototype._undestroy = destroyImpl.undestroy +Readable.prototype._destroy = function (err, cb) { + cb(err) +} +Readable.prototype[EE.captureRejectionSymbol] = function (err) { + this.destroy(err) +} +Readable.prototype[SymbolAsyncDispose] = function () { + let error + if (!this.destroyed) { + error = this.readableEnded ? null : new AbortError() + this.destroy(error) + } + return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null)))) +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + return readableAddChunk(this, chunk, encoding, false) +} + +// Unshift should *always* be something directly out of read(). +Readable.prototype.unshift = function (chunk, encoding) { + return readableAddChunk(this, chunk, encoding, true) +} +function readableAddChunk(stream, chunk, encoding, addToFront) { + debug('readableAddChunk', chunk) + const state = stream._readableState + let err + if ((state.state & kObjectMode) === 0) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding + if (state.encoding !== encoding) { + if (addToFront && state.encoding) { + // When unshifting, if state.encoding is set, we have to save + // the string in the BufferList with the state encoding. + chunk = Buffer.from(chunk, encoding).toString(state.encoding) + } else { + chunk = Buffer.from(chunk, encoding) + encoding = '' + } + } + } else if (chunk instanceof Buffer) { + encoding = '' + } else if (Stream._isUint8Array(chunk)) { + chunk = Stream._uint8ArrayToBuffer(chunk) + encoding = '' + } else if (chunk != null) { + err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) + } + } + if (err) { + errorOrDestroy(stream, err) + } else if (chunk === null) { + state.state &= ~kReading + onEofChunk(stream, state) + } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) { + if (addToFront) { + if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()) + else if (state.destroyed || state.errored) return false + else addChunk(stream, state, chunk, true) + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()) + } else if (state.destroyed || state.errored) { + return false + } else { + state.state &= ~kReading + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk) + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false) + else maybeReadMore(stream, state) + } else { + addChunk(stream, state, chunk, false) + } + } + } else if (!addToFront) { + state.state &= ~kReading + maybeReadMore(stream, state) + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0) +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) { + // Use the guard to avoid creating `Set()` repeatedly + // when we have multiple pipes. + if ((state.state & kMultiAwaitDrain) !== 0) { + state.awaitDrainWriters.clear() + } else { + state.awaitDrainWriters = null + } + state.dataEmitted = true + stream.emit('data', chunk) + } else { + // Update the buffer info. + state.length += state.objectMode ? 1 : chunk.length + if (addToFront) state.buffer.unshift(chunk) + else state.buffer.push(chunk) + if ((state.state & kNeedReadable) !== 0) emitReadable(stream) + } + maybeReadMore(stream, state) +} +Readable.prototype.isPaused = function () { + const state = this._readableState + return state[kPaused] === true || state.flowing === false +} + +// Backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + const decoder = new StringDecoder(enc) + this._readableState.decoder = decoder + // If setEncoding(null), decoder.encoding equals utf8. + this._readableState.encoding = this._readableState.decoder.encoding + const buffer = this._readableState.buffer + // Iterate over current buffer to convert already stored Buffers: + let content = '' + for (const data of buffer) { + content += decoder.write(data) + } + buffer.clear() + if (content !== '') buffer.push(content) + this._readableState.length = content.length + return this +} + +// Don't raise the hwm > 1GB. +const MAX_HWM = 0x40000000 +function computeNewHighWaterMark(n) { + if (n > MAX_HWM) { + throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n) + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts. + n-- + n |= n >>> 1 + n |= n >>> 2 + n |= n >>> 4 + n |= n >>> 8 + n |= n >>> 16 + n++ + } + return n +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || (state.length === 0 && state.ended)) return 0 + if ((state.state & kObjectMode) !== 0) return 1 + if (NumberIsNaN(n)) { + // Only flow one buffer at a time. + if (state.flowing && state.length) return state.buffer.first().length + return state.length + } + if (n <= state.length) return n + return state.ended ? state.length : 0 +} + +// You can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n) + // Same as parseInt(undefined, 10), however V8 7.3 performance regressed + // in this scenario, so we are doing it manually. + if (n === undefined) { + n = NaN + } else if (!NumberIsInteger(n)) { + n = NumberParseInt(n, 10) + } + const state = this._readableState + const nOrig = n + + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n) + if (n !== 0) state.state &= ~kEmittedReadable + + // If we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if ( + n === 0 && + state.needReadable && + ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) + ) { + debug('read: emitReadable', state.length, state.ended) + if (state.length === 0 && state.ended) endReadable(this) + else emitReadable(this) + return null + } + n = howMuchToRead(n, state) + + // If we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this) + return null + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + let doRead = (state.state & kNeedReadable) !== 0 + debug('need readable', doRead) + + // If we currently have less than the highWaterMark, then also read some. + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true + debug('length less than watermark', doRead) + } + + // However, if we've ended, then there's no point, if we're already + // reading, then it's unnecessary, if we're constructing we have to wait, + // and if we're destroyed or errored, then it's not allowed, + if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { + doRead = false + debug('reading, ended or constructing', doRead) + } else if (doRead) { + debug('do read') + state.state |= kReading | kSync + // If the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.state |= kNeedReadable + + // Call internal read method + try { + this._read(state.highWaterMark) + } catch (err) { + errorOrDestroy(this, err) + } + state.state &= ~kSync + + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state) + } + let ret + if (n > 0) ret = fromList(n, state) + else ret = null + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark + n = 0 + } else { + state.length -= n + if (state.multiAwaitDrain) { + state.awaitDrainWriters.clear() + } else { + state.awaitDrainWriters = null + } + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this) + } + if (ret !== null && !state.errorEmitted && !state.closeEmitted) { + state.dataEmitted = true + this.emit('data', ret) + } + return ret +} +function onEofChunk(stream, state) { + debug('onEofChunk') + if (state.ended) return + if (state.decoder) { + const chunk = state.decoder.end() + if (chunk && chunk.length) { + state.buffer.push(chunk) + state.length += state.objectMode ? 1 : chunk.length + } + } + state.ended = true + if (state.sync) { + // If we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call. + emitReadable(stream) + } else { + // Emit 'readable' now to make sure it gets picked up. + state.needReadable = false + state.emittedReadable = true + // We have to emit readable now that we are EOF. Modules + // in the ecosystem (e.g. dicer) rely on this event being sync. + emitReadable_(stream) + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + const state = stream._readableState + debug('emitReadable', state.needReadable, state.emittedReadable) + state.needReadable = false + if (!state.emittedReadable) { + debug('emitReadable', state.flowing) + state.emittedReadable = true + process.nextTick(emitReadable_, stream) + } +} +function emitReadable_(stream) { + const state = stream._readableState + debug('emitReadable_', state.destroyed, state.length, state.ended) + if (!state.destroyed && !state.errored && (state.length || state.ended)) { + stream.emit('readable') + state.emittedReadable = false + } + + // The stream needs another readable event if: + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark + flow(stream) +} + +// At this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore && state.constructed) { + state.readingMore = true + process.nextTick(maybeReadMore_, stream, state) + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while ( + !state.reading && + !state.ended && + (state.length < state.highWaterMark || (state.flowing && state.length === 0)) + ) { + const len = state.length + debug('maybeReadMore read 0') + stream.read(0) + if (len === state.length) + // Didn't get any data, stop spinning. + break + } + state.readingMore = false +} + +// Abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + throw new ERR_METHOD_NOT_IMPLEMENTED('_read()') +} +Readable.prototype.pipe = function (dest, pipeOpts) { + const src = this + const state = this._readableState + if (state.pipes.length === 1) { + if (!state.multiAwaitDrain) { + state.multiAwaitDrain = true + state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []) + } + } + state.pipes.push(dest) + debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts) + const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr + const endFn = doEnd ? onend : unpipe + if (state.endEmitted) process.nextTick(endFn) + else src.once('end', endFn) + dest.on('unpipe', onunpipe) + function onunpipe(readable, unpipeInfo) { + debug('onunpipe') + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true + cleanup() + } + } + } + function onend() { + debug('onend') + dest.end() + } + let ondrain + let cleanedUp = false + function cleanup() { + debug('cleanup') + // Cleanup event handlers once the pipe is broken. + dest.removeListener('close', onclose) + dest.removeListener('finish', onfinish) + if (ondrain) { + dest.removeListener('drain', ondrain) + } + dest.removeListener('error', onerror) + dest.removeListener('unpipe', onunpipe) + src.removeListener('end', onend) + src.removeListener('end', unpipe) + src.removeListener('data', ondata) + cleanedUp = true + + // If the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain() + } + function pause() { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if (!cleanedUp) { + if (state.pipes.length === 1 && state.pipes[0] === dest) { + debug('false write response, pause', 0) + state.awaitDrainWriters = dest + state.multiAwaitDrain = false + } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { + debug('false write response, pause', state.awaitDrainWriters.size) + state.awaitDrainWriters.add(dest) + } + src.pause() + } + if (!ondrain) { + // When the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + ondrain = pipeOnDrain(src, dest) + dest.on('drain', ondrain) + } + } + src.on('data', ondata) + function ondata(chunk) { + debug('ondata') + const ret = dest.write(chunk) + debug('dest.write', ret) + if (ret === false) { + pause() + } + } + + // If the dest has an error, then stop piping into it. + // However, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er) + unpipe() + dest.removeListener('error', onerror) + if (dest.listenerCount('error') === 0) { + const s = dest._writableState || dest._readableState + if (s && !s.errorEmitted) { + // User incorrectly emitted 'error' directly on the stream. + errorOrDestroy(dest, er) + } else { + dest.emit('error', er) + } + } + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror) + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish) + unpipe() + } + dest.once('close', onclose) + function onfinish() { + debug('onfinish') + dest.removeListener('close', onclose) + unpipe() + } + dest.once('finish', onfinish) + function unpipe() { + debug('unpipe') + src.unpipe(dest) + } + + // Tell the dest that it's being piped to. + dest.emit('pipe', src) + + // Start the flow if it hasn't been started already. + + if (dest.writableNeedDrain === true) { + pause() + } else if (!state.flowing) { + debug('pipe resume') + src.resume() + } + return dest +} +function pipeOnDrain(src, dest) { + return function pipeOnDrainFunctionResult() { + const state = src._readableState + + // `ondrain` will call directly, + // `this` maybe not a reference to dest, + // so we use the real dest here. + if (state.awaitDrainWriters === dest) { + debug('pipeOnDrain', 1) + state.awaitDrainWriters = null + } else if (state.multiAwaitDrain) { + debug('pipeOnDrain', state.awaitDrainWriters.size) + state.awaitDrainWriters.delete(dest) + } + if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) { + src.resume() + } + } +} +Readable.prototype.unpipe = function (dest) { + const state = this._readableState + const unpipeInfo = { + hasUnpiped: false + } + + // If we're not piping anywhere, then do nothing. + if (state.pipes.length === 0) return this + if (!dest) { + // remove all. + const dests = state.pipes + state.pipes = [] + this.pause() + for (let i = 0; i < dests.length; i++) + dests[i].emit('unpipe', this, { + hasUnpiped: false + }) + return this + } + + // Try to find the right one. + const index = ArrayPrototypeIndexOf(state.pipes, dest) + if (index === -1) return this + state.pipes.splice(index, 1) + if (state.pipes.length === 0) this.pause() + dest.emit('unpipe', this, unpipeInfo) + return this +} + +// Set up data events if they are asked for +// Ensure readable listeners eventually get something. +Readable.prototype.on = function (ev, fn) { + const res = Stream.prototype.on.call(this, ev, fn) + const state = this._readableState + if (ev === 'data') { + // Update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0 + + // Try start flowing on next tick if stream isn't explicitly paused. + if (state.flowing !== false) this.resume() + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true + state.flowing = false + state.emittedReadable = false + debug('on readable', state.length, state.reading) + if (state.length) { + emitReadable(this) + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this) + } + } + } + return res +} +Readable.prototype.addListener = Readable.prototype.on +Readable.prototype.removeListener = function (ev, fn) { + const res = Stream.prototype.removeListener.call(this, ev, fn) + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this) + } + return res +} +Readable.prototype.off = Readable.prototype.removeListener +Readable.prototype.removeAllListeners = function (ev) { + const res = Stream.prototype.removeAllListeners.apply(this, arguments) + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this) + } + return res +} +function updateReadableListening(self) { + const state = self._readableState + state.readableListening = self.listenerCount('readable') > 0 + if (state.resumeScheduled && state[kPaused] === false) { + // Flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true + + // Crude way to check if we should resume. + } else if (self.listenerCount('data') > 0) { + self.resume() + } else if (!state.readableListening) { + state.flowing = null + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0') + self.read(0) +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + const state = this._readableState + if (!state.flowing) { + debug('resume') + // We flow only if there is no one listening + // for readable, but we still have to call + // resume(). + state.flowing = !state.readableListening + resume(this, state) + } + state[kPaused] = false + return this +} +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true + process.nextTick(resume_, stream, state) + } +} +function resume_(stream, state) { + debug('resume', state.reading) + if (!state.reading) { + stream.read(0) + } + state.resumeScheduled = false + stream.emit('resume') + flow(stream) + if (state.flowing && !state.reading) stream.read(0) +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing) + if (this._readableState.flowing !== false) { + debug('pause') + this._readableState.flowing = false + this.emit('pause') + } + this._readableState[kPaused] = true + return this +} +function flow(stream) { + const state = stream._readableState + debug('flow', state.flowing) + while (state.flowing && stream.read() !== null); +} + +// Wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + let paused = false + + // TODO (ronag): Should this.destroy(err) emit + // 'error' on the wrapped stream? Would require + // a static factory method, e.g. Readable.wrap(stream). + + stream.on('data', (chunk) => { + if (!this.push(chunk) && stream.pause) { + paused = true + stream.pause() + } + }) + stream.on('end', () => { + this.push(null) + }) + stream.on('error', (err) => { + errorOrDestroy(this, err) + }) + stream.on('close', () => { + this.destroy() + }) + stream.on('destroy', () => { + this.destroy() + }) + this._read = () => { + if (paused && stream.resume) { + paused = false + stream.resume() + } + } + + // Proxy all the other methods. Important when wrapping filters and duplexes. + const streamKeys = ObjectKeys(stream) + for (let j = 1; j < streamKeys.length; j++) { + const i = streamKeys[j] + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = stream[i].bind(stream) + } + } + return this +} +Readable.prototype[SymbolAsyncIterator] = function () { + return streamToAsyncIterator(this) +} +Readable.prototype.iterator = function (options) { + if (options !== undefined) { + validateObject(options, 'options') + } + return streamToAsyncIterator(this, options) +} +function streamToAsyncIterator(stream, options) { + if (typeof stream.read !== 'function') { + stream = Readable.wrap(stream, { + objectMode: true + }) + } + const iter = createAsyncIterator(stream, options) + iter.stream = stream + return iter +} +async function* createAsyncIterator(stream, options) { + let callback = nop + function next(resolve) { + if (this === stream) { + callback() + callback = nop + } else { + callback = resolve + } + } + stream.on('readable', next) + let error + const cleanup = eos( + stream, + { + writable: false + }, + (err) => { + error = err ? aggregateTwoErrors(error, err) : null + callback() + callback = nop + } + ) + try { + while (true) { + const chunk = stream.destroyed ? null : stream.read() + if (chunk !== null) { + yield chunk + } else if (error) { + throw error + } else if (error === null) { + return + } else { + await new Promise(next) + } + } + } catch (err) { + error = aggregateTwoErrors(error, err) + throw error + } finally { + if ( + (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) && + (error === undefined || stream._readableState.autoDestroy) + ) { + destroyImpl.destroyer(stream, null) + } else { + stream.off('readable', next) + cleanup() + } + } +} + +// Making it explicit these properties are not enumerable +// because otherwise some prototype manipulation in +// userland will fail. +ObjectDefineProperties(Readable.prototype, { + readable: { + __proto__: null, + get() { + const r = this._readableState + // r.readable === false means that this is part of a Duplex stream + // where the readable side was disabled upon construction. + // Compat. The user might manually disable readable side through + // deprecated setter. + return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted + }, + set(val) { + // Backwards compat. + if (this._readableState) { + this._readableState.readable = !!val + } + } + }, + readableDidRead: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.dataEmitted + } + }, + readableAborted: { + __proto__: null, + enumerable: false, + get: function () { + return !!( + this._readableState.readable !== false && + (this._readableState.destroyed || this._readableState.errored) && + !this._readableState.endEmitted + ) + } + }, + readableHighWaterMark: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.highWaterMark + } + }, + readableBuffer: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState && this._readableState.buffer + } + }, + readableFlowing: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.flowing + }, + set: function (state) { + if (this._readableState) { + this._readableState.flowing = state + } + } + }, + readableLength: { + __proto__: null, + enumerable: false, + get() { + return this._readableState.length + } + }, + readableObjectMode: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.objectMode : false + } + }, + readableEncoding: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.encoding : null + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.errored : null + } + }, + closed: { + __proto__: null, + get() { + return this._readableState ? this._readableState.closed : false + } + }, + destroyed: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.destroyed : false + }, + set(value) { + // We ignore the value if the stream + // has not been initialized yet. + if (!this._readableState) { + return + } + + // Backward compatibility, the user is explicitly + // managing destroyed. + this._readableState.destroyed = value + } + }, + readableEnded: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.endEmitted : false + } + } +}) +ObjectDefineProperties(ReadableState.prototype, { + // Legacy getter for `pipesCount`. + pipesCount: { + __proto__: null, + get() { + return this.pipes.length + } + }, + // Legacy property for `paused`. + paused: { + __proto__: null, + get() { + return this[kPaused] !== false + }, + set(value) { + this[kPaused] = !!value + } + } +}) + +// Exposed for testing purposes only. +Readable._fromList = fromList + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered. + if (state.length === 0) return null + let ret + if (state.objectMode) ret = state.buffer.shift() + else if (!n || n >= state.length) { + // Read it all, truncate the list. + if (state.decoder) ret = state.buffer.join('') + else if (state.buffer.length === 1) ret = state.buffer.first() + else ret = state.buffer.concat(state.length) + state.buffer.clear() + } else { + // read part of list. + ret = state.buffer.consume(n, state.decoder) + } + return ret +} +function endReadable(stream) { + const state = stream._readableState + debug('endReadable', state.endEmitted) + if (!state.endEmitted) { + state.ended = true + process.nextTick(endReadableNT, state, stream) + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length) + + // Check that we didn't get one last unshift. + if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { + state.endEmitted = true + stream.emit('end') + if (stream.writable && stream.allowHalfOpen === false) { + process.nextTick(endWritableNT, stream) + } else if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well. + const wState = stream._writableState + const autoDestroy = + !wState || + (wState.autoDestroy && + // We don't expect the writable to ever 'finish' + // if writable is explicitly set to false. + (wState.finished || wState.writable === false)) + if (autoDestroy) { + stream.destroy() + } + } + } +} +function endWritableNT(stream) { + const writable = stream.writable && !stream.writableEnded && !stream.destroyed + if (writable) { + stream.end() + } +} +Readable.from = function (iterable, opts) { + return from(Readable, iterable, opts) +} +let webStreamsAdapters + +// Lazy to avoid circular references +function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {} + return webStreamsAdapters +} +Readable.fromWeb = function (readableStream, options) { + return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options) +} +Readable.toWeb = function (streamReadable, options) { + return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options) +} +Readable.wrap = function (src, options) { + var _ref, _src$readableObjectMo + return new Readable({ + objectMode: + (_ref = + (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined + ? _src$readableObjectMo + : src.objectMode) !== null && _ref !== undefined + ? _ref + : true, + ...options, + destroy(err, callback) { + destroyImpl.destroyer(src, err) + callback(err) + } + }).wrap(src) +} diff --git a/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 00000000..79294a04 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,39 @@ +'use strict' + +const { MathFloor, NumberIsInteger } = require('../../ours/primordials') +const { validateInteger } = require('../validators') +const { ERR_INVALID_ARG_VALUE } = require('../../ours/errors').codes +let defaultHighWaterMarkBytes = 16 * 1024 +let defaultHighWaterMarkObjectMode = 16 +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null +} +function getDefaultHighWaterMark(objectMode) { + return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes +} +function setDefaultHighWaterMark(objectMode, value) { + validateInteger(value, 'value', 0) + if (objectMode) { + defaultHighWaterMarkObjectMode = value + } else { + defaultHighWaterMarkBytes = value + } +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + const hwm = highWaterMarkFrom(options, isDuplex, duplexKey) + if (hwm != null) { + if (!NumberIsInteger(hwm) || hwm < 0) { + const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark' + throw new ERR_INVALID_ARG_VALUE(name, hwm) + } + return MathFloor(hwm) + } + + // Default value + return getDefaultHighWaterMark(state.objectMode) +} +module.exports = { + getHighWaterMark, + getDefaultHighWaterMark, + setDefaultHighWaterMark +} diff --git a/node_modules/readable-stream/lib/internal/streams/transform.js b/node_modules/readable-stream/lib/internal/streams/transform.js new file mode 100644 index 00000000..fa9413a4 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/transform.js @@ -0,0 +1,180 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict' + +const { ObjectSetPrototypeOf, Symbol } = require('../../ours/primordials') +module.exports = Transform +const { ERR_METHOD_NOT_IMPLEMENTED } = require('../../ours/errors').codes +const Duplex = require('./duplex') +const { getHighWaterMark } = require('./state') +ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype) +ObjectSetPrototypeOf(Transform, Duplex) +const kCallback = Symbol('kCallback') +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options) + + // TODO (ronag): This should preferably always be + // applied but would be semver-major. Or even better; + // make Transform a Readable with the Writable interface. + const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null + if (readableHighWaterMark === 0) { + // A Duplex will buffer both on the writable and readable side while + // a Transform just wants to buffer hwm number of elements. To avoid + // buffering twice we disable buffering on the writable side. + options = { + ...options, + highWaterMark: null, + readableHighWaterMark, + // TODO (ronag): 0 is not optimal since we have + // a "bug" where we check needDrain before calling _write and not after. + // Refs: https://github.com/nodejs/node/pull/32887 + // Refs: https://github.com/nodejs/node/pull/35941 + writableHighWaterMark: options.writableHighWaterMark || 0 + } + } + Duplex.call(this, options) + + // We have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false + this[kCallback] = null + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform + if (typeof options.flush === 'function') this._flush = options.flush + } + + // When the writable side finishes, then flush out anything remaining. + // Backwards compat. Some Transform streams incorrectly implement _final + // instead of or in addition to _flush. By using 'prefinish' instead of + // implementing _final we continue supporting this unfortunate use case. + this.on('prefinish', prefinish) +} +function final(cb) { + if (typeof this._flush === 'function' && !this.destroyed) { + this._flush((er, data) => { + if (er) { + if (cb) { + cb(er) + } else { + this.destroy(er) + } + return + } + if (data != null) { + this.push(data) + } + this.push(null) + if (cb) { + cb() + } + }) + } else { + this.push(null) + if (cb) { + cb() + } + } +} +function prefinish() { + if (this._final !== final) { + final.call(this) + } +} +Transform.prototype._final = final +Transform.prototype._transform = function (chunk, encoding, callback) { + throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()') +} +Transform.prototype._write = function (chunk, encoding, callback) { + const rState = this._readableState + const wState = this._writableState + const length = rState.length + this._transform(chunk, encoding, (err, val) => { + if (err) { + callback(err) + return + } + if (val != null) { + this.push(val) + } + if ( + wState.ended || + // Backwards compat. + length === rState.length || + // Backwards compat. + rState.length < rState.highWaterMark + ) { + callback() + } else { + this[kCallback] = callback + } + }) +} +Transform.prototype._read = function () { + if (this[kCallback]) { + const callback = this[kCallback] + this[kCallback] = null + callback() + } +} diff --git a/node_modules/readable-stream/lib/internal/streams/utils.js b/node_modules/readable-stream/lib/internal/streams/utils.js new file mode 100644 index 00000000..f0d7884e --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/utils.js @@ -0,0 +1,327 @@ +'use strict' + +const { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require('../../ours/primordials') + +// We need to use SymbolFor to make these globally available +// for interopt with readable-stream, i.e. readable-stream +// and node core needs to be able to read/write private state +// from each other for proper interoperability. +const kIsDestroyed = SymbolFor('nodejs.stream.destroyed') +const kIsErrored = SymbolFor('nodejs.stream.errored') +const kIsReadable = SymbolFor('nodejs.stream.readable') +const kIsWritable = SymbolFor('nodejs.stream.writable') +const kIsDisturbed = SymbolFor('nodejs.stream.disturbed') +const kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise') +const kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction') +function isReadableNodeStream(obj, strict = false) { + var _obj$_readableState + return !!( + ( + obj && + typeof obj.pipe === 'function' && + typeof obj.on === 'function' && + (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) && + (!obj._writableState || + ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined + ? undefined + : _obj$_readableState.readable) !== false) && + // Duplex + (!obj._writableState || obj._readableState) + ) // Writable has .pipe. + ) +} +function isWritableNodeStream(obj) { + var _obj$_writableState + return !!( + ( + obj && + typeof obj.write === 'function' && + typeof obj.on === 'function' && + (!obj._readableState || + ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined + ? undefined + : _obj$_writableState.writable) !== false) + ) // Duplex + ) +} +function isDuplexNodeStream(obj) { + return !!( + obj && + typeof obj.pipe === 'function' && + obj._readableState && + typeof obj.on === 'function' && + typeof obj.write === 'function' + ) +} +function isNodeStream(obj) { + return ( + obj && + (obj._readableState || + obj._writableState || + (typeof obj.write === 'function' && typeof obj.on === 'function') || + (typeof obj.pipe === 'function' && typeof obj.on === 'function')) + ) +} +function isReadableStream(obj) { + return !!( + obj && + !isNodeStream(obj) && + typeof obj.pipeThrough === 'function' && + typeof obj.getReader === 'function' && + typeof obj.cancel === 'function' + ) +} +function isWritableStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function') +} +function isTransformStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object') +} +function isWebStream(obj) { + return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj) +} +function isIterable(obj, isAsync) { + if (obj == null) return false + if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function' + if (isAsync === false) return typeof obj[SymbolIterator] === 'function' + return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function' +} +function isDestroyed(stream) { + if (!isNodeStream(stream)) return null + const wState = stream._writableState + const rState = stream._readableState + const state = wState || rState + return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed)) +} + +// Have been end():d. +function isWritableEnded(stream) { + if (!isWritableNodeStream(stream)) return null + if (stream.writableEnded === true) return true + const wState = stream._writableState + if (wState !== null && wState !== undefined && wState.errored) return false + if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null + return wState.ended +} + +// Have emitted 'finish'. +function isWritableFinished(stream, strict) { + if (!isWritableNodeStream(stream)) return null + if (stream.writableFinished === true) return true + const wState = stream._writableState + if (wState !== null && wState !== undefined && wState.errored) return false + if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null + return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0)) +} + +// Have been push(null):d. +function isReadableEnded(stream) { + if (!isReadableNodeStream(stream)) return null + if (stream.readableEnded === true) return true + const rState = stream._readableState + if (!rState || rState.errored) return false + if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null + return rState.ended +} + +// Have emitted 'end'. +function isReadableFinished(stream, strict) { + if (!isReadableNodeStream(stream)) return null + const rState = stream._readableState + if (rState !== null && rState !== undefined && rState.errored) return false + if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null + return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0)) +} +function isReadable(stream) { + if (stream && stream[kIsReadable] != null) return stream[kIsReadable] + if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null + if (isDestroyed(stream)) return false + return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream) +} +function isWritable(stream) { + if (stream && stream[kIsWritable] != null) return stream[kIsWritable] + if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null + if (isDestroyed(stream)) return false + return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream) +} +function isFinished(stream, opts) { + if (!isNodeStream(stream)) { + return null + } + if (isDestroyed(stream)) { + return true + } + if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) { + return false + } + if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) { + return false + } + return true +} +function isWritableErrored(stream) { + var _stream$_writableStat, _stream$_writableStat2 + if (!isNodeStream(stream)) { + return null + } + if (stream.writableErrored) { + return stream.writableErrored + } + return (_stream$_writableStat = + (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined + ? undefined + : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined + ? _stream$_writableStat + : null +} +function isReadableErrored(stream) { + var _stream$_readableStat, _stream$_readableStat2 + if (!isNodeStream(stream)) { + return null + } + if (stream.readableErrored) { + return stream.readableErrored + } + return (_stream$_readableStat = + (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined + ? undefined + : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined + ? _stream$_readableStat + : null +} +function isClosed(stream) { + if (!isNodeStream(stream)) { + return null + } + if (typeof stream.closed === 'boolean') { + return stream.closed + } + const wState = stream._writableState + const rState = stream._readableState + if ( + typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' || + typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean' + ) { + return ( + (wState === null || wState === undefined ? undefined : wState.closed) || + (rState === null || rState === undefined ? undefined : rState.closed) + ) + } + if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) { + return stream._closed + } + return null +} +function isOutgoingMessage(stream) { + return ( + typeof stream._closed === 'boolean' && + typeof stream._defaultKeepAlive === 'boolean' && + typeof stream._removedConnection === 'boolean' && + typeof stream._removedContLen === 'boolean' + ) +} +function isServerResponse(stream) { + return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream) +} +function isServerRequest(stream) { + var _stream$req + return ( + typeof stream._consuming === 'boolean' && + typeof stream._dumped === 'boolean' && + ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) === + undefined + ) +} +function willEmitClose(stream) { + if (!isNodeStream(stream)) return null + const wState = stream._writableState + const rState = stream._readableState + const state = wState || rState + return ( + (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false) + ) +} +function isDisturbed(stream) { + var _stream$kIsDisturbed + return !!( + stream && + ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined + ? _stream$kIsDisturbed + : stream.readableDidRead || stream.readableAborted) + ) +} +function isErrored(stream) { + var _ref, + _ref2, + _ref3, + _ref4, + _ref5, + _stream$kIsErrored, + _stream$_readableStat3, + _stream$_writableStat3, + _stream$_readableStat4, + _stream$_writableStat4 + return !!( + stream && + ((_ref = + (_ref2 = + (_ref3 = + (_ref4 = + (_ref5 = + (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined + ? _stream$kIsErrored + : stream.readableErrored) !== null && _ref5 !== undefined + ? _ref5 + : stream.writableErrored) !== null && _ref4 !== undefined + ? _ref4 + : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined + ? undefined + : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined + ? _ref3 + : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined + ? undefined + : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined + ? _ref2 + : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined + ? undefined + : _stream$_readableStat4.errored) !== null && _ref !== undefined + ? _ref + : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined + ? undefined + : _stream$_writableStat4.errored) + ) +} +module.exports = { + isDestroyed, + kIsDestroyed, + isDisturbed, + kIsDisturbed, + isErrored, + kIsErrored, + isReadable, + kIsReadable, + kIsClosedPromise, + kControllerErrorFunction, + kIsWritable, + isClosed, + isDuplexNodeStream, + isFinished, + isIterable, + isReadableNodeStream, + isReadableStream, + isReadableEnded, + isReadableFinished, + isReadableErrored, + isNodeStream, + isWebStream, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableEnded, + isWritableFinished, + isWritableErrored, + isServerRequest, + isServerResponse, + willEmitClose, + isTransformStream +} diff --git a/node_modules/readable-stream/lib/internal/streams/writable.js b/node_modules/readable-stream/lib/internal/streams/writable.js new file mode 100644 index 00000000..b4ecf0e2 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/writable.js @@ -0,0 +1,819 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict' + +/* replacement start */ + +const process = require('process/') + +/* replacement end */ + +const { + ArrayPrototypeSlice, + Error, + FunctionPrototypeSymbolHasInstance, + ObjectDefineProperty, + ObjectDefineProperties, + ObjectSetPrototypeOf, + StringPrototypeToLowerCase, + Symbol, + SymbolHasInstance +} = require('../../ours/primordials') +module.exports = Writable +Writable.WritableState = WritableState +const { EventEmitter: EE } = require('events') +const Stream = require('./legacy').Stream +const { Buffer } = require('buffer') +const destroyImpl = require('./destroy') +const { addAbortSignal } = require('./add-abort-signal') +const { getHighWaterMark, getDefaultHighWaterMark } = require('./state') +const { + ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED, + ERR_STREAM_ALREADY_FINISHED, + ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING +} = require('../../ours/errors').codes +const { errorOrDestroy } = destroyImpl +ObjectSetPrototypeOf(Writable.prototype, Stream.prototype) +ObjectSetPrototypeOf(Writable, Stream) +function nop() {} +const kOnFinished = Symbol('kOnFinished') +function WritableState(options, stream, isDuplex) { + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex') + + // Object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!(options && options.objectMode) + if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode) + + // The point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write(). + this.highWaterMark = options + ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex) + : getDefaultHighWaterMark(false) + + // if _final has been called. + this.finalCalled = false + + // drain event flag. + this.needDrain = false + // At the start of calling end() + this.ending = false + // When end() has been called, and returned. + this.ended = false + // When 'finish' is emitted. + this.finished = false + + // Has it been destroyed + this.destroyed = false + + // Should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + const noDecode = !!(options && options.decodeStrings === false) + this.decodeStrings = !noDecode + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' + + // Not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0 + + // A flag to see when we're in the middle of a write. + this.writing = false + + // When true all writes will be buffered until .uncork() call. + this.corked = 0 + + // A flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true + + // A flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false + + // The callback that's passed to _write(chunk, cb). + this.onwrite = onwrite.bind(undefined, stream) + + // The callback that the user supplies to write(chunk, encoding, cb). + this.writecb = null + + // The amount that is being written when _write is called. + this.writelen = 0 + + // Storage for data passed to the afterWrite() callback in case of + // synchronous _write() completion. + this.afterWriteTickInfo = null + resetBuffer(this) + + // Number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted. + this.pendingcb = 0 + + // Stream is still being constructed and cannot be + // destroyed until construction finished or failed. + // Async construction is opt in, therefore we start as + // constructed. + this.constructed = true + + // Emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams. + this.prefinished = false + + // True if the error was already emitted and should not be thrown again. + this.errorEmitted = false + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = !options || options.emitClose !== false + + // Should .destroy() be called after 'finish' (and potentially 'end'). + this.autoDestroy = !options || options.autoDestroy !== false + + // Indicates whether the stream has errored. When true all write() calls + // should return false. This is needed since when autoDestroy + // is disabled we need a way to tell whether the stream has failed. + this.errored = null + + // Indicates whether the stream has finished destroying. + this.closed = false + + // True if close has been emitted or would have been emitted + // depending on emitClose. + this.closeEmitted = false + this[kOnFinished] = [] +} +function resetBuffer(state) { + state.buffered = [] + state.bufferedIndex = 0 + state.allBuffers = true + state.allNoop = true +} +WritableState.prototype.getBuffer = function getBuffer() { + return ArrayPrototypeSlice(this.buffered, this.bufferedIndex) +} +ObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', { + __proto__: null, + get() { + return this.buffered.length - this.bufferedIndex + } +}) +function Writable(options) { + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5. + const isDuplex = this instanceof require('./duplex') + if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options) + this._writableState = new WritableState(options, this, isDuplex) + if (options) { + if (typeof options.write === 'function') this._write = options.write + if (typeof options.writev === 'function') this._writev = options.writev + if (typeof options.destroy === 'function') this._destroy = options.destroy + if (typeof options.final === 'function') this._final = options.final + if (typeof options.construct === 'function') this._construct = options.construct + if (options.signal) addAbortSignal(options.signal, this) + } + Stream.call(this, options) + destroyImpl.construct(this, () => { + const state = this._writableState + if (!state.writing) { + clearBuffer(this, state) + } + finishMaybe(this, state) + }) +} +ObjectDefineProperty(Writable, SymbolHasInstance, { + __proto__: null, + value: function (object) { + if (FunctionPrototypeSymbolHasInstance(this, object)) return true + if (this !== Writable) return false + return object && object._writableState instanceof WritableState + } +}) + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()) +} +function _write(stream, chunk, encoding, cb) { + const state = stream._writableState + if (typeof encoding === 'function') { + cb = encoding + encoding = state.defaultEncoding + } else { + if (!encoding) encoding = state.defaultEncoding + else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) + if (typeof cb !== 'function') cb = nop + } + if (chunk === null) { + throw new ERR_STREAM_NULL_VALUES() + } else if (!state.objectMode) { + if (typeof chunk === 'string') { + if (state.decodeStrings !== false) { + chunk = Buffer.from(chunk, encoding) + encoding = 'buffer' + } + } else if (chunk instanceof Buffer) { + encoding = 'buffer' + } else if (Stream._isUint8Array(chunk)) { + chunk = Stream._uint8ArrayToBuffer(chunk) + encoding = 'buffer' + } else { + throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) + } + } + let err + if (state.ending) { + err = new ERR_STREAM_WRITE_AFTER_END() + } else if (state.destroyed) { + err = new ERR_STREAM_DESTROYED('write') + } + if (err) { + process.nextTick(cb, err) + errorOrDestroy(stream, err, true) + return err + } + state.pendingcb++ + return writeOrBuffer(stream, state, chunk, encoding, cb) +} +Writable.prototype.write = function (chunk, encoding, cb) { + return _write(this, chunk, encoding, cb) === true +} +Writable.prototype.cork = function () { + this._writableState.corked++ +} +Writable.prototype.uncork = function () { + const state = this._writableState + if (state.corked) { + state.corked-- + if (!state.writing) clearBuffer(this, state) + } +} +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding) + if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) + this._writableState.defaultEncoding = encoding + return this +} + +// If we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, callback) { + const len = state.objectMode ? 1 : chunk.length + state.length += len + + // stream._write resets state.length + const ret = state.length < state.highWaterMark + // We must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true + if (state.writing || state.corked || state.errored || !state.constructed) { + state.buffered.push({ + chunk, + encoding, + callback + }) + if (state.allBuffers && encoding !== 'buffer') { + state.allBuffers = false + } + if (state.allNoop && callback !== nop) { + state.allNoop = false + } + } else { + state.writelen = len + state.writecb = callback + state.writing = true + state.sync = true + stream._write(chunk, encoding, state.onwrite) + state.sync = false + } + + // Return false if errored or destroyed in order to break + // any synchronous while(stream.write(data)) loops. + return ret && !state.errored && !state.destroyed +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len + state.writecb = cb + state.writing = true + state.sync = true + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write')) + else if (writev) stream._writev(chunk, state.onwrite) + else stream._write(chunk, encoding, state.onwrite) + state.sync = false +} +function onwriteError(stream, state, er, cb) { + --state.pendingcb + cb(er) + // Ensure callbacks are invoked even when autoDestroy is + // not enabled. Passing `er` here doesn't make sense since + // it's related to one specific write, not to the buffered + // writes. + errorBuffer(state) + // This can emit error, but error must always follow cb. + errorOrDestroy(stream, er) +} +function onwrite(stream, er) { + const state = stream._writableState + const sync = state.sync + const cb = state.writecb + if (typeof cb !== 'function') { + errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()) + return + } + state.writing = false + state.writecb = null + state.length -= state.writelen + state.writelen = 0 + if (er) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + er.stack // eslint-disable-line no-unused-expressions + + if (!state.errored) { + state.errored = er + } + + // In case of duplex streams we need to notify the readable side of the + // error. + if (stream._readableState && !stream._readableState.errored) { + stream._readableState.errored = er + } + if (sync) { + process.nextTick(onwriteError, stream, state, er, cb) + } else { + onwriteError(stream, state, er, cb) + } + } else { + if (state.buffered.length > state.bufferedIndex) { + clearBuffer(stream, state) + } + if (sync) { + // It is a common case that the callback passed to .write() is always + // the same. In that case, we do not schedule a new nextTick(), but + // rather just increase a counter, to improve performance and avoid + // memory allocations. + if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) { + state.afterWriteTickInfo.count++ + } else { + state.afterWriteTickInfo = { + count: 1, + cb, + stream, + state + } + process.nextTick(afterWriteTick, state.afterWriteTickInfo) + } + } else { + afterWrite(stream, state, 1, cb) + } + } +} +function afterWriteTick({ stream, state, count, cb }) { + state.afterWriteTickInfo = null + return afterWrite(stream, state, count, cb) +} +function afterWrite(stream, state, count, cb) { + const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain + if (needDrain) { + state.needDrain = false + stream.emit('drain') + } + while (count-- > 0) { + state.pendingcb-- + cb() + } + if (state.destroyed) { + errorBuffer(state) + } + finishMaybe(stream, state) +} + +// If there's something in the buffer waiting, then invoke callbacks. +function errorBuffer(state) { + if (state.writing) { + return + } + for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { + var _state$errored + const { chunk, callback } = state.buffered[n] + const len = state.objectMode ? 1 : chunk.length + state.length -= len + callback( + (_state$errored = state.errored) !== null && _state$errored !== undefined + ? _state$errored + : new ERR_STREAM_DESTROYED('write') + ) + } + const onfinishCallbacks = state[kOnFinished].splice(0) + for (let i = 0; i < onfinishCallbacks.length; i++) { + var _state$errored2 + onfinishCallbacks[i]( + (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined + ? _state$errored2 + : new ERR_STREAM_DESTROYED('end') + ) + } + resetBuffer(state) +} + +// If there's something in the buffer waiting, then process it. +function clearBuffer(stream, state) { + if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) { + return + } + const { buffered, bufferedIndex, objectMode } = state + const bufferedLength = buffered.length - bufferedIndex + if (!bufferedLength) { + return + } + let i = bufferedIndex + state.bufferProcessing = true + if (bufferedLength > 1 && stream._writev) { + state.pendingcb -= bufferedLength - 1 + const callback = state.allNoop + ? nop + : (err) => { + for (let n = i; n < buffered.length; ++n) { + buffered[n].callback(err) + } + } + // Make a copy of `buffered` if it's going to be used by `callback` above, + // since `doWrite` will mutate the array. + const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i) + chunks.allBuffers = state.allBuffers + doWrite(stream, state, true, state.length, chunks, '', callback) + resetBuffer(state) + } else { + do { + const { chunk, encoding, callback } = buffered[i] + buffered[i++] = null + const len = objectMode ? 1 : chunk.length + doWrite(stream, state, false, len, chunk, encoding, callback) + } while (i < buffered.length && !state.writing) + if (i === buffered.length) { + resetBuffer(state) + } else if (i > 256) { + buffered.splice(0, i) + state.bufferedIndex = 0 + } else { + state.bufferedIndex = i + } + } + state.bufferProcessing = false +} +Writable.prototype._write = function (chunk, encoding, cb) { + if (this._writev) { + this._writev( + [ + { + chunk, + encoding + } + ], + cb + ) + } else { + throw new ERR_METHOD_NOT_IMPLEMENTED('_write()') + } +} +Writable.prototype._writev = null +Writable.prototype.end = function (chunk, encoding, cb) { + const state = this._writableState + if (typeof chunk === 'function') { + cb = chunk + chunk = null + encoding = null + } else if (typeof encoding === 'function') { + cb = encoding + encoding = null + } + let err + if (chunk !== null && chunk !== undefined) { + const ret = _write(this, chunk, encoding) + if (ret instanceof Error) { + err = ret + } + } + + // .end() fully uncorks. + if (state.corked) { + state.corked = 1 + this.uncork() + } + if (err) { + // Do nothing... + } else if (!state.errored && !state.ending) { + // This is forgiving in terms of unnecessary calls to end() and can hide + // logic errors. However, usually such errors are harmless and causing a + // hard error can be disproportionately destructive. It is not always + // trivial for the user to determine whether end() needs to be called + // or not. + + state.ending = true + finishMaybe(this, state, true) + state.ended = true + } else if (state.finished) { + err = new ERR_STREAM_ALREADY_FINISHED('end') + } else if (state.destroyed) { + err = new ERR_STREAM_DESTROYED('end') + } + if (typeof cb === 'function') { + if (err || state.finished) { + process.nextTick(cb, err) + } else { + state[kOnFinished].push(cb) + } + } + return this +} +function needFinish(state) { + return ( + state.ending && + !state.destroyed && + state.constructed && + state.length === 0 && + !state.errored && + state.buffered.length === 0 && + !state.finished && + !state.writing && + !state.errorEmitted && + !state.closeEmitted + ) +} +function callFinal(stream, state) { + let called = false + function onFinish(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK()) + return + } + called = true + state.pendingcb-- + if (err) { + const onfinishCallbacks = state[kOnFinished].splice(0) + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i](err) + } + errorOrDestroy(stream, err, state.sync) + } else if (needFinish(state)) { + state.prefinished = true + stream.emit('prefinish') + // Backwards compat. Don't check state.sync here. + // Some streams assume 'finish' will be emitted + // asynchronously relative to _final callback. + state.pendingcb++ + process.nextTick(finish, stream, state) + } + } + state.sync = true + state.pendingcb++ + try { + stream._final(onFinish) + } catch (err) { + onFinish(err) + } + state.sync = false +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.finalCalled = true + callFinal(stream, state) + } else { + state.prefinished = true + stream.emit('prefinish') + } + } +} +function finishMaybe(stream, state, sync) { + if (needFinish(state)) { + prefinish(stream, state) + if (state.pendingcb === 0) { + if (sync) { + state.pendingcb++ + process.nextTick( + (stream, state) => { + if (needFinish(state)) { + finish(stream, state) + } else { + state.pendingcb-- + } + }, + stream, + state + ) + } else if (needFinish(state)) { + state.pendingcb++ + finish(stream, state) + } + } + } +} +function finish(stream, state) { + state.pendingcb-- + state.finished = true + const onfinishCallbacks = state[kOnFinished].splice(0) + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i]() + } + stream.emit('finish') + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well. + const rState = stream._readableState + const autoDestroy = + !rState || + (rState.autoDestroy && + // We don't expect the readable to ever 'end' + // if readable is explicitly set to false. + (rState.endEmitted || rState.readable === false)) + if (autoDestroy) { + stream.destroy() + } + } +} +ObjectDefineProperties(Writable.prototype, { + closed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.closed : false + } + }, + destroyed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.destroyed : false + }, + set(value) { + // Backward compatibility, the user is explicitly managing destroyed. + if (this._writableState) { + this._writableState.destroyed = value + } + } + }, + writable: { + __proto__: null, + get() { + const w = this._writableState + // w.writable === false means that this is part of a Duplex stream + // where the writable side was disabled upon construction. + // Compat. The user might manually disable writable side through + // deprecated setter. + return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended + }, + set(val) { + // Backwards compatible. + if (this._writableState) { + this._writableState.writable = !!val + } + } + }, + writableFinished: { + __proto__: null, + get() { + return this._writableState ? this._writableState.finished : false + } + }, + writableObjectMode: { + __proto__: null, + get() { + return this._writableState ? this._writableState.objectMode : false + } + }, + writableBuffer: { + __proto__: null, + get() { + return this._writableState && this._writableState.getBuffer() + } + }, + writableEnded: { + __proto__: null, + get() { + return this._writableState ? this._writableState.ending : false + } + }, + writableNeedDrain: { + __proto__: null, + get() { + const wState = this._writableState + if (!wState) return false + return !wState.destroyed && !wState.ending && wState.needDrain + } + }, + writableHighWaterMark: { + __proto__: null, + get() { + return this._writableState && this._writableState.highWaterMark + } + }, + writableCorked: { + __proto__: null, + get() { + return this._writableState ? this._writableState.corked : 0 + } + }, + writableLength: { + __proto__: null, + get() { + return this._writableState && this._writableState.length + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._writableState ? this._writableState.errored : null + } + }, + writableAborted: { + __proto__: null, + enumerable: false, + get: function () { + return !!( + this._writableState.writable !== false && + (this._writableState.destroyed || this._writableState.errored) && + !this._writableState.finished + ) + } + } +}) +const destroy = destroyImpl.destroy +Writable.prototype.destroy = function (err, cb) { + const state = this._writableState + + // Invoke pending callbacks. + if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) { + process.nextTick(errorBuffer, state) + } + destroy.call(this, err, cb) + return this +} +Writable.prototype._undestroy = destroyImpl.undestroy +Writable.prototype._destroy = function (err, cb) { + cb(err) +} +Writable.prototype[EE.captureRejectionSymbol] = function (err) { + this.destroy(err) +} +let webStreamsAdapters + +// Lazy to avoid circular references +function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {} + return webStreamsAdapters +} +Writable.fromWeb = function (writableStream, options) { + return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options) +} +Writable.toWeb = function (streamWritable) { + return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable) +} diff --git a/node_modules/readable-stream/lib/internal/validators.js b/node_modules/readable-stream/lib/internal/validators.js new file mode 100644 index 00000000..f9006844 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/validators.js @@ -0,0 +1,530 @@ +/* eslint jsdoc/require-jsdoc: "error" */ + +'use strict' + +const { + ArrayIsArray, + ArrayPrototypeIncludes, + ArrayPrototypeJoin, + ArrayPrototypeMap, + NumberIsInteger, + NumberIsNaN, + NumberMAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER, + NumberParseInt, + ObjectPrototypeHasOwnProperty, + RegExpPrototypeExec, + String, + StringPrototypeToUpperCase, + StringPrototypeTrim +} = require('../ours/primordials') +const { + hideStackFrames, + codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } +} = require('../ours/errors') +const { normalizeEncoding } = require('../ours/util') +const { isAsyncFunction, isArrayBufferView } = require('../ours/util').types +const signals = {} + +/** + * @param {*} value + * @returns {boolean} + */ +function isInt32(value) { + return value === (value | 0) +} + +/** + * @param {*} value + * @returns {boolean} + */ +function isUint32(value) { + return value === value >>> 0 +} +const octalReg = /^[0-7]+$/ +const modeDesc = 'must be a 32-bit unsigned integer or an octal string' + +/** + * Parse and validate values that will be converted into mode_t (the S_* + * constants). Only valid numbers and octal strings are allowed. They could be + * converted to 32-bit unsigned integers or non-negative signed integers in the + * C++ land, but any value higher than 0o777 will result in platform-specific + * behaviors. + * @param {*} value Values to be validated + * @param {string} name Name of the argument + * @param {number} [def] If specified, will be returned for invalid values + * @returns {number} + */ +function parseFileMode(value, name, def) { + if (typeof value === 'undefined') { + value = def + } + if (typeof value === 'string') { + if (RegExpPrototypeExec(octalReg, value) === null) { + throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc) + } + value = NumberParseInt(value, 8) + } + validateUint32(value, name) + return value +} + +/** + * @callback validateInteger + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ + +/** @type {validateInteger} */ +const validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => { + if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) +}) + +/** + * @callback validateInt32 + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ + +/** @type {validateInt32} */ +const validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => { + // The defaults for min and max correspond to the limits of 32-bit integers. + if (typeof value !== 'number') { + throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + } + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) + } +}) + +/** + * @callback validateUint32 + * @param {*} value + * @param {string} name + * @param {number|boolean} [positive=false] + * @returns {asserts value is number} + */ + +/** @type {validateUint32} */ +const validateUint32 = hideStackFrames((value, name, positive = false) => { + if (typeof value !== 'number') { + throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + } + const min = positive ? 1 : 0 + // 2 ** 32 === 4294967296 + const max = 4294967295 + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) + } +}) + +/** + * @callback validateString + * @param {*} value + * @param {string} name + * @returns {asserts value is string} + */ + +/** @type {validateString} */ +function validateString(value, name) { + if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value) +} + +/** + * @callback validateNumber + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ + +/** @type {validateNumber} */ +function validateNumber(value, name, min = undefined, max) { + if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + if ( + (min != null && value < min) || + (max != null && value > max) || + ((min != null || max != null) && NumberIsNaN(value)) + ) { + throw new ERR_OUT_OF_RANGE( + name, + `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`, + value + ) + } +} + +/** + * @callback validateOneOf + * @template T + * @param {T} value + * @param {string} name + * @param {T[]} oneOf + */ + +/** @type {validateOneOf} */ +const validateOneOf = hideStackFrames((value, name, oneOf) => { + if (!ArrayPrototypeIncludes(oneOf, value)) { + const allowed = ArrayPrototypeJoin( + ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))), + ', ' + ) + const reason = 'must be one of: ' + allowed + throw new ERR_INVALID_ARG_VALUE(name, value, reason) + } +}) + +/** + * @callback validateBoolean + * @param {*} value + * @param {string} name + * @returns {asserts value is boolean} + */ + +/** @type {validateBoolean} */ +function validateBoolean(value, name) { + if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value) +} + +/** + * @param {any} options + * @param {string} key + * @param {boolean} defaultValue + * @returns {boolean} + */ +function getOwnPropertyValueOrDefault(options, key, defaultValue) { + return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key] +} + +/** + * @callback validateObject + * @param {*} value + * @param {string} name + * @param {{ + * allowArray?: boolean, + * allowFunction?: boolean, + * nullable?: boolean + * }} [options] + */ + +/** @type {validateObject} */ +const validateObject = hideStackFrames((value, name, options = null) => { + const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false) + const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false) + const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false) + if ( + (!nullable && value === null) || + (!allowArray && ArrayIsArray(value)) || + (typeof value !== 'object' && (!allowFunction || typeof value !== 'function')) + ) { + throw new ERR_INVALID_ARG_TYPE(name, 'Object', value) + } +}) + +/** + * @callback validateDictionary - We are using the Web IDL Standard definition + * of "dictionary" here, which means any value + * whose Type is either Undefined, Null, or + * Object (which includes functions). + * @param {*} value + * @param {string} name + * @see https://webidl.spec.whatwg.org/#es-dictionary + * @see https://tc39.es/ecma262/#table-typeof-operator-results + */ + +/** @type {validateDictionary} */ +const validateDictionary = hideStackFrames((value, name) => { + if (value != null && typeof value !== 'object' && typeof value !== 'function') { + throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value) + } +}) + +/** + * @callback validateArray + * @param {*} value + * @param {string} name + * @param {number} [minLength] + * @returns {asserts value is any[]} + */ + +/** @type {validateArray} */ +const validateArray = hideStackFrames((value, name, minLength = 0) => { + if (!ArrayIsArray(value)) { + throw new ERR_INVALID_ARG_TYPE(name, 'Array', value) + } + if (value.length < minLength) { + const reason = `must be longer than ${minLength}` + throw new ERR_INVALID_ARG_VALUE(name, value, reason) + } +}) + +/** + * @callback validateStringArray + * @param {*} value + * @param {string} name + * @returns {asserts value is string[]} + */ + +/** @type {validateStringArray} */ +function validateStringArray(value, name) { + validateArray(value, name) + for (let i = 0; i < value.length; i++) { + validateString(value[i], `${name}[${i}]`) + } +} + +/** + * @callback validateBooleanArray + * @param {*} value + * @param {string} name + * @returns {asserts value is boolean[]} + */ + +/** @type {validateBooleanArray} */ +function validateBooleanArray(value, name) { + validateArray(value, name) + for (let i = 0; i < value.length; i++) { + validateBoolean(value[i], `${name}[${i}]`) + } +} + +/** + * @callback validateAbortSignalArray + * @param {*} value + * @param {string} name + * @returns {asserts value is AbortSignal[]} + */ + +/** @type {validateAbortSignalArray} */ +function validateAbortSignalArray(value, name) { + validateArray(value, name) + for (let i = 0; i < value.length; i++) { + const signal = value[i] + const indexedName = `${name}[${i}]` + if (signal == null) { + throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal) + } + validateAbortSignal(signal, indexedName) + } +} + +/** + * @param {*} signal + * @param {string} [name='signal'] + * @returns {asserts signal is keyof signals} + */ +function validateSignalName(signal, name = 'signal') { + validateString(signal, name) + if (signals[signal] === undefined) { + if (signals[StringPrototypeToUpperCase(signal)] !== undefined) { + throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)') + } + throw new ERR_UNKNOWN_SIGNAL(signal) + } +} + +/** + * @callback validateBuffer + * @param {*} buffer + * @param {string} [name='buffer'] + * @returns {asserts buffer is ArrayBufferView} + */ + +/** @type {validateBuffer} */ +const validateBuffer = hideStackFrames((buffer, name = 'buffer') => { + if (!isArrayBufferView(buffer)) { + throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer) + } +}) + +/** + * @param {string} data + * @param {string} encoding + */ +function validateEncoding(data, encoding) { + const normalizedEncoding = normalizeEncoding(encoding) + const length = data.length + if (normalizedEncoding === 'hex' && length % 2 !== 0) { + throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`) + } +} + +/** + * Check that the port number is not NaN when coerced to a number, + * is an integer and that it falls within the legal range of port numbers. + * @param {*} port + * @param {string} [name='Port'] + * @param {boolean} [allowZero=true] + * @returns {number} + */ +function validatePort(port, name = 'Port', allowZero = true) { + if ( + (typeof port !== 'number' && typeof port !== 'string') || + (typeof port === 'string' && StringPrototypeTrim(port).length === 0) || + +port !== +port >>> 0 || + port > 0xffff || + (port === 0 && !allowZero) + ) { + throw new ERR_SOCKET_BAD_PORT(name, port, allowZero) + } + return port | 0 +} + +/** + * @callback validateAbortSignal + * @param {*} signal + * @param {string} name + */ + +/** @type {validateAbortSignal} */ +const validateAbortSignal = hideStackFrames((signal, name) => { + if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) + } +}) + +/** + * @callback validateFunction + * @param {*} value + * @param {string} name + * @returns {asserts value is Function} + */ + +/** @type {validateFunction} */ +const validateFunction = hideStackFrames((value, name) => { + if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) +}) + +/** + * @callback validatePlainFunction + * @param {*} value + * @param {string} name + * @returns {asserts value is Function} + */ + +/** @type {validatePlainFunction} */ +const validatePlainFunction = hideStackFrames((value, name) => { + if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) +}) + +/** + * @callback validateUndefined + * @param {*} value + * @param {string} name + * @returns {asserts value is undefined} + */ + +/** @type {validateUndefined} */ +const validateUndefined = hideStackFrames((value, name) => { + if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value) +}) + +/** + * @template T + * @param {T} value + * @param {string} name + * @param {T[]} union + */ +function validateUnion(value, name, union) { + if (!ArrayPrototypeIncludes(union, value)) { + throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value) + } +} + +/* + The rules for the Link header field are described here: + https://www.rfc-editor.org/rfc/rfc8288.html#section-3 + + This regex validates any string surrounded by angle brackets + (not necessarily a valid URI reference) followed by zero or more + link-params separated by semicolons. +*/ +const linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/ + +/** + * @param {any} value + * @param {string} name + */ +function validateLinkHeaderFormat(value, name) { + if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) { + throw new ERR_INVALID_ARG_VALUE( + name, + value, + 'must be an array or string of format "; rel=preload; as=style"' + ) + } +} + +/** + * @param {any} hints + * @return {string} + */ +function validateLinkHeaderValue(hints) { + if (typeof hints === 'string') { + validateLinkHeaderFormat(hints, 'hints') + return hints + } else if (ArrayIsArray(hints)) { + const hintsLength = hints.length + let result = '' + if (hintsLength === 0) { + return result + } + for (let i = 0; i < hintsLength; i++) { + const link = hints[i] + validateLinkHeaderFormat(link, 'hints') + result += link + if (i !== hintsLength - 1) { + result += ', ' + } + } + return result + } + throw new ERR_INVALID_ARG_VALUE( + 'hints', + hints, + 'must be an array or string of format "; rel=preload; as=style"' + ) +} +module.exports = { + isInt32, + isUint32, + parseFileMode, + validateArray, + validateStringArray, + validateBooleanArray, + validateAbortSignalArray, + validateBoolean, + validateBuffer, + validateDictionary, + validateEncoding, + validateFunction, + validateInt32, + validateInteger, + validateNumber, + validateObject, + validateOneOf, + validatePlainFunction, + validatePort, + validateSignalName, + validateString, + validateUint32, + validateUndefined, + validateUnion, + validateAbortSignal, + validateLinkHeaderValue +} diff --git a/node_modules/readable-stream/lib/ours/browser.js b/node_modules/readable-stream/lib/ours/browser.js new file mode 100644 index 00000000..39acef3d --- /dev/null +++ b/node_modules/readable-stream/lib/ours/browser.js @@ -0,0 +1,35 @@ +'use strict' + +const CustomStream = require('../stream') +const promises = require('../stream/promises') +const originalDestroy = CustomStream.Readable.destroy +module.exports = CustomStream.Readable + +// Explicit export naming is needed for ESM +module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer +module.exports._isUint8Array = CustomStream._isUint8Array +module.exports.isDisturbed = CustomStream.isDisturbed +module.exports.isErrored = CustomStream.isErrored +module.exports.isReadable = CustomStream.isReadable +module.exports.Readable = CustomStream.Readable +module.exports.Writable = CustomStream.Writable +module.exports.Duplex = CustomStream.Duplex +module.exports.Transform = CustomStream.Transform +module.exports.PassThrough = CustomStream.PassThrough +module.exports.addAbortSignal = CustomStream.addAbortSignal +module.exports.finished = CustomStream.finished +module.exports.destroy = CustomStream.destroy +module.exports.destroy = originalDestroy +module.exports.pipeline = CustomStream.pipeline +module.exports.compose = CustomStream.compose +Object.defineProperty(CustomStream, 'promises', { + configurable: true, + enumerable: true, + get() { + return promises + } +}) +module.exports.Stream = CustomStream.Stream + +// Allow default importing +module.exports.default = module.exports diff --git a/node_modules/readable-stream/lib/ours/errors.js b/node_modules/readable-stream/lib/ours/errors.js new file mode 100644 index 00000000..979957e3 --- /dev/null +++ b/node_modules/readable-stream/lib/ours/errors.js @@ -0,0 +1,343 @@ +'use strict' + +const { format, inspect } = require('./util/inspect') +const { AggregateError: CustomAggregateError } = require('./primordials') + +/* + This file is a reduced and adapted version of the main lib/internal/errors.js file defined at + + https://github.com/nodejs/node/blob/main/lib/internal/errors.js + + Don't try to replace with the original file and keep it up to date (starting from E(...) definitions) + with the upstream file. +*/ + +const AggregateError = globalThis.AggregateError || CustomAggregateError +const kIsNodeError = Symbol('kIsNodeError') +const kTypes = [ + 'string', + 'function', + 'number', + 'object', + // Accept 'Function' and 'Object' as alternative to the lower cased version. + 'Function', + 'Object', + 'boolean', + 'bigint', + 'symbol' +] +const classRegExp = /^([A-Z][a-z0-9]*)+$/ +const nodeInternalPrefix = '__node_internal_' +const codes = {} +function assert(value, message) { + if (!value) { + throw new codes.ERR_INTERNAL_ASSERTION(message) + } +} + +// Only use this for integers! Decimal numbers do not work with this function. +function addNumericalSeparator(val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} +function getMessage(key, msg, args) { + if (typeof msg === 'function') { + assert( + msg.length <= args.length, + // Default options do not count. + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` + ) + return msg(...args) + } + const expectedLength = (msg.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 msg + } + return format(msg, ...args) +} +function E(code, message, Base) { + if (!Base) { + Base = Error + } + class NodeError extends Base { + constructor(...args) { + super(getMessage(code, message, args)) + } + toString() { + return `${this.name} [${code}]: ${this.message}` + } + } + Object.defineProperties(NodeError.prototype, { + name: { + value: Base.name, + writable: true, + enumerable: false, + configurable: true + }, + toString: { + value() { + return `${this.name} [${code}]: ${this.message}` + }, + writable: true, + enumerable: false, + configurable: true + } + }) + NodeError.prototype.code = code + NodeError.prototype[kIsNodeError] = true + codes[code] = NodeError +} +function hideStackFrames(fn) { + // We rename the functions that will be hidden to cut off the stacktrace + // at the outermost one + const hidden = nodeInternalPrefix + fn.name + Object.defineProperty(fn, 'name', { + value: hidden + }) + return fn +} +function aggregateTwoErrors(innerError, outerError) { + if (innerError && outerError && innerError !== outerError) { + if (Array.isArray(outerError.errors)) { + // If `outerError` is already an `AggregateError`. + outerError.errors.push(innerError) + return outerError + } + const err = new AggregateError([outerError, innerError], outerError.message) + err.code = outerError.code + return err + } + return innerError || outerError +} +class AbortError extends Error { + constructor(message = 'The operation was aborted', options = undefined) { + if (options !== undefined && typeof options !== 'object') { + throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options) + } + super(message, options) + this.code = 'ABORT_ERR' + this.name = 'AbortError' + } +} +E('ERR_ASSERTION', '%s', Error) +E( + 'ERR_INVALID_ARG_TYPE', + (name, expected, actual) => { + assert(typeof name === 'string', "'name' must be a string") + if (!Array.isArray(expected)) { + expected = [expected] + } + let msg = 'The ' + if (name.endsWith(' argument')) { + // For cases like 'first argument' + msg += `${name} ` + } else { + msg += `"${name}" ${name.includes('.') ? 'property' : 'argument'} ` + } + msg += 'must be ' + const types = [] + const instances = [] + const other = [] + for (const value of expected) { + assert(typeof value === 'string', 'All expected entries have to be of type string') + if (kTypes.includes(value)) { + types.push(value.toLowerCase()) + } else if (classRegExp.test(value)) { + instances.push(value) + } else { + assert(value !== 'object', 'The value "object" should be written as "Object"') + other.push(value) + } + } + + // Special handle `object` in case other instances are allowed to outline + // the differences between each other. + if (instances.length > 0) { + const pos = types.indexOf('object') + if (pos !== -1) { + types.splice(types, pos, 1) + instances.push('Object') + } + } + if (types.length > 0) { + switch (types.length) { + case 1: + msg += `of type ${types[0]}` + break + case 2: + msg += `one of type ${types[0]} or ${types[1]}` + break + default: { + const last = types.pop() + msg += `one of type ${types.join(', ')}, or ${last}` + } + } + if (instances.length > 0 || other.length > 0) { + msg += ' or ' + } + } + if (instances.length > 0) { + switch (instances.length) { + case 1: + msg += `an instance of ${instances[0]}` + break + case 2: + msg += `an instance of ${instances[0]} or ${instances[1]}` + break + default: { + const last = instances.pop() + msg += `an instance of ${instances.join(', ')}, or ${last}` + } + } + if (other.length > 0) { + msg += ' or ' + } + } + switch (other.length) { + case 0: + break + case 1: + if (other[0].toLowerCase() !== other[0]) { + msg += 'an ' + } + msg += `${other[0]}` + break + case 2: + msg += `one of ${other[0]} or ${other[1]}` + break + default: { + const last = other.pop() + msg += `one of ${other.join(', ')}, or ${last}` + } + } + if (actual == null) { + msg += `. Received ${actual}` + } else if (typeof actual === 'function' && actual.name) { + msg += `. Received function ${actual.name}` + } else if (typeof actual === 'object') { + var _actual$constructor + if ( + (_actual$constructor = actual.constructor) !== null && + _actual$constructor !== undefined && + _actual$constructor.name + ) { + msg += `. Received an instance of ${actual.constructor.name}` + } else { + const inspected = inspect(actual, { + depth: -1 + }) + msg += `. Received ${inspected}` + } + } else { + let inspected = inspect(actual, { + colors: false + }) + if (inspected.length > 25) { + inspected = `${inspected.slice(0, 25)}...` + } + msg += `. Received type ${typeof actual} (${inspected})` + } + return msg + }, + TypeError +) +E( + 'ERR_INVALID_ARG_VALUE', + (name, value, reason = 'is invalid') => { + let inspected = 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 +) +E( + 'ERR_INVALID_RETURN_VALUE', + (input, name, value) => { + var _value$constructor + const type = + value !== null && + value !== undefined && + (_value$constructor = value.constructor) !== null && + _value$constructor !== undefined && + _value$constructor.name + ? `instance of ${value.constructor.name}` + : `type ${typeof value}` + return `Expected ${input} to be returned from the "${name}"` + ` function but got ${type}.` + }, + TypeError +) +E( + 'ERR_MISSING_ARGS', + (...args) => { + assert(args.length > 0, 'At least one arg needs to be specified') + let msg + const len = args.length + args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(' or ') + switch (len) { + case 1: + msg += `The ${args[0]} argument` + break + case 2: + msg += `The ${args[0]} and ${args[1]} arguments` + break + default: + { + const last = args.pop() + msg += `The ${args.join(', ')}, and ${last} arguments` + } + break + } + return `${msg} must be specified` + }, + TypeError +) +E( + 'ERR_OUT_OF_RANGE', + (str, range, input) => { + assert(range, 'Missing "range" argument') + let received + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + const limit = BigInt(2) ** BigInt(32) + if (input > limit || input < -limit) { + received = addNumericalSeparator(received) + } + received += 'n' + } else { + received = inspect(input) + } + return `The value of "${str}" is out of range. It must be ${range}. Received ${received}` + }, + RangeError +) +E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error) +E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error) +E('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error) +E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error) +E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error) +E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError) +E('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error) +E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error) +E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error) +E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error) +E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError) +module.exports = { + AbortError, + aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), + hideStackFrames, + codes +} diff --git a/node_modules/readable-stream/lib/ours/index.js b/node_modules/readable-stream/lib/ours/index.js new file mode 100644 index 00000000..6cdd2d78 --- /dev/null +++ b/node_modules/readable-stream/lib/ours/index.js @@ -0,0 +1,65 @@ +'use strict' + +const Stream = require('stream') +if (Stream && process.env.READABLE_STREAM === 'disable') { + const promises = Stream.promises + + // Explicit export naming is needed for ESM + module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer + module.exports._isUint8Array = Stream._isUint8Array + module.exports.isDisturbed = Stream.isDisturbed + module.exports.isErrored = Stream.isErrored + module.exports.isReadable = Stream.isReadable + module.exports.Readable = Stream.Readable + module.exports.Writable = Stream.Writable + module.exports.Duplex = Stream.Duplex + module.exports.Transform = Stream.Transform + module.exports.PassThrough = Stream.PassThrough + module.exports.addAbortSignal = Stream.addAbortSignal + module.exports.finished = Stream.finished + module.exports.destroy = Stream.destroy + module.exports.pipeline = Stream.pipeline + module.exports.compose = Stream.compose + Object.defineProperty(Stream, 'promises', { + configurable: true, + enumerable: true, + get() { + return promises + } + }) + module.exports.Stream = Stream.Stream +} else { + const CustomStream = require('../stream') + const promises = require('../stream/promises') + const originalDestroy = CustomStream.Readable.destroy + module.exports = CustomStream.Readable + + // Explicit export naming is needed for ESM + module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer + module.exports._isUint8Array = CustomStream._isUint8Array + module.exports.isDisturbed = CustomStream.isDisturbed + module.exports.isErrored = CustomStream.isErrored + module.exports.isReadable = CustomStream.isReadable + module.exports.Readable = CustomStream.Readable + module.exports.Writable = CustomStream.Writable + module.exports.Duplex = CustomStream.Duplex + module.exports.Transform = CustomStream.Transform + module.exports.PassThrough = CustomStream.PassThrough + module.exports.addAbortSignal = CustomStream.addAbortSignal + module.exports.finished = CustomStream.finished + module.exports.destroy = CustomStream.destroy + module.exports.destroy = originalDestroy + module.exports.pipeline = CustomStream.pipeline + module.exports.compose = CustomStream.compose + Object.defineProperty(CustomStream, 'promises', { + configurable: true, + enumerable: true, + get() { + return promises + } + }) + module.exports.Stream = CustomStream.Stream +} + +// Allow default importing +module.exports.default = module.exports diff --git a/node_modules/readable-stream/lib/ours/primordials.js b/node_modules/readable-stream/lib/ours/primordials.js new file mode 100644 index 00000000..81856fcf --- /dev/null +++ b/node_modules/readable-stream/lib/ours/primordials.js @@ -0,0 +1,124 @@ +'use strict' + +/* + This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at + + https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js + + Don't try to replace with the original file and keep it up to date with the upstream file. +*/ + +// This is a simplified version of AggregateError +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`) + } + let message = '' + for (let i = 0; i < errors.length; i++) { + message += ` ${errors[i].stack}\n` + } + super(message) + this.name = 'AggregateError' + this.errors = errors + } +} +module.exports = { + AggregateError, + ArrayIsArray(self) { + return Array.isArray(self) + }, + ArrayPrototypeIncludes(self, el) { + return self.includes(el) + }, + ArrayPrototypeIndexOf(self, el) { + return self.indexOf(el) + }, + ArrayPrototypeJoin(self, sep) { + return self.join(sep) + }, + ArrayPrototypeMap(self, fn) { + return self.map(fn) + }, + ArrayPrototypePop(self, el) { + return self.pop(el) + }, + ArrayPrototypePush(self, el) { + return self.push(el) + }, + ArrayPrototypeSlice(self, start, end) { + return self.slice(start, end) + }, + Error, + FunctionPrototypeCall(fn, thisArgs, ...args) { + return fn.call(thisArgs, ...args) + }, + FunctionPrototypeSymbolHasInstance(self, instance) { + return Function.prototype[Symbol.hasInstance].call(self, instance) + }, + MathFloor: Math.floor, + Number, + NumberIsInteger: Number.isInteger, + NumberIsNaN: Number.isNaN, + NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, + NumberParseInt: Number.parseInt, + ObjectDefineProperties(self, props) { + return Object.defineProperties(self, props) + }, + ObjectDefineProperty(self, name, prop) { + return Object.defineProperty(self, name, prop) + }, + ObjectGetOwnPropertyDescriptor(self, name) { + return Object.getOwnPropertyDescriptor(self, name) + }, + ObjectKeys(obj) { + return Object.keys(obj) + }, + ObjectSetPrototypeOf(target, proto) { + return Object.setPrototypeOf(target, proto) + }, + Promise, + PromisePrototypeCatch(self, fn) { + return self.catch(fn) + }, + PromisePrototypeThen(self, thenFn, catchFn) { + return self.then(thenFn, catchFn) + }, + PromiseReject(err) { + return Promise.reject(err) + }, + PromiseResolve(val) { + return Promise.resolve(val) + }, + ReflectApply: Reflect.apply, + RegExpPrototypeTest(self, value) { + return self.test(value) + }, + SafeSet: Set, + String, + StringPrototypeSlice(self, start, end) { + return self.slice(start, end) + }, + StringPrototypeToLowerCase(self) { + return self.toLowerCase() + }, + StringPrototypeToUpperCase(self) { + return self.toUpperCase() + }, + StringPrototypeTrim(self) { + return self.trim() + }, + Symbol, + SymbolFor: Symbol.for, + SymbolAsyncIterator: Symbol.asyncIterator, + SymbolHasInstance: Symbol.hasInstance, + SymbolIterator: Symbol.iterator, + SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'), + SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'), + TypedArrayPrototypeSet(self, buf, len) { + return self.set(buf, len) + }, + Boolean, + Uint8Array +} diff --git a/node_modules/readable-stream/lib/ours/util.js b/node_modules/readable-stream/lib/ours/util.js new file mode 100644 index 00000000..b560361f --- /dev/null +++ b/node_modules/readable-stream/lib/ours/util.js @@ -0,0 +1,148 @@ +'use strict' + +const bufferModule = require('buffer') +const { format, inspect } = require('./util/inspect') +const { + codes: { ERR_INVALID_ARG_TYPE } +} = require('./errors') +const { kResistStopPropagation, AggregateError, SymbolDispose } = require('./primordials') +const AbortSignal = globalThis.AbortSignal || require('abort-controller').AbortSignal +const AbortController = globalThis.AbortController || require('abort-controller').AbortController +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor +const Blob = globalThis.Blob || bufferModule.Blob +/* eslint-disable indent */ +const isBlob = + typeof Blob !== 'undefined' + ? function isBlob(b) { + // eslint-disable-next-line indent + return b instanceof Blob + } + : function isBlob(b) { + return false + } +/* eslint-enable indent */ + +const validateAbortSignal = (signal, name) => { + if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) + } +} +const validateFunction = (value, name) => { + if (typeof value !== 'function') { + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) + } +} +module.exports = { + AggregateError, + kEmptyObject: Object.freeze({}), + once(callback) { + let called = false + return function (...args) { + if (called) { + return + } + called = true + callback.apply(this, args) + } + }, + createDeferredPromise: function () { + let resolve + let reject + + // eslint-disable-next-line promise/param-names + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { + promise, + resolve, + reject + } + }, + promisify(fn) { + return new Promise((resolve, reject) => { + fn((err, ...args) => { + if (err) { + return reject(err) + } + return resolve(...args) + }) + }) + }, + debuglog() { + return function () {} + }, + format, + inspect, + types: { + isAsyncFunction(fn) { + return fn instanceof AsyncFunction + }, + isArrayBufferView(arr) { + return ArrayBuffer.isView(arr) + } + }, + isBlob, + deprecate(fn, message) { + return fn + }, + addAbortListener: + require('events').addAbortListener || + function addAbortListener(signal, listener) { + if (signal === undefined) { + throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal) + } + validateAbortSignal(signal, 'signal') + validateFunction(listener, 'listener') + let removeEventListener + if (signal.aborted) { + queueMicrotask(() => listener()) + } else { + signal.addEventListener('abort', listener, { + __proto__: null, + once: true, + [kResistStopPropagation]: true + }) + removeEventListener = () => { + signal.removeEventListener('abort', listener) + } + } + return { + __proto__: null, + [SymbolDispose]() { + var _removeEventListener + ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined + ? undefined + : _removeEventListener() + } + } + }, + AbortSignalAny: + AbortSignal.any || + function AbortSignalAny(signals) { + // Fast path if there is only one signal. + if (signals.length === 1) { + return signals[0] + } + const ac = new AbortController() + const abort = () => ac.abort() + signals.forEach((signal) => { + validateAbortSignal(signal, 'signals') + signal.addEventListener('abort', abort, { + once: true + }) + }) + ac.signal.addEventListener( + 'abort', + () => { + signals.forEach((signal) => signal.removeEventListener('abort', abort)) + }, + { + once: true + } + ) + return ac.signal + } +} +module.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom') diff --git a/node_modules/readable-stream/lib/ours/util/inspect.js b/node_modules/readable-stream/lib/ours/util/inspect.js new file mode 100644 index 00000000..e0084457 --- /dev/null +++ b/node_modules/readable-stream/lib/ours/util/inspect.js @@ -0,0 +1,55 @@ +'use strict' + +/* + This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at + + https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js + + Don't try to replace with the original file and keep it up to date with the upstream file. +*/ +module.exports = { + format(format, ...args) { + // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args + return format.replace(/%([sdifj])/g, function (...[_unused, type]) { + const replacement = args.shift() + if (type === 'f') { + return replacement.toFixed(6) + } else if (type === 'j') { + return JSON.stringify(replacement) + } else if (type === 's' && typeof replacement === 'object') { + const ctor = replacement.constructor !== Object ? replacement.constructor.name : '' + return `${ctor} {}`.trim() + } else { + return replacement.toString() + } + }) + }, + inspect(value) { + // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options + switch (typeof value) { + case 'string': + if (value.includes("'")) { + if (!value.includes('"')) { + return `"${value}"` + } else if (!value.includes('`') && !value.includes('${')) { + return `\`${value}\`` + } + } + return `'${value}'` + case 'number': + if (isNaN(value)) { + return 'NaN' + } else if (Object.is(value, -0)) { + return String(value) + } + return value + case 'bigint': + return `${String(value)}n` + case 'boolean': + case 'undefined': + return String(value) + case 'object': + return '{}' + } + } +} diff --git a/node_modules/readable-stream/lib/stream.js b/node_modules/readable-stream/lib/stream.js new file mode 100644 index 00000000..1e2cab31 --- /dev/null +++ b/node_modules/readable-stream/lib/stream.js @@ -0,0 +1,143 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict' + +/* replacement start */ + +const { Buffer } = require('buffer') + +/* replacement end */ + +const { ObjectDefineProperty, ObjectKeys, ReflectApply } = require('./ours/primordials') +const { + promisify: { custom: customPromisify } +} = require('./ours/util') +const { streamReturningOperators, promiseReturningOperators } = require('./internal/streams/operators') +const { + codes: { ERR_ILLEGAL_CONSTRUCTOR } +} = require('./ours/errors') +const compose = require('./internal/streams/compose') +const { setDefaultHighWaterMark, getDefaultHighWaterMark } = require('./internal/streams/state') +const { pipeline } = require('./internal/streams/pipeline') +const { destroyer } = require('./internal/streams/destroy') +const eos = require('./internal/streams/end-of-stream') +const internalBuffer = {} +const promises = require('./stream/promises') +const utils = require('./internal/streams/utils') +const Stream = (module.exports = require('./internal/streams/legacy').Stream) +Stream.isDestroyed = utils.isDestroyed +Stream.isDisturbed = utils.isDisturbed +Stream.isErrored = utils.isErrored +Stream.isReadable = utils.isReadable +Stream.isWritable = utils.isWritable +Stream.Readable = require('./internal/streams/readable') +for (const key of ObjectKeys(streamReturningOperators)) { + const op = streamReturningOperators[key] + function fn(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR() + } + return Stream.Readable.from(ReflectApply(op, this, args)) + } + ObjectDefineProperty(fn, 'name', { + __proto__: null, + value: op.name + }) + ObjectDefineProperty(fn, 'length', { + __proto__: null, + value: op.length + }) + ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, + value: fn, + enumerable: false, + configurable: true, + writable: true + }) +} +for (const key of ObjectKeys(promiseReturningOperators)) { + const op = promiseReturningOperators[key] + function fn(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR() + } + return ReflectApply(op, this, args) + } + ObjectDefineProperty(fn, 'name', { + __proto__: null, + value: op.name + }) + ObjectDefineProperty(fn, 'length', { + __proto__: null, + value: op.length + }) + ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, + value: fn, + enumerable: false, + configurable: true, + writable: true + }) +} +Stream.Writable = require('./internal/streams/writable') +Stream.Duplex = require('./internal/streams/duplex') +Stream.Transform = require('./internal/streams/transform') +Stream.PassThrough = require('./internal/streams/passthrough') +Stream.pipeline = pipeline +const { addAbortSignal } = require('./internal/streams/add-abort-signal') +Stream.addAbortSignal = addAbortSignal +Stream.finished = eos +Stream.destroy = destroyer +Stream.compose = compose +Stream.setDefaultHighWaterMark = setDefaultHighWaterMark +Stream.getDefaultHighWaterMark = getDefaultHighWaterMark +ObjectDefineProperty(Stream, 'promises', { + __proto__: null, + configurable: true, + enumerable: true, + get() { + return promises + } +}) +ObjectDefineProperty(pipeline, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises.pipeline + } +}) +ObjectDefineProperty(eos, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises.finished + } +}) + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream +Stream._isUint8Array = function isUint8Array(value) { + return value instanceof Uint8Array +} +Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) +} diff --git a/node_modules/readable-stream/lib/stream/promises.js b/node_modules/readable-stream/lib/stream/promises.js new file mode 100644 index 00000000..5d4ce15f --- /dev/null +++ b/node_modules/readable-stream/lib/stream/promises.js @@ -0,0 +1,43 @@ +'use strict' + +const { ArrayPrototypePop, Promise } = require('../ours/primordials') +const { isIterable, isNodeStream, isWebStream } = require('../internal/streams/utils') +const { pipelineImpl: pl } = require('../internal/streams/pipeline') +const { finished } = require('../internal/streams/end-of-stream') +require('../../lib/stream.js') +function pipeline(...streams) { + return new Promise((resolve, reject) => { + let signal + let end + const lastArg = streams[streams.length - 1] + if ( + lastArg && + typeof lastArg === 'object' && + !isNodeStream(lastArg) && + !isIterable(lastArg) && + !isWebStream(lastArg) + ) { + const options = ArrayPrototypePop(streams) + signal = options.signal + end = options.end + } + pl( + streams, + (err, value) => { + if (err) { + reject(err) + } else { + resolve(value) + } + }, + { + signal, + end + } + ) + }) +} +module.exports = { + finished, + pipeline +} diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 00000000..98b48e68 --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,88 @@ +{ + "name": "readable-stream", + "version": "4.7.0", + "description": "Node.js Streams, a user-land copy of the stream library from Node.js", + "homepage": "https://github.com/nodejs/readable-stream", + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "https://choosealicense.com/licenses/mit/" + } + ], + "keywords": [ + "readable", + "stream", + "pipe" + ], + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "bugs": { + "url": "https://github.com/nodejs/readable-stream/issues" + }, + "main": "lib/ours/index.js", + "files": [ + "lib", + "LICENSE", + "README.md" + ], + "browser": { + "util": "./lib/ours/util.js", + "./lib/ours/index.js": "./lib/ours/browser.js" + }, + "scripts": { + "build": "node build/build.mjs 18.19.0", + "postbuild": "prettier -w lib test", + "test": "tap --rcfile=./tap.yml test/parallel/test-*.js test/ours/test-*.js", + "test:prepare": "node test/browser/runner-prepare.mjs", + "test:browsers": "node test/browser/runner-browser.mjs", + "test:bundlers": "node test/browser/runner-node.mjs", + "test:readable-stream-only": "node readable-stream-test/runner-prepare.mjs", + "coverage": "c8 -c ./c8.json tap --rcfile=./tap.yml test/parallel/test-*.js test/ours/test-*.js", + "format": "prettier -w src lib test", + "test:format": "prettier -c src lib test", + "lint": "eslint src" + }, + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "devDependencies": { + "@babel/core": "^7.17.10", + "@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.7", + "@babel/plugin-proposal-optional-chaining": "^7.16.7", + "@eslint/eslintrc": "^3.2.0", + "@rollup/plugin-commonjs": "^22.0.0", + "@rollup/plugin-inject": "^4.0.4", + "@rollup/plugin-node-resolve": "^13.3.0", + "@sinonjs/fake-timers": "^9.1.2", + "browserify": "^17.0.0", + "c8": "^7.11.2", + "esbuild": "^0.19.9", + "esbuild-plugin-alias": "^0.2.1", + "eslint": "^8.15.0", + "eslint-config-standard": "^17.0.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-n": "^15.2.0", + "eslint-plugin-promise": "^6.0.0", + "playwright": "^1.21.1", + "prettier": "^2.6.2", + "rollup": "^2.72.1", + "rollup-plugin-polyfill-node": "^0.9.0", + "tap": "^16.2.0", + "tap-mocha-reporter": "^5.0.3", + "tape": "^5.5.3", + "tar": "^6.1.11", + "undici": "^5.1.1", + "webpack": "^5.72.1", + "webpack-cli": "^4.9.2" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } +} diff --git a/node_modules/readable-web-to-node-stream/README.md b/node_modules/readable-web-to-node-stream/README.md new file mode 100644 index 00000000..6e8756e7 --- /dev/null +++ b/node_modules/readable-web-to-node-stream/README.md @@ -0,0 +1,70 @@ +[![CI browser tests](https://github.com/Borewit/readable-web-to-node-stream/actions/workflows/xvfb-ci.yml/badge.svg)](https://github.com/Borewit/readable-web-to-node-stream/actions/workflows/xvfb-ci.yml) +[![NPM version](https://badge.fury.io/js/readable-web-to-node-stream.svg)](https://npmjs.org/package/readable-web-to-node-stream) +[![npm downloads](http://img.shields.io/npm/dm/readable-web-to-node-stream.svg)](https://npmcharts.com/compare/readable-web-to-node-stream) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/readable-web-to-node-stream/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/readable-web-to-node-stream?targetFile=package.json) +[![Codacy Badge](https://app.codacy.com/project/badge/Grade/d4b511481b3a4634b6ca5c0724407eb9)](https://www.codacy.com/gh/Borewit/peek-readable/dashboard?utm_source=github.com&utm_medium=referral&utm_content=Borewit/peek-readable&utm_campaign=Badge_Grade) +[![Coverage Status](https://coveralls.io/repos/github/Borewit/readable-web-to-node-stream/badge.svg?branch=master)](https://coveralls.io/github/Borewit/readable-web-to-node-stream?branch=master) +[![Minified size](https://badgen.net/bundlephobia/min/readable-web-to-node-stream)](https://bundlephobia.com/result?p=readable-web-to-node-stream) + +# readable-web-to-node-stream + +Converts a [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) into a [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams). + +To covert the other way around, from [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) to [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader), +you may use [node-readable-to-web-readable-stream](https://github.com/Borewit/node-readable-to-web-readable-stream). + +## Installation +Install via [npm](http://npmjs.org/): + +```bash +npm install readable-web-to-node-stream +``` +or [yarn](https://yarnpkg.com/): +```bash +yarn add readable-web-to-node-stream +``` + +## Compatibility + +Source is written in TypeScript and compiled to ECMAScript 2017 (ES8). + +Unit tests are performed on the following browsers: +* Latest Google Chrome 74.0 + + +## Example + +Import readable-web-stream-to-node in JavaScript: +```js +const {ReadableWebToNodeStream} = require('readable-web-to-node-stream'); + +async function download(url) { + const response = await fetch(url); + const readableWebStream = response.body; + const nodeStream = new ReadableWebToNodeStream(readableWebStream); +} +``` + +## API + +**constructor(stream: ReadableStream): Promise** + +`stream: ReadableStream`: the [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader). + +**close(): Promise** +Will cancel close the Readable-node stream, and will release Web-API-readable-stream. + +**waitForReadToComplete(): Promise** +If there is no unresolved read call to Web-API Readable​Stream immediately returns, otherwise it will wait until the read is resolved. + +## Licence + +(The MIT License) + +Copyright (c) 2019 Borewit + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/readable-web-to-node-stream/lib/index.d.ts b/node_modules/readable-web-to-node-stream/lib/index.d.ts new file mode 100644 index 00000000..5623731a --- /dev/null +++ b/node_modules/readable-web-to-node-stream/lib/index.d.ts @@ -0,0 +1,39 @@ +import { Readable } from 'readable-stream'; +/** + * Converts a Web-API stream into Node stream.Readable class + * Node stream readable: https://nodejs.org/api/stream.html#stream_readable_streams + * Web API readable-stream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + * Node readable stream: https://nodejs.org/api/stream.html#stream_readable_streams + */ +export declare class ReadableWebToNodeStream extends Readable { + bytesRead: number; + released: boolean; + /** + * Default web API stream reader + * https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader + */ + private reader; + private pendingRead; + /** + * + * @param stream ReadableStream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + */ + constructor(stream: ReadableStream | ReadableStream); + /** + * Implementation of readable._read(size). + * When readable._read() is called, if data is available from the resource, + * the implementation should begin pushing that data into the read queue + * https://nodejs.org/api/stream.html#stream_readable_read_size_1 + */ + _read(): void; + /** + * If there is no unresolved read call to Web-API Readable​Stream immediately returns; + * otherwise will wait until the read is resolved. + */ + waitForReadToComplete(): Promise; + /** + * Close wrapper + */ + close(): Promise; + private syncAndRelease; +} diff --git a/node_modules/readable-web-to-node-stream/lib/index.js b/node_modules/readable-web-to-node-stream/lib/index.js new file mode 100644 index 00000000..6daffb49 --- /dev/null +++ b/node_modules/readable-web-to-node-stream/lib/index.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadableWebToNodeStream = void 0; +const readable_stream_1 = require("readable-stream"); +/** + * Converts a Web-API stream into Node stream.Readable class + * Node stream readable: https://nodejs.org/api/stream.html#stream_readable_streams + * Web API readable-stream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + * Node readable stream: https://nodejs.org/api/stream.html#stream_readable_streams + */ +class ReadableWebToNodeStream extends readable_stream_1.Readable { + /** + * + * @param stream ReadableStream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + */ + constructor(stream) { + super(); + this.bytesRead = 0; + this.released = false; + this.reader = stream.getReader(); + } + /** + * Implementation of readable._read(size). + * When readable._read() is called, if data is available from the resource, + * the implementation should begin pushing that data into the read queue + * https://nodejs.org/api/stream.html#stream_readable_read_size_1 + */ + _read() { + // Should start pushing data into the queue + // Read data from the underlying Web-API-readable-stream + if (this.released) { + this.push(null); // Signal EOF + return; + } + this.pendingRead = this.reader + .read() + .then((data) => { + delete this.pendingRead; + if (data.done || this.released) { + this.push(null); // Signal EOF + } + else { + this.bytesRead += data.value.length; + this.push(data.value); // Push new data to the queue + } + }) + .catch((err) => { + this.destroy(err); + }); + } + /** + * If there is no unresolved read call to Web-API Readable​Stream immediately returns; + * otherwise will wait until the read is resolved. + */ + async waitForReadToComplete() { + if (this.pendingRead) { + await this.pendingRead; + } + } + /** + * Close wrapper + */ + async close() { + await this.syncAndRelease(); + } + async syncAndRelease() { + this.released = true; + await this.waitForReadToComplete(); + await this.reader.releaseLock(); + } +} +exports.ReadableWebToNodeStream = ReadableWebToNodeStream; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/readable-web-to-node-stream/package.json b/node_modules/readable-web-to-node-stream/package.json new file mode 100644 index 00000000..a9408970 --- /dev/null +++ b/node_modules/readable-web-to-node-stream/package.json @@ -0,0 +1,84 @@ +{ + "name": "readable-web-to-node-stream", + "version": "3.0.4", + "description": "Converts a Web-API readable-stream into a Node readable-stream.", + "type": "commonjs", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "files": [ + "lib/index.js", + "lib/index.d.ts" + ], + "engines": { + "node": ">=8" + }, + "scripts": { + "clean": "del-cli 'lib/**/*.js' 'lib/**/*.js.map' 'lib/**/*.d.ts' 'coverage'", + "compile-lib": "tsc -p lib/tsconfig.json", + "compile-test": "tsc -p lib/tsconfig.spec.json", + "prepublishOnly": "yarn run build", + "build": "yarn run compile-lib && npm run compile-test", + "lint-ts": "biome check", + "lint": "yarn run biome check", + "test": "karma start --single-run", + "karma-headless": "karma start --single-run --reporters coverage-istanbul,spec,progress", + "karma": "karma start", + "karma-firefox": "karma start --browsers Firefox", + "karma-once": "karma start --browsers Chrome --single-run", + "post-coveralls": "coveralls < coverage/lcov.info", + "post-codacy": " codacy-coverage < coverage/lcov.info" + }, + "keywords": [ + "stream.readable", + "web", + "node", + "browser", + "stream", + "covert", + "coverter", + "readable", + "readablestream" + ], + "repository": "https://github.com/Borewit/readable-web-to-node-stream.git", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/Borewit/readable-web-to-node-stream/issues" + }, + "dependencies": { + "readable-stream": "^4.7.0" + }, + "devDependencies": { + "@biomejs/biome": "^1.9.4", + "@types/jasmine": "^5.1.6", + "@types/node": "^22.13.4", + "@types/readable-stream": "^4.0.18", + "coveralls": "^3.1.1", + "del-cli": "^6.0.0", + "istanbul-instrumenter-loader": "^3.0.1", + "jasmine-core": "^5.6.0", + "karma": "^6.4.4", + "karma-chrome-launcher": "^3.2.0", + "karma-coverage-istanbul-reporter": "^3.0.3", + "karma-edge-launcher": "^0.4.2", + "karma-firefox-launcher": "^2.1.3", + "karma-jasmine": "^5.1.0", + "karma-jasmine-html-reporter": "^2.1.0", + "karma-safari-launcher": "^1.0.0", + "karma-spec-reporter": "^0.0.36", + "karma-webpack": "^5.0.1", + "music-metadata-browser": "^2.5.11", + "ts-loader": "^9.5.2", + "typescript": "^5.7.3", + "webpack": "^5.98.0", + "webpack-cli": "^6.0.1" + }, + "packageManager": "yarn@4.6.0" +} diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 00000000..778edb20 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 00000000..5fd58315 --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 00000000..2e89e63f --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 00000000..b2bb1411 --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/node_modules/strtok3/LICENSE b/node_modules/strtok3/LICENSE new file mode 100644 index 00000000..c85ef2c1 --- /dev/null +++ b/node_modules/strtok3/LICENSE @@ -0,0 +1,15 @@ +Copyright (c) 2017, Borewit +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/strtok3/README.md b/node_modules/strtok3/README.md new file mode 100644 index 00000000..f45a723a --- /dev/null +++ b/node_modules/strtok3/README.md @@ -0,0 +1,304 @@ +![Node.js CI](https://github.com/Borewit/strtok3/workflows/Node.js%20CI/badge.svg) +[![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3) +[![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30) +[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/8526/branches/103329/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=8526&bid=103329) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json) +[![Total alerts](https://img.shields.io/lgtm/alerts/g/Borewit/strtok3.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/strtok3/alerts/) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/59dd6795e61949fb97066ca52e6097ef)](https://www.codacy.com/app/Borewit/strtok3?utm_source=github.com&utm_medium=referral&utm_content=Borewit/strtok3&utm_campaign=Badge_Grade) +[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Borewit/strtok3.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/strtok3/context:javascript) +# strtok3 + +A promise based streaming [*tokenizer*](#tokenizer) for [Node.js](http://nodejs.org) and browsers. +This node module is a successor of [strtok2](https://github.com/Borewit/strtok2). + +The `strtok3` contains a few methods to turn different input into a [*tokenizer*](#tokenizer). Designed to +* Support a streaming environment +* Decoding of binary data, strings and numbers in mind +* Read [predefined](https://github.com/Borewit/token-types) or custom tokens. +* Optimized [*tokenizers*](#tokenizer) for reading from [file](#method-strtok3fromfile), [stream](#method-strtok3fromstream) or [buffer](#method-strtok3frombuffer). + +It can read from: +* A file (taking a file path as an input) +* A Node.js [stream](https://nodejs.org/api/stream.html). +* A [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) +* HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http). +* Chunked [Amazon S3](https://aws.amazon.com/s3) access provided by [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3). + +## Installation + +```sh +npm install strtok3 +``` + +### Compatibility + +NPM module is compliant with [ECMAScript 2018 (ES9)](https://en.wikipedia.org/wiki/ECMAScript#9th_Edition_%E2%80%93_ECMAScript_2018). + +## API + +Use one of the methods to instantiate an [*abstract tokenizer*](#tokenizer): +* [strtok3.fromFile](#method-strtok3fromfile) +* [strtok3.fromStream](#method-strtok3fromstream) +* [strtok3.fromBuffer](#method-strtok3fromBuffer) +* [strtok3.fromUint8Array](#method-strtok3fromUint8Array) + +### strtok3 methods + +All of the strtok3 methods return a [*tokenizer*](#tokenizer), either directly or via a promise. + +#### Method `strtok3.fromFile()` + +| Parameter | Type | Description | +|-----------|-----------------------|----------------------------| +| path | Path to file (string) | Path to file to read from | + +> __Note__: that [file-information](#file-information) is automatically added. + +Returns, via a promise, a [*tokenizer*](#tokenizer) which can be used to parse a file. + +```js +const strtok3 = require('strtok3'); +const Token = require('token-types'); + +(async () => { + + const tokenizer = await strtok3.fromFile("somefile.bin"); + try { + const myNumber = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myNumber}`); + } finally { + tokenizer.close(); // Close the file + } +})(); + +``` + +#### Method `strtok3.fromStream()` + +Create [*tokenizer*](#tokenizer) from a node.js [readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +| Parameter | Optional | Type | Description | +|-----------|-----------|-----------------------------------------------------------------------------|--------------------------| +| stream | no | [Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable) | Stream to read from | +| fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information | + +Returns a [*tokenizer*](#tokenizer), via a Promise, which can be used to parse a buffer. + +```js +const strtok3 = require('strtok3'); +const Token = require('token-types'); + +strtok3.fromStream(stream).then(tokenizer => { + return tokenizer.readToken(Token.UINT8).then(myUint8Number => { + console.log(`My number: ${myUint8Number}`); + }); +}); +``` + +#### Method `strtok3.fromBuffer()` + +| Parameter | Optional | Type | Description | +|------------|----------|--------------------------------------------------|----------------------------------------| +| uint8Array | no | [Uint8Array](https://nodejs.org/api/buffer.html) | Uint8Array or Buffer to read from | +| fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information | + +Returns a [*tokenizer*](#tokenizer) which can be used to parse the provided buffer. + +```js +const strtok3 = require('strtok3'); + +const tokenizer = strtok3.fromBuffer(buffer); + +tokenizer.readToken(Token.UINT8).then(myUint8Number => { + console.log(`My number: ${myUint8Number}`); +}); +``` + +## Tokenizer +The tokenizer allows us to *read* or *peek* from the *tokenizer-stream*. The *tokenizer-stream* is an abstraction of a [stream](https://nodejs.org/api/stream.html), file or [Buffer](https://nodejs.org/api/buffer.html). +It can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http); + +What is the difference with Nodejs.js stream? +* The *tokenizer-stream* supports jumping / seeking in a the *tokenizer-stream* using [`tokenizer.ignore()`](#method-tokenizerignore) +* In addition to *read* methods, it has *peek* methods, to read a ahead and check what is coming. + +The [tokenizer.position](#attribute-tokenizerposition) keeps tracks of the read position. + +### strtok3 attributes + +#### Attribute `tokenizer.fileInfo` +Optional attribute describing the file information, see [IFileInfo](#IFileInfo) + +#### Attribute `tokenizer.position` +Pointer to the current position in the [*tokenizer*](#tokenizer) stream. +If a *position* is provided to a *read* or *peek* method, is should be, at least, equal or greater than this value. + +### Tokenizer methods + +There are two kind of methods: +1. *read* methods: used to read a *token* of [Buffer](https://nodejs.org/api/buffer.html) from the [*tokenizer*](#tokenizer). The position of the *tokenizer-stream* will advance with the size of the token. +2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead. + +#### Method `tokenizer.readBuffer()` + +Read buffer from stream. +`readBuffer(buffer, options?)` + +| Parameter | Type | Description | +|------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| buffer | [Buffer](https://nodejs.org/api/buffer.html) | Uint8Array | Target buffer to write the data read to | +| options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read | + +Return value `Promise` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set. + +#### Method `tokenizer.peekBuffer()` + +Peek (read ahead) buffer from [*tokenizer*](#tokenizer) +`peekBuffer(buffer, options?)` + +| Parameter | Type | Description | +|------------|-----------------------------------------|-----------------------------------------------------| +| buffer | Buffer | Uint8Array | Target buffer to write the data read (peeked) to. | +| options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read. | | + +Return value `Promise` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set. + +#### Method `tokenizer.readToken()` + +Read a *token* from the tokenizer-stream. +`readToken(token, position?)` + +| Parameter | Type | Description | +|------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- | +| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. | +| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. | + +Return value `Promise`. Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set. + +#### Method `tokenizer.peekToken()` + +Peek a *token* from the [*tokenizer*](#tokenizer). +`peekToken(token, position?)` + +| Parameter | Type | Description | +|------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------| +| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. | +| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. | + +Return value `Promise` Promise with token value peeked from the [*tokenizer*](#tokenizer). + +#### Method `tokenizer.readNumber()` + +Peek a numeric [*token*](#token) from the [*tokenizer*](#tokenizer). +`readNumber(token)` + +| Parameter | Type | Description | +|------------|---------------------------------|----------------------------------------------------| +| token | [IGetToken](#IGetToken) | Numeric token to read from the tokenizer-stream. | + +Return value `Promise` Promise with number peeked from the *tokenizer-stream*. + +#### Method `tokenizer.ignore()` + +Advanse the offset pointer with the number of bytes provided. +`ignore(length)` + +| Parameter | Type | Description | +|------------|--------|----------------------------------------------------------------------| +| ignore | number | Numeric of bytes to ignore. Will advance the `tokenizer.position` | + +Return value `Promise` Promise with number peeked from the *tokenizer-stream*. + +#### Method `tokenizer.close()` +Clean up resources, such as closing a file pointer if applicable. + +### IReadChunkOptions + +Each attribute is optional: + +| Attribute | Type | Description | +|-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| offset | number | The offset in the buffer to start writing at; if not provided, start at 0 | +| length | number | Requested number of bytes to read. | +| position | number | Position where to peek from the file. If position is null, data will be read from the [current file position](#attribute-tokenizerposition). Position may not be less then [tokenizer.position](#attribute-tokenizerposition) | +| mayBeLess | boolean | If and only if set, will not throw an EOF error if less then the requested *mayBeLess* could be read. | + +Example: +```js + tokenizer.peekBuffer(buffer, {mayBeLess: true}); +``` + +## IFileInfo + +File information interface which describes the underlying file, each attribute is optional. + +| Attribute | Type | Description | +|-----------|---------|---------------------------------------------------------------------------------------------------| +| size | number | File size in bytes | +| mimeType | number | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. | +| path | number | File path | +| url | boolean | File URL | + +## Token + +The *token* is basically a description what to read form the [*tokenizer-stream*](#tokenizer). +A basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types). + +A token is something which implements the following interface: +```ts +export interface IGetToken { + + /** + * Length in bytes of encoded value + */ + len: number; + + /** + * Decode value from buffer at offset + * @param buf Buffer to read the decoded value from + * @param off Decode offset + */ + get(buf: Buffer, off: number): T; +} +``` +The *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer. +The `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type. + +## Browser compatibility +To exclude fs based dependencies, you can use a submodule-import from 'strtok3/lib/core'. + +| function | 'strtok3' | 'strtok3/lib/core' | +| ----------------------| --------------------|---------------------| +| `parseBuffer` | ✓ | ✓ | +| `parseStream` | ✓ | ✓ | +| `fromFile` | ✓ | | + +### Working with Web-API readable stream +To convert a [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) into a [Node.js readable stream]((https://nodejs.org/api/stream.html#stream_readable_streams)), you can use [readable-web-to-node-stream](https://github.com/Borewit/readable-web-to-node-stream) to convert one in another. + +Example submodule-import: +```js +const strtok3core = require('strtok3/lib/core'); // Submodule-import to prevent Node.js specific dependencies +const {ReadableWebToNodeStream} = require('readable-web-to-node-stream'); + +(async () => { + + const response = await fetch(url); + const readableWebStream = response.body; // Web-API readable stream + const nodeStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream + + const tokenizer = strtok3core.fromStream(nodeStream); // And we now have tokenizer in a web environment +})(); +``` + +## Licence + +(The MIT License) + +Copyright (c) 2020 Borewit + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/strtok3/lib/AbstractTokenizer.d.ts b/node_modules/strtok3/lib/AbstractTokenizer.d.ts new file mode 100644 index 00000000..bf4d42c7 --- /dev/null +++ b/node_modules/strtok3/lib/AbstractTokenizer.d.ts @@ -0,0 +1,69 @@ +import { ITokenizer, IFileInfo, IReadChunkOptions } from './types'; +import { IGetToken, IToken } from '@tokenizer/token'; +interface INormalizedReadChunkOptions extends IReadChunkOptions { + offset: number; + length: number; + position: number; + mayBeLess?: boolean; +} +/** + * Core tokenizer + */ +export declare abstract class AbstractTokenizer implements ITokenizer { + fileInfo: IFileInfo; + protected constructor(fileInfo?: IFileInfo); + /** + * Tokenizer-stream position + */ + position: number; + private numBuffer; + /** + * Read buffer from tokenizer + * @param buffer - Target buffer to fill with data read from the tokenizer-stream + * @param options - Additional read options + * @returns Promise with number of bytes read + */ + abstract readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array- Target buffer to fill with data peek from the tokenizer-stream + * @param options - Peek behaviour options + * @returns Promise with number of bytes read + */ + abstract peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + readToken(token: IGetToken, position?: number): Promise; + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + peekToken(token: IGetToken, position?: number): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + readNumber(token: IToken): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + peekNumber(token: IToken): Promise; + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + ignore(length: number): Promise; + close(): Promise; + protected normalizeOptions(uint8Array: Uint8Array, options?: IReadChunkOptions): INormalizedReadChunkOptions; +} +export {}; diff --git a/node_modules/strtok3/lib/AbstractTokenizer.js b/node_modules/strtok3/lib/AbstractTokenizer.js new file mode 100644 index 00000000..6683b323 --- /dev/null +++ b/node_modules/strtok3/lib/AbstractTokenizer.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AbstractTokenizer = void 0; +const peek_readable_1 = require("peek-readable"); +/** + * Core tokenizer + */ +class AbstractTokenizer { + constructor(fileInfo) { + /** + * Tokenizer-stream position + */ + this.position = 0; + this.numBuffer = new Uint8Array(8); + this.fileInfo = fileInfo ? fileInfo : {}; + } + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + async readToken(token, position = this.position) { + const uint8Array = Buffer.alloc(token.len); + const len = await this.readBuffer(uint8Array, { position }); + if (len < token.len) + throw new peek_readable_1.EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + async peekToken(token, position = this.position) { + const uint8Array = Buffer.alloc(token.len); + const len = await this.peekBuffer(uint8Array, { position }); + if (len < token.len) + throw new peek_readable_1.EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async readNumber(token) { + const len = await this.readBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new peek_readable_1.EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async peekNumber(token) { + const len = await this.peekBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new peek_readable_1.EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + async ignore(length) { + if (this.fileInfo.size !== undefined) { + const bytesLeft = this.fileInfo.size - this.position; + if (length > bytesLeft) { + this.position += bytesLeft; + return bytesLeft; + } + } + this.position += length; + return length; + } + async close() { + // empty + } + normalizeOptions(uint8Array, options) { + if (options && options.position !== undefined && options.position < this.position) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + if (options) { + return { + mayBeLess: options.mayBeLess === true, + offset: options.offset ? options.offset : 0, + length: options.length ? options.length : (uint8Array.length - (options.offset ? options.offset : 0)), + position: options.position ? options.position : this.position + }; + } + return { + mayBeLess: false, + offset: 0, + length: uint8Array.length, + position: this.position + }; + } +} +exports.AbstractTokenizer = AbstractTokenizer; diff --git a/node_modules/strtok3/lib/BufferTokenizer.d.ts b/node_modules/strtok3/lib/BufferTokenizer.d.ts new file mode 100644 index 00000000..534e31bc --- /dev/null +++ b/node_modules/strtok3/lib/BufferTokenizer.d.ts @@ -0,0 +1,26 @@ +import { IFileInfo, IReadChunkOptions } from './types'; +import { AbstractTokenizer } from './AbstractTokenizer'; +export declare class BufferTokenizer extends AbstractTokenizer { + private uint8Array; + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param fileInfo - Pass additional file information to the tokenizer + */ + constructor(uint8Array: Uint8Array, fileInfo?: IFileInfo); + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; +} diff --git a/node_modules/strtok3/lib/BufferTokenizer.js b/node_modules/strtok3/lib/BufferTokenizer.js new file mode 100644 index 00000000..33d8b1fb --- /dev/null +++ b/node_modules/strtok3/lib/BufferTokenizer.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BufferTokenizer = void 0; +const peek_readable_1 = require("peek-readable"); +const AbstractTokenizer_1 = require("./AbstractTokenizer"); +class BufferTokenizer extends AbstractTokenizer_1.AbstractTokenizer { + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param fileInfo - Pass additional file information to the tokenizer + */ + constructor(uint8Array, fileInfo) { + super(fileInfo); + this.uint8Array = uint8Array; + this.fileInfo.size = this.fileInfo.size ? this.fileInfo.size : uint8Array.length; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + async readBuffer(uint8Array, options) { + if (options && options.position) { + if (options.position < this.position) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + this.position = options.position; + } + const bytesRead = await this.peekBuffer(uint8Array, options); + this.position += bytesRead; + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length); + if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) { + throw new peek_readable_1.EndOfStreamError(); + } + else { + uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read), normOptions.offset); + return bytes2read; + } + } + async close() { + // empty + } +} +exports.BufferTokenizer = BufferTokenizer; diff --git a/node_modules/strtok3/lib/FileTokenizer.d.ts b/node_modules/strtok3/lib/FileTokenizer.d.ts new file mode 100644 index 00000000..3d940594 --- /dev/null +++ b/node_modules/strtok3/lib/FileTokenizer.d.ts @@ -0,0 +1,22 @@ +import { AbstractTokenizer } from './AbstractTokenizer'; +import { IFileInfo, IReadChunkOptions } from './types'; +export declare class FileTokenizer extends AbstractTokenizer { + private fd; + constructor(fd: number, fileInfo: IFileInfo); + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; +} +export declare function fromFile(sourceFilePath: string): Promise; diff --git a/node_modules/strtok3/lib/FileTokenizer.js b/node_modules/strtok3/lib/FileTokenizer.js new file mode 100644 index 00000000..b6fd31fa --- /dev/null +++ b/node_modules/strtok3/lib/FileTokenizer.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromFile = exports.FileTokenizer = void 0; +const AbstractTokenizer_1 = require("./AbstractTokenizer"); +const peek_readable_1 = require("peek-readable"); +const fs = require("./FsPromise"); +class FileTokenizer extends AbstractTokenizer_1.AbstractTokenizer { + constructor(fd, fileInfo) { + super(fileInfo); + this.fd = fd; + } + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + this.position = normOptions.position; + const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position); + this.position += res.bytesRead; + if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) { + throw new peek_readable_1.EndOfStreamError(); + } + return res.bytesRead; + } + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position); + if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) { + throw new peek_readable_1.EndOfStreamError(); + } + return res.bytesRead; + } + async close() { + return fs.close(this.fd); + } +} +exports.FileTokenizer = FileTokenizer; +async function fromFile(sourceFilePath) { + const stat = await fs.stat(sourceFilePath); + if (!stat.isFile) { + throw new Error(`File not a file: ${sourceFilePath}`); + } + const fd = await fs.open(sourceFilePath, 'r'); + return new FileTokenizer(fd, { path: sourceFilePath, size: stat.size }); +} +exports.fromFile = fromFile; diff --git a/node_modules/strtok3/lib/FsPromise.d.ts b/node_modules/strtok3/lib/FsPromise.d.ts new file mode 100644 index 00000000..cd2fb0fd --- /dev/null +++ b/node_modules/strtok3/lib/FsPromise.d.ts @@ -0,0 +1,18 @@ +/** + * Module convert fs functions to promise based functions + */ +/// +import * as fs from 'fs'; +export interface IReadResult { + bytesRead: number; + buffer: Uint8Array; +} +export declare const pathExists: typeof fs.existsSync; +export declare const createReadStream: typeof fs.createReadStream; +export declare function stat(path: fs.PathLike): Promise; +export declare function close(fd: number): Promise; +export declare function open(path: fs.PathLike, mode: fs.Mode): Promise; +export declare function read(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): Promise; +export declare function writeFile(path: fs.PathLike, data: Buffer | string): Promise; +export declare function writeFileSync(path: fs.PathLike, data: Buffer | string): void; +export declare function readFile(path: fs.PathLike): Promise; diff --git a/node_modules/strtok3/lib/FsPromise.js b/node_modules/strtok3/lib/FsPromise.js new file mode 100644 index 00000000..690a5e2b --- /dev/null +++ b/node_modules/strtok3/lib/FsPromise.js @@ -0,0 +1,79 @@ +"use strict"; +/** + * Module convert fs functions to promise based functions + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readFile = exports.writeFileSync = exports.writeFile = exports.read = exports.open = exports.close = exports.stat = exports.createReadStream = exports.pathExists = void 0; +const fs = require("fs"); +exports.pathExists = fs.existsSync; +exports.createReadStream = fs.createReadStream; +async function stat(path) { + return new Promise((resolve, reject) => { + fs.stat(path, (err, stats) => { + if (err) + reject(err); + else + resolve(stats); + }); + }); +} +exports.stat = stat; +async function close(fd) { + return new Promise((resolve, reject) => { + fs.close(fd, err => { + if (err) + reject(err); + else + resolve(); + }); + }); +} +exports.close = close; +async function open(path, mode) { + return new Promise((resolve, reject) => { + fs.open(path, mode, (err, fd) => { + if (err) + reject(err); + else + resolve(fd); + }); + }); +} +exports.open = open; +async function read(fd, buffer, offset, length, position) { + return new Promise((resolve, reject) => { + fs.read(fd, buffer, offset, length, position, (err, bytesRead, _buffer) => { + if (err) + reject(err); + else + resolve({ bytesRead, buffer: _buffer }); + }); + }); +} +exports.read = read; +async function writeFile(path, data) { + return new Promise((resolve, reject) => { + fs.writeFile(path, data, err => { + if (err) + reject(err); + else + resolve(); + }); + }); +} +exports.writeFile = writeFile; +function writeFileSync(path, data) { + fs.writeFileSync(path, data); +} +exports.writeFileSync = writeFileSync; +async function readFile(path) { + return new Promise((resolve, reject) => { + fs.readFile(path, (err, buffer) => { + if (err) + reject(err); + else + resolve(buffer); + }); + }); +} +exports.readFile = readFile; diff --git a/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts b/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts new file mode 100644 index 00000000..18252c39 --- /dev/null +++ b/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts @@ -0,0 +1,28 @@ +/// +import { AbstractTokenizer } from './AbstractTokenizer'; +import { Readable } from 'stream'; +import { IFileInfo, IReadChunkOptions } from './types'; +export declare class ReadStreamTokenizer extends AbstractTokenizer { + private streamReader; + constructor(stream: Readable, fileInfo?: IFileInfo); + /** + * Get file information, an HTTP-client may implement this doing a HEAD request + * @return Promise with file information + */ + getFileInfo(): Promise; + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + ignore(length: number): Promise; +} diff --git a/node_modules/strtok3/lib/ReadStreamTokenizer.js b/node_modules/strtok3/lib/ReadStreamTokenizer.js new file mode 100644 index 00000000..0270b4d9 --- /dev/null +++ b/node_modules/strtok3/lib/ReadStreamTokenizer.js @@ -0,0 +1,98 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadStreamTokenizer = void 0; +const AbstractTokenizer_1 = require("./AbstractTokenizer"); +const peek_readable_1 = require("peek-readable"); +const maxBufferSize = 256000; +class ReadStreamTokenizer extends AbstractTokenizer_1.AbstractTokenizer { + constructor(stream, fileInfo) { + super(fileInfo); + this.streamReader = new peek_readable_1.StreamReader(stream); + } + /** + * Get file information, an HTTP-client may implement this doing a HEAD request + * @return Promise with file information + */ + async getFileInfo() { + return this.fileInfo; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + await this.ignore(skipBytes); + return this.readBuffer(uint8Array, options); + } + else if (skipBytes < 0) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + if (normOptions.length === 0) { + return 0; + } + const bytesRead = await this.streamReader.read(uint8Array, normOptions.offset, normOptions.length); + this.position += bytesRead; + if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) { + throw new peek_readable_1.EndOfStreamError(); + } + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + let bytesRead = 0; + if (normOptions.position) { + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + const skipBuffer = new Uint8Array(normOptions.length + skipBytes); + bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess }); + uint8Array.set(skipBuffer.subarray(skipBytes), normOptions.offset); + return bytesRead - skipBytes; + } + else if (skipBytes < 0) { + throw new Error('Cannot peek from a negative offset in a stream'); + } + } + if (normOptions.length > 0) { + try { + bytesRead = await this.streamReader.peek(uint8Array, normOptions.offset, normOptions.length); + } + catch (err) { + if (options && options.mayBeLess && err instanceof peek_readable_1.EndOfStreamError) { + return 0; + } + throw err; + } + if ((!normOptions.mayBeLess) && bytesRead < normOptions.length) { + throw new peek_readable_1.EndOfStreamError(); + } + } + return bytesRead; + } + async ignore(length) { + // debug(`ignore ${this.position}...${this.position + length - 1}`); + const bufSize = Math.min(maxBufferSize, length); + const buf = new Uint8Array(bufSize); + let totBytesRead = 0; + while (totBytesRead < length) { + const remaining = length - totBytesRead; + const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) }); + if (bytesRead < 0) { + return bytesRead; + } + totBytesRead += bytesRead; + } + return totBytesRead; + } +} +exports.ReadStreamTokenizer = ReadStreamTokenizer; diff --git a/node_modules/strtok3/lib/core.d.ts b/node_modules/strtok3/lib/core.d.ts new file mode 100644 index 00000000..04ec5b24 --- /dev/null +++ b/node_modules/strtok3/lib/core.d.ts @@ -0,0 +1,23 @@ +/// +import { ReadStreamTokenizer } from './ReadStreamTokenizer'; +import { Readable } from 'stream'; +import { BufferTokenizer } from './BufferTokenizer'; +import { IFileInfo } from './types'; +export { EndOfStreamError } from 'peek-readable'; +export { ITokenizer, IFileInfo } from './types'; +export { IToken, IGetToken } from '@tokenizer/token'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property/ + * @param stream - Read from Node.js Stream.Readable + * @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream. + * @returns ReadStreamTokenizer + */ +export declare function fromStream(stream: Readable, fileInfo?: IFileInfo): ReadStreamTokenizer; +/** + * Construct ReadStreamTokenizer from given Buffer. + * @param uint8Array - Uint8Array to tokenize + * @param fileInfo - Pass additional file information to the tokenizer + * @returns BufferTokenizer + */ +export declare function fromBuffer(uint8Array: Uint8Array, fileInfo?: IFileInfo): BufferTokenizer; diff --git a/node_modules/strtok3/lib/core.js b/node_modules/strtok3/lib/core.js new file mode 100644 index 00000000..fb92aa72 --- /dev/null +++ b/node_modules/strtok3/lib/core.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromBuffer = exports.fromStream = exports.EndOfStreamError = void 0; +const ReadStreamTokenizer_1 = require("./ReadStreamTokenizer"); +const BufferTokenizer_1 = require("./BufferTokenizer"); +var peek_readable_1 = require("peek-readable"); +Object.defineProperty(exports, "EndOfStreamError", { enumerable: true, get: function () { return peek_readable_1.EndOfStreamError; } }); +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property/ + * @param stream - Read from Node.js Stream.Readable + * @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream. + * @returns ReadStreamTokenizer + */ +function fromStream(stream, fileInfo) { + fileInfo = fileInfo ? fileInfo : {}; + return new ReadStreamTokenizer_1.ReadStreamTokenizer(stream, fileInfo); +} +exports.fromStream = fromStream; +/** + * Construct ReadStreamTokenizer from given Buffer. + * @param uint8Array - Uint8Array to tokenize + * @param fileInfo - Pass additional file information to the tokenizer + * @returns BufferTokenizer + */ +function fromBuffer(uint8Array, fileInfo) { + return new BufferTokenizer_1.BufferTokenizer(uint8Array, fileInfo); +} +exports.fromBuffer = fromBuffer; diff --git a/node_modules/strtok3/lib/index.d.ts b/node_modules/strtok3/lib/index.d.ts new file mode 100644 index 00000000..c4bd267c --- /dev/null +++ b/node_modules/strtok3/lib/index.d.ts @@ -0,0 +1,15 @@ +/// +import { Readable } from 'stream'; +import { ReadStreamTokenizer } from './ReadStreamTokenizer'; +import * as core from './core'; +export { fromFile } from './FileTokenizer'; +export { ITokenizer, EndOfStreamError, fromBuffer, IFileInfo } from './core'; +export { IToken, IGetToken } from '@tokenizer/token'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property. + * @param stream - Node.js Stream.Readable + * @param fileInfo - Pass additional file information to the tokenizer + * @returns Tokenizer + */ +export declare function fromStream(stream: Readable, fileInfo?: core.IFileInfo): Promise; diff --git a/node_modules/strtok3/lib/index.js b/node_modules/strtok3/lib/index.js new file mode 100644 index 00000000..030e750f --- /dev/null +++ b/node_modules/strtok3/lib/index.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromStream = exports.fromBuffer = exports.EndOfStreamError = exports.fromFile = void 0; +const fs = require("./FsPromise"); +const core = require("./core"); +var FileTokenizer_1 = require("./FileTokenizer"); +Object.defineProperty(exports, "fromFile", { enumerable: true, get: function () { return FileTokenizer_1.fromFile; } }); +var core_1 = require("./core"); +Object.defineProperty(exports, "EndOfStreamError", { enumerable: true, get: function () { return core_1.EndOfStreamError; } }); +Object.defineProperty(exports, "fromBuffer", { enumerable: true, get: function () { return core_1.fromBuffer; } }); +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property. + * @param stream - Node.js Stream.Readable + * @param fileInfo - Pass additional file information to the tokenizer + * @returns Tokenizer + */ +async function fromStream(stream, fileInfo) { + fileInfo = fileInfo ? fileInfo : {}; + if (stream.path) { + const stat = await fs.stat(stream.path); + fileInfo.path = stream.path; + fileInfo.size = stat.size; + } + return core.fromStream(stream, fileInfo); +} +exports.fromStream = fromStream; diff --git a/node_modules/strtok3/lib/types.d.ts b/node_modules/strtok3/lib/types.d.ts new file mode 100644 index 00000000..93895dfd --- /dev/null +++ b/node_modules/strtok3/lib/types.d.ts @@ -0,0 +1,103 @@ +/// +import { IGetToken } from '@tokenizer/token'; +export interface IFileInfo { + /** + * File size in bytes + */ + size?: number; + /** + * MIME-type of file + */ + mimeType?: string; + /** + * File path + */ + path?: string; + /** + * File URL + */ + url?: string; +} +export interface IReadChunkOptions { + /** + * The offset in the buffer to start writing at; default is 0 + */ + offset?: number; + /** + * Number of bytes to read. + */ + length?: number; + /** + * Position where to begin reading from the file. + * Default it is `tokenizer.position`. + * Position may not be less then `tokenizer.position`. + */ + position?: number; + /** + * If set, will not throw an EOF error if not all of the requested data could be read + */ + mayBeLess?: boolean; +} +/** + * The tokenizer allows us to read or peek from the tokenizer-stream. + * The tokenizer-stream is an abstraction of a stream, file or Buffer. + */ +export interface ITokenizer { + /** + * Provide access to information of the underlying information stream or file. + */ + fileInfo: IFileInfo; + /** + * Offset in bytes (= number of bytes read) since beginning of file or stream + */ + position: number; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer - Target buffer to fill with data peek from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + peekBuffer(buffer: Buffer, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer - Target buffer to fill with data peeked from the tokenizer-stream + * @param options - Additional read options + * @returns Promise with number of bytes read + */ + readBuffer(buffer: Buffer, options?: IReadChunkOptions): Promise; + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @param maybeless - If set, will not throw an EOF error if the less then the requested length could be read. + */ + peekToken(token: IGetToken, position?: number | null, maybeless?: boolean): Promise; + /** + * Read a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + */ + readToken(token: IGetToken, position?: number): Promise; + /** + * Peek a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + peekNumber(token: IGetToken): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + readNumber(token: IGetToken): Promise; + /** + * Ignore given number of bytes + * @param length - Number of bytes ignored + */ + ignore(length: number): Promise; + /** + * Clean up resources. + * It does not close the stream for StreamReader, but is does close the file-descriptor. + */ + close(): Promise; +} diff --git a/node_modules/strtok3/lib/types.js b/node_modules/strtok3/lib/types.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/strtok3/lib/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/strtok3/package.json b/node_modules/strtok3/package.json new file mode 100644 index 00000000..1f864d38 --- /dev/null +++ b/node_modules/strtok3/package.json @@ -0,0 +1,103 @@ +{ + "name": "strtok3", + "version": "6.3.0", + "description": "A promise based streaming tokenizer", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "scripts": { + "clean": "del-cli lib/**/*.js lib/**/*.js.map lib/**/*.d.ts test/**/*.js test/**/*.js.map", + "compile-src": "tsc -p lib", + "compile-test": "tsc -p test", + "compile": "npm run compile-src && npm run compile-test", + "build": "npm run clean && npm run compile", + "eslint": "eslint lib test --ext .ts --ignore-pattern *.d.ts", + "lint-md": "remark -u preset-lint-recommended .", + "lint": "npm run lint-md && npm run eslint", + "fix": "eslint lib test --ext .ts --ignore-pattern *.d.ts --fix", + "test": "mocha --require ts-node/register --require source-map-support/register --full-trace test/test.ts", + "test-coverage": "nyc npm run test", + "send-coveralls": "nyc report --reporter=text-lcov | coveralls", + "send-codacy": "nyc report --reporter=text-lcov | codacy-coverage", + "start": "npm run compile && npm run lint && npm run cover-test" + }, + "engines": { + "node": ">=10" + }, + "repository": { + "type": "git", + "url": "https://github.com/Borewit/strtok3.git" + }, + "license": "MIT", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "files": [ + "lib/**/*.js", + "lib/**/*.d.ts" + ], + "bugs": { + "url": "https://github.com/Borewit/strtok3/issues" + }, + "devDependencies": { + "@types/chai": "^4.3.0", + "@types/debug": "^4.1.7", + "@types/mocha": "^9.1.0", + "@types/node": "^17.0.14", + "@typescript-eslint/eslint-plugin": "^5.10.2", + "@typescript-eslint/parser": "^5.10.2", + "chai": "^4.3.6", + "coveralls": "^3.1.1", + "del-cli": "^4.0.1", + "eslint": "^8.8.0", + "eslint-config-prettier": "^8.3.0", + "eslint-import-resolver-typescript": "^2.5.0", + "eslint-plugin-import": "^2.25.4", + "eslint-plugin-jsdoc": "^37.7.1", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-unicorn": "^40.1.0", + "mocha": "^9.2.0", + "nyc": "^15.1.0", + "remark-cli": "^10.0.1", + "remark-preset-lint-recommended": "^6.1.2", + "source-map-support": "^0.5.21", + "token-types": "^4.1.1", + "ts-node": "^10.4.0", + "typescript": "^4.5.5" + }, + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^4.1.0" + }, + "keywords": [ + "tokenizer", + "reader", + "token", + "async", + "promise", + "parser", + "decoder", + "binary", + "endian", + "uint", + "stream", + "streaming" + ], + "nyc": { + "check-coverage": false, + "extension": [ + ".ts" + ], + "sourceMap": true, + "instrument": true, + "reporter": [ + "lcov", + "text" + ], + "report-dir": "coverage" + } +} diff --git a/node_modules/timm/.eslintrc.yaml b/node_modules/timm/.eslintrc.yaml new file mode 100644 index 00000000..b37c92f0 --- /dev/null +++ b/node_modules/timm/.eslintrc.yaml @@ -0,0 +1,33 @@ +root: true +parser: '@typescript-eslint/parser' +plugins: + - '@typescript-eslint' +extends: + - eslint:recommended + # - plugin:react/recommended + - plugin:@typescript-eslint/recommended + - prettier + - prettier/@typescript-eslint +env: + node: true + browser: true + es6: true + jest: true +rules: + '@typescript-eslint/explicit-function-return-type': off + '@typescript-eslint/explicit-member-accessibility': off + '@typescript-eslint/indent': off + '@typescript-eslint/member-delimiter-style': off + '@typescript-eslint/no-explicit-any': off + '@typescript-eslint/no-empty-function': off + '@typescript-eslint/no-non-null-assertion': off + '@typescript-eslint/no-var-requires': off + '@typescript-eslint/explicit-module-boundary-types': off + '@typescript-eslint/ban-ts-comment': off + '@typescript-eslint/ban-types': + - 2 + - types: + Function: false + '@typescript-eslint/no-unused-vars': + - 2 + - argsIgnorePattern: '^_' diff --git a/node_modules/timm/.flowconfig b/node_modules/timm/.flowconfig new file mode 100644 index 00000000..e69de29b diff --git a/node_modules/timm/.github/workflows/run-tests.yml b/node_modules/timm/.github/workflows/run-tests.yml new file mode 100644 index 00000000..3d06fff5 --- /dev/null +++ b/node_modules/timm/.github/workflows/run-tests.yml @@ -0,0 +1,27 @@ +name: Tests + +on: + push: + branches: + - master + - development + +jobs: + test: + name: Run tests + runs-on: ubuntu-latest + steps: + - name: Check out monorepo + uses: actions/checkout@v1 + - name: Install Node 12 + uses: actions/setup-node@v1 + with: + node-version: '12.x' + - name: Install project dependencies + run: | + npm install -g yarn + yarn install + - name: Compile subpackages + run: yarn compile + - name: Execute tests + run: yarn test diff --git a/node_modules/timm/.prettierignore b/node_modules/timm/.prettierignore new file mode 100644 index 00000000..f2fa7196 --- /dev/null +++ b/node_modules/timm/.prettierignore @@ -0,0 +1,3 @@ +node_modules +/package.json +*.md diff --git a/node_modules/timm/.prettierrc b/node_modules/timm/.prettierrc new file mode 100644 index 00000000..5234635e --- /dev/null +++ b/node_modules/timm/.prettierrc @@ -0,0 +1,2 @@ +singleQuote: true +trailingComma: es5 \ No newline at end of file diff --git a/node_modules/timm/CHANGELOG.md b/node_modules/timm/CHANGELOG.md new file mode 100644 index 00000000..acf20f6a --- /dev/null +++ b/node_modules/timm/CHANGELOG.md @@ -0,0 +1,134 @@ +## 1.7.1 (2020-9-16) + +* Improve TypeScript signatures (fix overload order + add missing catch-alls). + +## 1.7.0 (2020-8-27) + +* Rewritten in TypeScript. + +## 1.6.2 (2019-8-11) + +* Update package metadata. +* Update deps to fix security audit. + +## 1.6.1 (2018-8-8) + +* Update deps to fix security audit. + +## 1.6.0 (2018-8-8) + +* Replace functions when merging (`merge()` and `mergeDeep()`) [#25, @hipstersmoothie] + +## 1.5.0 (2018-7-23) + +* Add TypeScript definitions [#23, @grrowl] + +## 1.4.2 (2018-3-29) + +* Support Symbol properties in objects. + +## 1.4.1 (2018-1-2) + +* Add `mergeDeep()` benchmarks [#16, @dentrado] +* doSetIn: ensure nested value is object [#17, @petermikitsh] + +## 1.4.0 (2017-10-25) + +* Add **mergeDeep()** [#14, @dentrado] +* Update benchmarks to reflect current versions of *ImmutableJS* and *seamless-immutable* + +## 1.3.1 (2017-10-14) + +* Add **update()** to Flow API [#13, @dentrado] + +## 1.3.0 (October 3, 2017) + +* Add **update()** [#12, @dentrado] + +## 1.2.5 (April 2, 2017) + +* Improve `replaceAt` performance [#9, @gamtiq] + +## 1.2.4 (March 4, 2017) + +* Bugfix: Fix `setIn` object creation for arrays in some edge cases [#8, @adierkens] + +## 1.2.3 (December 8, 2016) + +* Bugfix: Allow `set`/`setIn` to automatically create arrays, handling correctly negative and decimal numbers [#4, @YellowKirby] + +## 1.2.2 (December 7, 2016) + +* Bugfix: Allow `set`/`setIn` to automatically create arrays [#3, @YellowKirby] + +## 1.2.1 (November 15, 2016) + +* Update external Flow type definitions to support Flex 0.35. + +## 1.2.0 (October 24, 2016) + +* Add **removeFirst(), removeLast()** + +## 1.1.3 (October 19, 2016) + +* Make user-facing Flow type definitions inherit from internal ones (to avoid divergence). + +## 1.1.2 (October 19, 2016) + +* Change how Flow type definitions are exposed so they can be used with zero config. + +## 1.1.1 (October 18, 2016) + +* Fix Flow type definitions for object-related function outputs, making them more flexible. + +## 1.1.0 (October 10, 2016) + +* Expose **Flow** type definitions. + +## 1.0.0 (June 13, 2016) + +* **Use semantic versioning** +* [minor] Bump development dependencies. + +## 0.6.1 (Apr. 22, 2016) + +* Add `omit()` + +## 0.6.0 (Mar. 24, 2016) + +* Renamed build directory to `lib`. + +## 0.5.3 (Mar. 23, 2016) + +* Removed Babel config (.babelrc) from the published package (npm). This simplifies consumption of the ES6 (or ES6 with Flow) versions. + +## 0.5.1, 0.5.2 (Mar. 23, 2016) + +* Distribute 4 versions of Timm: + - ES5 (default): `timm.js` (just `require('timm')`) + - ES5 minimised: `timm.min.js` + - ES6: `timm_es6.js` + - ES6 with Flow type annotations: `timm_es6_flow.js` + +## 0.5.0 (Mar. 23, 2016) + +* Important internal changes (migrated to AVA, ES6, Flow), but usage remains unchanged + +## 0.4.3 (Mar. 08, 2016) + +* Bugfix: internal `_merge()` incorrectly merged `{a: 3} + {a: undefined} => {a: undefined}` + +## 0.4.2 (Feb. 28, 2016) + +* Update documentation for the new functions added in 0.4.1. + +## 0.4.1 (Feb. 28, 2016) + +* Add `getIn()`, `updateIn()`, `mergeIn()` +* `setIn()` now creates nested objects for unknown paths +* Bugfix: internal `_clone()` converted arrays to objects + +## 0.4.0 (Feb. 25, 2016) + +* Accept arrays in array operations `addLast()` and `addFirst()`. +* Add new array operation `insert()`. diff --git a/node_modules/timm/LICENSE b/node_modules/timm/LICENSE new file mode 100644 index 00000000..7afa65c8 --- /dev/null +++ b/node_modules/timm/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016-present Guillermo Grau Panea + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/timm/README.md b/node_modules/timm/README.md new file mode 100644 index 00000000..48f457a0 --- /dev/null +++ b/node_modules/timm/README.md @@ -0,0 +1,448 @@ +# timm [![Build Status](https://github.com/guigrpa/timm/workflows/Tests/badge.svg)](https://github.com/guigrpa/timm/actions) [![npm version](https://img.shields.io/npm/v/timm.svg)](https://www.npmjs.com/package/timm) + +Immutability helpers with fast reads and acceptable writes ([blog post](http://guigrpa.github.io/2016/06/16/painless-immutability/)) + + +## Installation + +``` +$ npm install --save timm +``` + + +## Motivation + +I know, I know... the world doesn't need yet another immutability library, especially with the likes of [ImmutableJS](http://facebook.github.io/immutable-js/) and [seamless-immutable](https://github.com/rtfeldman/seamless-immutable) around. + +And yet... I felt the urge, at least just to cover my limited needs. ImmutableJS is a solid, comprehensive and highly-performant solution, but this power comes at a price: mixing up ImmutableJS's Maps and Lists with your plain objects can cause some friction, and reading those objects (in my case, more often than writing them) isn't that convenient. + +On the other side, *seamless-immutable* solves the "friction" problem by using plain objects and arrays, but seems to have some performance issues (at least in my benchmarks, see below). + +*timm*'s approach: use plain objects and arrays and provide simple mutation functions to handle most common operations (suggestions are welcome!). As a bonus, *timm* creates new objects *lazily*, when it confirms that the operation will mutate the input object; in other words, **operations that don't modify an object always return the object itself**. This alleviates pressure on the garbage collector and lets you easily check whether an object changed after an operation: `merge(obj, { a: 3 }) === obj`. + +**Important notice:** *timm* does *not* freeze the objects it provides. In other words, it doesn't protect you against inadvertently modifying them in your code. I considered deeply freezing all objects with `Object.freeze()`, but it is really slow. Then I considered doing this only in development (like [*seamless-immutable*](https://github.com/rtfeldman/seamless-immutable#performance)), but then modifying frozen objects will silently fail in development (unless you `use strict` in your code), and –worse still– succeed in production. Not good. In conclusion, **be careful** (or send me a suggestion to work around this!). + +...Oh, I almost forgot! It's **tiny: just ~200 LOC and ~1.5 kB minified & compressed!** + +## Benchmarks + +I prepared an initial benchmarking tool comparing read/write speeds in four cases: + +* In-place editing (mutable) +* [ImmutableJS](http://facebook.github.io/immutable-js/) +* [timm](https://github.com/guigrpa/timm) +* [seamless-immutable](https://github.com/rtfeldman/seamless-immutable) +* [immutability-helper](https://github.com/kolodny/immutability-helper) + +All five solutions are first verified for consistency (the mutable solution obviously does not pass all tests) and then benchmarked. Benchmarks cover reading and writing object attributes at different nesting levels (root level, 2 levels and 5 levels deep), merging two small objects, and replacing an object in a 1000-long array. + +Feel free to run them yourself (download the repo and then `npm install && npm run benchmarks`). These are my results on OS X for 200k iterations (Node v8.6.0): + +![Benchmarks](https://github.com/guigrpa/timm/blob/master/docs/bechmarks-osx-20180822-node9.11.png?raw=true) + +Some conclusions from these benchmarks: + +* Reads are on par with native objects/arrays, *seamless-immutable* and *immutability-helper*, and faster than *ImmutableJS* (the deeper, the faster, even though *ImmutableJS* has improved read performance substantially in recent versions). In fact, you cannot go faster than native objects for reading! + +* Writes are much slower than in-place edits, as expected, but are much faster than *seamless-immutable* (even in production mode) and *immutability-helper*, both for objects and arrays. Compared to *ImmutableJS*, object writes and merges are faster (the deeper, the faster), whereas array writes are way slower (not as slow as *seamless-immutable* and *immutability-helper*, though). For *timm* and *seamless-immutable*, write times degrade linearly with array length (and probably object size), but much more slowly for *ImmutableJS* (logarithmically?). This is where *ImmutableJS* really shines. + +* Hence, what I recommend (from top to bottom): + + - If you don't need immutability, well... just **mutate in peace!** I mean, *in place* + - If you need a complete, well-tested, rock-solid library and don't mind using a non-native API for reads: use **ImmutableJS** + - If you value using plain arrays/objects above other considerations, use **timm** + - If your typical use cases involve much more reading than writing, use **timm** as well + - If you do a lot of writes, updating items in long arrays or attributes in fat objects, use **ImmutableJS** + + +## Usage + +```js +import { merge, set as timmSet } from 'timm'; +const obj = merge({ a: 2 }, { b: 3 }); +const obj2 = timmSet({ foo: 1}, 'bar', 2); +``` + +### Arrays + +#### addLast() +Returns a new array with an appended item or items. + +Usage: `addLast(array, val)` + +```js +arr = ['a', 'b'] +arr2 = addLast(arr, 'c') +// ['a', 'b', 'c'] +arr2 === arr +// false +arr3 = addLast(arr, ['c', 'd']) +// ['a', 'b', 'c', 'd'] +``` + +#### addFirst() +Returns a new array with a prepended item or items. + +Usage: `addFirst(array, val)` + +```js +arr = ['a', 'b'] +arr2 = addFirst(arr, 'c') +// ['c', 'a', 'b'] +arr2 === arr +// false +arr3 = addFirst(arr, ['c', 'd']) +// ['c', 'd', 'a', 'b'] +``` + +#### removeLast() +Returns a new array removing the last item. + +Usage: `removeLast(array)` + +```js +arr = ['a', 'b'] +arr2 = removeLast(arr) +// ['a'] +arr2 === arr +// false + +// The same array is returned if there are no changes: +arr3 = [] +removeLast(arr3) === arr3 +// true +``` + +#### removeFirst() +Returns a new array removing the first item. + +Usage: `removeFirst(array)` + +```js +arr = ['a', 'b'] +arr2 = removeFirst(arr) +// ['b'] +arr2 === arr +// false + +// The same array is returned if there are no changes: +arr3 = [] +removeFirst(arr3) === arr3 +// true +``` + +#### insert() +Returns a new array obtained by inserting an item or items +at a specified index. + +Usage: `insert(array, idx, val)` + +```js +arr = ['a', 'b', 'c'] +arr2 = insert(arr, 1, 'd') +// ['a', 'd', 'b', 'c'] +arr2 === arr +// false +insert(arr, 1, ['d', 'e']) +// ['a', 'd', 'e', 'b', 'c'] +``` + +#### removeAt() +Returns a new array obtained by removing an item at +a specified index. + +Usage: `removeAt(array, idx)` + +```js +arr = ['a', 'b', 'c'] +arr2 = removeAt(arr, 1) +// ['a', 'c'] +arr2 === arr +// false + +// The same array is returned if there are no changes: +removeAt(arr, 4) === arr +// true +``` + +#### replaceAt() +Returns a new array obtained by replacing an item at +a specified index. If the provided item is the same as +(*referentially equal to*) the previous item at that position, +the original array is returned. + +Usage: `replaceAt(array, idx, newItem)` + +```js +arr = ['a', 'b', 'c'] +arr2 = replaceAt(arr, 1, 'd') +// ['a', 'd', 'c'] +arr2 === arr +// false + +// The same object is returned if there are no changes: +replaceAt(arr, 1, 'b') === arr +// true +``` + +### Collections (objects and arrays) + +#### getIn() +Returns a value from an object at a given path. Works with +nested arrays and objects. If the path does not exist, it returns +`undefined`. + +Usage: `getIn(obj, path)` + +```js +obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: ['a', 'b', 'c'] } +getIn(obj, ['d', 'd1']) +// 3 +getIn(obj, ['e', 1]) +// 'b' +``` + +#### set() +Returns a new object with a modified attribute. +If the provided value is the same as (*referentially equal to*) +the previous value, the original object is returned. + +Usage: `set(obj, key, val)` + +```js +obj = { a: 1, b: 2, c: 3 } +obj2 = set(obj, 'b', 5) +// { a: 1, b: 5, c: 3 } +obj2 === obj +// false + +// The same object is returned if there are no changes: +set(obj, 'b', 2) === obj +// true +``` + +#### setIn() +Returns a new object with a modified **nested** attribute. + +Notes: + +* If the provided value is the same as (*referentially equal to*) +the previous value, the original object is returned. +* If the path does not exist, it will be created before setting +the new value. + +Usage: `setIn(obj, path, val)` + +```js +obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +obj2 = setIn(obj, ['d', 'd1'], 4) +// { a: 1, b: 2, d: { d1: 4, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +obj2 === obj +// false +obj2.d === obj.d +// false +obj2.e === obj.e +// true + +// The same object is returned if there are no changes: +obj3 = setIn(obj, ['d', 'd1'], 3) +// { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +obj3 === obj +// true +obj3.d === obj.d +// true +obj3.e === obj.e +// true + +// ... unknown paths create intermediate keys. Numeric segments are treated as array indices: +setIn({ a: 3 }, ['unknown', 0, 'path'], 4) +// { a: 3, unknown: [{ path: 4 }] } +``` + +#### update() +Returns a new object with a modified attribute, +calculated via a user-provided callback based on the current value. +If the calculated value is the same as (*referentially equal to*) +the previous value, the original object is returned. + +Usage: `update(obj, key, fnUpdate)` + +```js +obj = { a: 1, b: 2, c: 3 } +obj2 = update(obj, 'b', (val) => val + 1) +// { a: 1, b: 3, c: 3 } +obj2 === obj +// false + +// The same object is returned if there are no changes: +update(obj, 'b', (val) => val) === obj +// true +``` + +#### updateIn() +Returns a new object with a modified **nested** attribute, +calculated via a user-provided callback based on the current value. +If the calculated value is the same as (*referentially equal to*) +the previous value, the original object is returned. + +Usage: `updateIn(obj: T, path: Array, +fnUpdate: (prevValue: any) => any): T` + +```js +obj = { a: 1, d: { d1: 3, d2: 4 } } +obj2 = updateIn(obj, ['d', 'd1'], (val) => val + 1) +// { a: 1, d: { d1: 4, d2: 4 } } +obj2 === obj +// false + +// The same object is returned if there are no changes: +obj3 = updateIn(obj, ['d', 'd1'], (val) => val) +// { a: 1, d: { d1: 3, d2: 4 } } +obj3 === obj +// true +``` + +#### merge() +Returns a new object built as follows: the overlapping keys from the +second one overwrite the corresponding entries from the first one. +Similar to `Object.assign()`, but immutable. + +Usage: + +* `merge(obj1, obj2)` +* `merge(obj1, ...objects)` + +The unmodified `obj1` is returned if `obj2` does not *provide something +new to* `obj1`, i.e. if either of the following +conditions are true: + +* `obj2` is `null` or `undefined` +* `obj2` is an object, but it is empty +* All attributes of `obj2` are `undefined` +* All attributes of `obj2` are referentially equal to the + corresponding attributes of `obj1` + +Note that `undefined` attributes in `obj2` do not modify the +corresponding attributes in `obj1`. + +```js +obj1 = { a: 1, b: 2, c: 3 } +obj2 = { c: 4, d: 5 } +obj3 = merge(obj1, obj2) +// { a: 1, b: 2, c: 4, d: 5 } +obj3 === obj1 +// false + +// The same object is returned if there are no changes: +merge(obj1, { c: 3 }) === obj1 +// true +``` + +#### mergeDeep() +Returns a new object built as follows: the overlapping keys from the +second one overwrite the corresponding entries from the first one. +If both the first and second entries are objects they are merged recursively. +Similar to `Object.assign()`, but immutable, and deeply merging. + +Usage: + +* `mergeDeep(obj1, obj2)` +* `mergeDeep(obj1, ...objects)` + +The unmodified `obj1` is returned if `obj2` does not *provide something +new to* `obj1`, i.e. if either of the following +conditions are true: + +* `obj2` is `null` or `undefined` +* `obj2` is an object, but it is empty +* All attributes of `obj2` are `undefined` +* All attributes of `obj2` are referentially equal to the + corresponding attributes of `obj1` + +Note that `undefined` attributes in `obj2` do not modify the +corresponding attributes in `obj1`. + +```js +obj1 = { a: 1, b: 2, c: { a: 1 } } +obj2 = { b: 3, c: { b: 2 } } +obj3 = mergeDeep(obj1, obj2) +// { a: 1, b: 3, c: { a: 1, b: 2 } } +obj3 === obj1 +// false + +// The same object is returned if there are no changes: +mergeDeep(obj1, { c: { a: 1 } }) === obj1 +// true +``` + +#### mergeIn() +Similar to `merge()`, but merging the value at a given nested path. + +Usage examples: + +* `mergeIn(obj1, path, obj2)` +* `mergeIn(obj1, path, ...objects)` + +```js +obj1 = { a: 1, d: { b: { d1: 3, d2: 4 } } } +obj2 = { d3: 5 } +obj3 = mergeIn(obj1, ['d', 'b'], obj2) +// { a: 1, d: { b: { d1: 3, d2: 4, d3: 5 } } } +obj3 === obj1 +// false + +// The same object is returned if there are no changes: +mergeIn(obj1, ['d', 'b'], { d2: 4 }) === obj1 +// true +``` + +#### omit() +Returns an object excluding one or several attributes. + +Usage: `omit(obj, attrs)` + +```js +obj = { a: 1, b: 2, c: 3, d: 4 } +omit(obj, 'a') +// { b: 2, c: 3, d: 4 } +omit(obj, ['b', 'c']) +// { a: 1, d: 4 } + +// The same object is returned if there are no changes: +omit(obj, 'z') === obj1 +// true +``` + +#### addDefaults() +Returns a new object built as follows: `undefined` keys in the first one +are filled in with the corresponding values from the second one +(even if they are `null`). + +Usage: + +* `addDefaults(obj, defaults)` +* `addDefaults(obj, ...defaultObjects)` + +```js +obj1 = { a: 1, b: 2, c: 3 } +obj2 = { c: 4, d: 5, e: null } +obj3 = addDefaults(obj1, obj2) +// { a: 1, b: 2, c: 3, d: 5, e: null } +obj3 === obj1 +// false + +// The same object is returned if there are no changes: +addDefaults(obj1, { c: 4 }) === obj1 +// true +``` + + +## MIT license + +Copyright (c) [Guillermo Grau Panea](https://github.com/guigrpa) 2016-present + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/timm/_config.yml b/node_modules/timm/_config.yml new file mode 100644 index 00000000..c4192631 --- /dev/null +++ b/node_modules/timm/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-cayman \ No newline at end of file diff --git a/node_modules/timm/babel.config.js b/node_modules/timm/babel.config.js new file mode 100644 index 00000000..7bf53eca --- /dev/null +++ b/node_modules/timm/babel.config.js @@ -0,0 +1,7 @@ +module.exports = { + presets: [ + ['@babel/env', { targets: { node: 'current' } }], + '@babel/typescript', + ], + plugins: [], +}; diff --git a/node_modules/timm/lib/timm.d.ts b/node_modules/timm/lib/timm.d.ts new file mode 100644 index 00000000..ddd43df1 --- /dev/null +++ b/node_modules/timm/lib/timm.d.ts @@ -0,0 +1,61 @@ +declare type Key = string | number; +export declare function clone(obj0: T): T; +export declare function addLast(array: T[], val: T[] | T): T[]; +export declare function addFirst(array: T[], val: T[] | T): T[]; +export declare function removeLast(array: T[]): T[]; +export declare function removeFirst(array: T[]): T[]; +export declare function insert(array: T[], idx: number, val: T[] | T): T[]; +export declare function removeAt(array: T[], idx: number): T[]; +export declare function replaceAt(array: T[], idx: number, newItem: T): T[]; +export declare function getIn(obj: undefined, path: Key[]): undefined; +export declare function getIn(obj: null, path: Key[]): null; +export declare function getIn(obj: object, path: Key[]): unknown; +export declare function set(obj: undefined | null, key: K, val: V): { + [P in K]: V; +}; +export declare function set(obj: undefined | null, key: number, val: V): [V]; +export declare function set(obj: T, key: K, val: V): Omit & { + [P in K]: V; +}; +export declare function set(obj: V[], key: number, val: V): V[]; +export declare function setIn(obj: object | null | undefined, path: Key[], val: any): unknown; +export declare function update(obj: object | null | undefined, key: Key, fnUpdate: (prevValue: any) => any): unknown; +export declare function updateIn(obj: object | null | undefined, path: Key[], fnUpdate: (prevValue: any) => any): unknown; +export declare function merge(a: T): T; +export declare function merge(a: T, b: undefined | null): T; +export declare function merge(a: T, b: U): Omit & U; +export declare function merge(a: T, b: undefined | null, c: V): Omit & V; +export declare function merge(a: T, b: U, c: undefined | null): Omit & U; +export declare function merge(a: T, b: undefined | null, c: undefined | null): T; +export declare function merge(a: T, b: U, c: V): Omit & U, keyof V> & V; +export declare function merge(a: object, ...rest: Array): object; +export declare function mergeDeep(a: object, b?: object | null, c?: object | null, d?: object | null, e?: object | null, f?: object | null, ...rest: Array): object; +export declare function mergeIn(a: any, path: Key[], b?: object | null, c?: object | null, d?: object | null, e?: object | null, f?: object | null, ...rest: Array): unknown; +export declare function omit(obj: T, attrs: K | K[]): Omit; +export declare function addDefaults(a: T, b: U): Omit & T; +export declare function addDefaults(a: object, b: object, ...rest: Array): object; +declare const timm: { + clone: typeof clone; + addLast: typeof addLast; + addFirst: typeof addFirst; + removeLast: typeof removeLast; + removeFirst: typeof removeFirst; + insert: typeof insert; + removeAt: typeof removeAt; + replaceAt: typeof replaceAt; + getIn: typeof getIn; + set: typeof set; + setIn: typeof setIn; + update: typeof update; + updateIn: typeof updateIn; + merge: typeof merge; + mergeDeep: typeof mergeDeep; + mergeIn: typeof mergeIn; + omit: typeof omit; + addDefaults: typeof addDefaults; +}; +export default timm; diff --git a/node_modules/timm/lib/timm.js b/node_modules/timm/lib/timm.js new file mode 100644 index 00000000..4b04c8e3 --- /dev/null +++ b/node_modules/timm/lib/timm.js @@ -0,0 +1,668 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.clone = clone; +exports.addLast = addLast; +exports.addFirst = addFirst; +exports.removeLast = removeLast; +exports.removeFirst = removeFirst; +exports.insert = insert; +exports.removeAt = removeAt; +exports.replaceAt = replaceAt; +exports.getIn = getIn; +exports.set = set; +exports.setIn = setIn; +exports.update = update; +exports.updateIn = updateIn; +exports.merge = merge; +exports.mergeDeep = mergeDeep; +exports.mergeIn = mergeIn; +exports.omit = omit; +exports.addDefaults = addDefaults; +exports.default = void 0; + +/* eslint-disable @typescript-eslint/ban-types */ + +/*! + * Timm + * + * Immutability helpers with fast reads and acceptable writes. + * + * @copyright Guillermo Grau Panea 2016 + * @license MIT + */ +const INVALID_ARGS = 'INVALID_ARGS'; +const IS_DEV = process.env.NODE_ENV !== 'production'; + +// =============================================== +// ### Helpers +// =============================================== +function throwStr(msg) { + throw new Error(msg); +} + +function getKeysAndSymbols(obj) { + const keys = Object.keys(obj); + + if (Object.getOwnPropertySymbols) { + // @ts-ignore + return keys.concat(Object.getOwnPropertySymbols(obj)); + } + + return keys; +} + +const hasOwnProperty = {}.hasOwnProperty; + +function clone(obj0) { + // As array + if (Array.isArray(obj0)) return obj0.slice(); // As object + + const obj = obj0; + const keys = getKeysAndSymbols(obj); + const out = {}; + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + out[key] = obj[key]; + } // @ts-ignore (see type tests) + + + return out; +} // Custom guard + + +function isObject(o) { + return o != null && typeof o === 'object'; +} // _deepFreeze = (obj) -> +// Object.freeze obj +// for key in Object.getOwnPropertyNames obj +// val = obj[key] +// if isObject(val) and not Object.isFrozen val +// _deepFreeze val +// obj +// =============================================== +// -- ### Arrays +// =============================================== +// -- #### addLast() +// -- Returns a new array with an appended item or items. +// -- +// -- Usage: `addLast(array, val)` +// -- +// -- ```js +// -- arr = ['a', 'b'] +// -- arr2 = addLast(arr, 'c') +// -- // ['a', 'b', 'c'] +// -- arr2 === arr +// -- // false +// -- arr3 = addLast(arr, ['c', 'd']) +// -- // ['a', 'b', 'c', 'd'] +// -- ``` +// `array.concat(val)` also handles the scalar case, +// but is apparently very slow + + +function addLast(array, val) { + if (Array.isArray(val)) return array.concat(val); + return array.concat([val]); +} // -- #### addFirst() +// -- Returns a new array with a prepended item or items. +// -- +// -- Usage: `addFirst(array, val)` +// -- +// -- ```js +// -- arr = ['a', 'b'] +// -- arr2 = addFirst(arr, 'c') +// -- // ['c', 'a', 'b'] +// -- arr2 === arr +// -- // false +// -- arr3 = addFirst(arr, ['c', 'd']) +// -- // ['c', 'd', 'a', 'b'] +// -- ``` + + +function addFirst(array, val) { + if (Array.isArray(val)) return val.concat(array); + return [val].concat(array); +} // -- #### removeLast() +// -- Returns a new array removing the last item. +// -- +// -- Usage: `removeLast(array)` +// -- +// -- ```js +// -- arr = ['a', 'b'] +// -- arr2 = removeLast(arr) +// -- // ['a'] +// -- arr2 === arr +// -- // false +// -- +// -- // The same array is returned if there are no changes: +// -- arr3 = [] +// -- removeLast(arr3) === arr3 +// -- // true +// -- ``` + + +function removeLast(array) { + if (!array.length) return array; + return array.slice(0, array.length - 1); +} // -- #### removeFirst() +// -- Returns a new array removing the first item. +// -- +// -- Usage: `removeFirst(array)` +// -- +// -- ```js +// -- arr = ['a', 'b'] +// -- arr2 = removeFirst(arr) +// -- // ['b'] +// -- arr2 === arr +// -- // false +// -- +// -- // The same array is returned if there are no changes: +// -- arr3 = [] +// -- removeFirst(arr3) === arr3 +// -- // true +// -- ``` + + +function removeFirst(array) { + if (!array.length) return array; + return array.slice(1); +} // -- #### insert() +// -- Returns a new array obtained by inserting an item or items +// -- at a specified index. +// -- +// -- Usage: `insert(array, idx, val)` +// -- +// -- ```js +// -- arr = ['a', 'b', 'c'] +// -- arr2 = insert(arr, 1, 'd') +// -- // ['a', 'd', 'b', 'c'] +// -- arr2 === arr +// -- // false +// -- insert(arr, 1, ['d', 'e']) +// -- // ['a', 'd', 'e', 'b', 'c'] +// -- ``` + + +function insert(array, idx, val) { + return array.slice(0, idx).concat(Array.isArray(val) ? val : [val]).concat(array.slice(idx)); +} // -- #### removeAt() +// -- Returns a new array obtained by removing an item at +// -- a specified index. +// -- +// -- Usage: `removeAt(array, idx)` +// -- +// -- ```js +// -- arr = ['a', 'b', 'c'] +// -- arr2 = removeAt(arr, 1) +// -- // ['a', 'c'] +// -- arr2 === arr +// -- // false +// -- +// -- // The same array is returned if there are no changes: +// -- removeAt(arr, 4) === arr +// -- // true +// -- ``` + + +function removeAt(array, idx) { + if (idx >= array.length || idx < 0) return array; + return array.slice(0, idx).concat(array.slice(idx + 1)); +} // -- #### replaceAt() +// -- Returns a new array obtained by replacing an item at +// -- a specified index. If the provided item is the same as +// -- (*referentially equal to*) the previous item at that position, +// -- the original array is returned. +// -- +// -- Usage: `replaceAt(array, idx, newItem)` +// -- +// -- ```js +// -- arr = ['a', 'b', 'c'] +// -- arr2 = replaceAt(arr, 1, 'd') +// -- // ['a', 'd', 'c'] +// -- arr2 === arr +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- replaceAt(arr, 1, 'b') === arr +// -- // true +// -- ``` + + +function replaceAt(array, idx, newItem) { + if (array[idx] === newItem) return array; + const len = array.length; + const result = Array(len); + + for (let i = 0; i < len; i++) { + result[i] = array[i]; + } + + result[idx] = newItem; + return result; +} // =============================================== +// -- ### Collections (objects and arrays) +// =============================================== +// -- #### getIn() +// -- Returns a value from an object at a given path. Works with +// -- nested arrays and objects. If the path does not exist, it returns +// -- `undefined`. +// -- +// -- Usage: `getIn(obj, path)` +// -- +// -- ```js +// -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: ['a', 'b', 'c'] } +// -- getIn(obj, ['d', 'd1']) +// -- // 3 +// -- getIn(obj, ['e', 1]) +// -- // 'b' +// -- ``` + + +function getIn(obj, path) { + if (!Array.isArray(path)) { + throwStr(IS_DEV ? 'A path array should be provided when calling getIn()' : INVALID_ARGS); + } + + if (obj == null) return undefined; + let ptr = obj; + + for (let i = 0; i < path.length; i++) { + const key = path[i]; + ptr = ptr != null ? ptr[key] : undefined; + if (ptr === undefined) return ptr; + } + + return ptr; +} // -- #### set() +// -- Returns a new object with a modified attribute. +// -- If the provided value is the same as (*referentially equal to*) +// -- the previous value, the original object is returned. +// -- +// -- Usage: `set(obj, key, val)` +// -- +// -- ```js +// -- obj = { a: 1, b: 2, c: 3 } +// -- obj2 = set(obj, 'b', 5) +// -- // { a: 1, b: 5, c: 3 } +// -- obj2 === obj +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- set(obj, 'b', 2) === obj +// -- // true +// -- ``` +// When called with an undefined/null `obj`, `set()` returns either +// a single-element array, or a single-key object + + +// Implementation +function set(obj0, key, val) { + let obj = obj0; + if (obj == null) obj = typeof key === 'number' ? [] : {}; + if (obj[key] === val) return obj; + const obj2 = clone(obj); + obj2[key] = val; + return obj2; +} // -- #### setIn() +// -- Returns a new object with a modified **nested** attribute. +// -- +// -- Notes: +// -- +// -- * If the provided value is the same as (*referentially equal to*) +// -- the previous value, the original object is returned. +// -- * If the path does not exist, it will be created before setting +// -- the new value. +// -- +// -- Usage: `setIn(obj, path, val)` +// -- +// -- ```js +// -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +// -- obj2 = setIn(obj, ['d', 'd1'], 4) +// -- // { a: 1, b: 2, d: { d1: 4, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +// -- obj2 === obj +// -- // false +// -- obj2.d === obj.d +// -- // false +// -- obj2.e === obj.e +// -- // true +// -- +// -- // The same object is returned if there are no changes: +// -- obj3 = setIn(obj, ['d', 'd1'], 3) +// -- // { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +// -- obj3 === obj +// -- // true +// -- obj3.d === obj.d +// -- // true +// -- obj3.e === obj.e +// -- // true +// -- +// -- // ... unknown paths create intermediate keys. Numeric segments are treated as array indices: +// -- setIn({ a: 3 }, ['unknown', 0, 'path'], 4) +// -- // { a: 3, unknown: [{ path: 4 }] } +// -- ``` + + +function setIn(obj, path, val) { + if (!path.length) return val; + return doSetIn(obj, path, val, 0); +} + +function doSetIn(obj, path, val, idx) { + let newValue; + const key = path[idx]; + + if (idx === path.length - 1) { + newValue = val; + } else { + const nestedObj = isObject(obj) && isObject(obj[key]) ? obj[key] : typeof path[idx + 1] === 'number' ? [] : {}; + newValue = doSetIn(nestedObj, path, val, idx + 1); + } + + return set(obj, key, newValue); +} // -- #### update() +// -- Returns a new object with a modified attribute, +// -- calculated via a user-provided callback based on the current value. +// -- If the calculated value is the same as (*referentially equal to*) +// -- the previous value, the original object is returned. +// -- +// -- Usage: `update(obj, key, fnUpdate)` +// -- +// -- ```js +// -- obj = { a: 1, b: 2, c: 3 } +// -- obj2 = update(obj, 'b', (val) => val + 1) +// -- // { a: 1, b: 3, c: 3 } +// -- obj2 === obj +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- update(obj, 'b', (val) => val) === obj +// -- // true +// -- ``` + + +function update(obj, key, fnUpdate) { + const prevVal = obj == null ? undefined : obj[key]; + const nextVal = fnUpdate(prevVal); + return set(obj, key, nextVal); +} // -- #### updateIn() +// -- Returns a new object with a modified **nested** attribute, +// -- calculated via a user-provided callback based on the current value. +// -- If the calculated value is the same as (*referentially equal to*) +// -- the previous value, the original object is returned. +// -- +// -- Usage: `updateIn(obj: T, path: Array, +// -- fnUpdate: (prevValue: any) => any): T` +// -- +// -- ```js +// -- obj = { a: 1, d: { d1: 3, d2: 4 } } +// -- obj2 = updateIn(obj, ['d', 'd1'], (val) => val + 1) +// -- // { a: 1, d: { d1: 4, d2: 4 } } +// -- obj2 === obj +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- obj3 = updateIn(obj, ['d', 'd1'], (val) => val) +// -- // { a: 1, d: { d1: 3, d2: 4 } } +// -- obj3 === obj +// -- // true +// -- ``` + + +function updateIn(obj, path, fnUpdate) { + const prevVal = getIn(obj, path); + const nextVal = fnUpdate(prevVal); + return setIn(obj, path, nextVal); +} // -- #### merge() +// -- Returns a new object built as follows: the overlapping keys from the +// -- second one overwrite the corresponding entries from the first one. +// -- Similar to `Object.assign()`, but immutable. +// -- +// -- Usage: +// -- +// -- * `merge(obj1, obj2)` +// -- * `merge(obj1, ...objects)` +// -- +// -- The unmodified `obj1` is returned if `obj2` does not *provide something +// -- new to* `obj1`, i.e. if either of the following +// -- conditions are true: +// -- +// -- * `obj2` is `null` or `undefined` +// -- * `obj2` is an object, but it is empty +// -- * All attributes of `obj2` are `undefined` +// -- * All attributes of `obj2` are referentially equal to the +// -- corresponding attributes of `obj1` +// -- +// -- Note that `undefined` attributes in `obj2` do not modify the +// -- corresponding attributes in `obj1`. +// -- +// -- ```js +// -- obj1 = { a: 1, b: 2, c: 3 } +// -- obj2 = { c: 4, d: 5 } +// -- obj3 = merge(obj1, obj2) +// -- // { a: 1, b: 2, c: 4, d: 5 } +// -- obj3 === obj1 +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- merge(obj1, { c: 3 }) === obj1 +// -- // true +// -- ``` +// Signatures: +// - 1 arg + + +// Implementation +function merge(a, b, c, d, e, f, ...rest) { + return rest.length ? doMerge.call(null, false, false, a, b, c, d, e, f, ...rest) : doMerge(false, false, a, b, c, d, e, f); +} // -- #### mergeDeep() +// -- Returns a new object built as follows: the overlapping keys from the +// -- second one overwrite the corresponding entries from the first one. +// -- If both the first and second entries are objects they are merged recursively. +// -- Similar to `Object.assign()`, but immutable, and deeply merging. +// -- +// -- Usage: +// -- +// -- * `mergeDeep(obj1, obj2)` +// -- * `mergeDeep(obj1, ...objects)` +// -- +// -- The unmodified `obj1` is returned if `obj2` does not *provide something +// -- new to* `obj1`, i.e. if either of the following +// -- conditions are true: +// -- +// -- * `obj2` is `null` or `undefined` +// -- * `obj2` is an object, but it is empty +// -- * All attributes of `obj2` are `undefined` +// -- * All attributes of `obj2` are referentially equal to the +// -- corresponding attributes of `obj1` +// -- +// -- Note that `undefined` attributes in `obj2` do not modify the +// -- corresponding attributes in `obj1`. +// -- +// -- ```js +// -- obj1 = { a: 1, b: 2, c: { a: 1 } } +// -- obj2 = { b: 3, c: { b: 2 } } +// -- obj3 = mergeDeep(obj1, obj2) +// -- // { a: 1, b: 3, c: { a: 1, b: 2 } } +// -- obj3 === obj1 +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- mergeDeep(obj1, { c: { a: 1 } }) === obj1 +// -- // true +// -- ``` + + +function mergeDeep(a, b, c, d, e, f, ...rest) { + return rest.length ? doMerge.call(null, false, true, a, b, c, d, e, f, ...rest) : doMerge(false, true, a, b, c, d, e, f); +} // -- #### mergeIn() +// -- Similar to `merge()`, but merging the value at a given nested path. +// -- +// -- Usage examples: +// -- +// -- * `mergeIn(obj1, path, obj2)` +// -- * `mergeIn(obj1, path, ...objects)` +// -- +// -- ```js +// -- obj1 = { a: 1, d: { b: { d1: 3, d2: 4 } } } +// -- obj2 = { d3: 5 } +// -- obj3 = mergeIn(obj1, ['d', 'b'], obj2) +// -- // { a: 1, d: { b: { d1: 3, d2: 4, d3: 5 } } } +// -- obj3 === obj1 +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- mergeIn(obj1, ['d', 'b'], { d2: 4 }) === obj1 +// -- // true +// -- ``` + + +function mergeIn(a, path, b, c, d, e, f, ...rest) { + let prevVal = getIn(a, path); + if (prevVal == null) prevVal = {}; + let nextVal; + + if (rest.length) { + nextVal = doMerge.call(null, false, false, prevVal, b, c, d, e, f, ...rest); + } else { + nextVal = doMerge(false, false, prevVal, b, c, d, e, f); + } + + return setIn(a, path, nextVal); +} // -- #### omit() +// -- Returns an object excluding one or several attributes. +// -- +// -- Usage: `omit(obj, attrs)` +// +// -- ```js +// -- obj = { a: 1, b: 2, c: 3, d: 4 } +// -- omit(obj, 'a') +// -- // { b: 2, c: 3, d: 4 } +// -- omit(obj, ['b', 'c']) +// -- // { a: 1, d: 4 } +// -- +// -- // The same object is returned if there are no changes: +// -- omit(obj, 'z') === obj1 +// -- // true +// -- ``` + + +function omit(obj, attrs) { + const omitList = Array.isArray(attrs) ? attrs : [attrs]; + let fDoSomething = false; + + for (let i = 0; i < omitList.length; i++) { + if (hasOwnProperty.call(obj, omitList[i])) { + fDoSomething = true; + break; + } + } + + if (!fDoSomething) return obj; + const out = {}; + const keys = getKeysAndSymbols(obj); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (omitList.indexOf(key) >= 0) continue; + out[key] = obj[key]; + } + + return out; +} // -- #### addDefaults() +// -- Returns a new object built as follows: `undefined` keys in the first one +// -- are filled in with the corresponding values from the second one +// -- (even if they are `null`). +// -- +// -- Usage: +// -- +// -- * `addDefaults(obj, defaults)` +// -- * `addDefaults(obj, ...defaultObjects)` +// -- +// -- ```js +// -- obj1 = { a: 1, b: 2, c: 3 } +// -- obj2 = { c: 4, d: 5, e: null } +// -- obj3 = addDefaults(obj1, obj2) +// -- // { a: 1, b: 2, c: 3, d: 5, e: null } +// -- obj3 === obj1 +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- addDefaults(obj1, { c: 4 }) === obj1 +// -- // true +// -- ``` +// Signatures: +// - 2 args + + +// Implementation and catch-all +function addDefaults(a, b, c, d, e, f, ...rest) { + return rest.length ? doMerge.call(null, true, false, a, b, c, d, e, f, ...rest) : doMerge(true, false, a, b, c, d, e, f); +} + +function doMerge(fAddDefaults, fDeep, first, ...rest) { + let out = first; + + if (!(out != null)) { + throwStr(IS_DEV ? 'At least one object should be provided to merge()' : INVALID_ARGS); + } + + let fChanged = false; + + for (let idx = 0; idx < rest.length; idx++) { + const obj = rest[idx]; + if (obj == null) continue; + const keys = getKeysAndSymbols(obj); + if (!keys.length) continue; + + for (let j = 0; j <= keys.length; j++) { + const key = keys[j]; + if (fAddDefaults && out[key] !== undefined) continue; + let nextVal = obj[key]; + + if (fDeep && isObject(out[key]) && isObject(nextVal)) { + nextVal = doMerge(fAddDefaults, fDeep, out[key], nextVal); + } + + if (nextVal === undefined || nextVal === out[key]) continue; + + if (!fChanged) { + fChanged = true; + out = clone(out); + } + + out[key] = nextVal; + } + } + + return out; +} // =============================================== +// ### Public API +// =============================================== + + +const timm = { + clone, + addLast, + addFirst, + removeLast, + removeFirst, + insert, + removeAt, + replaceAt, + getIn, + set, + setIn, + update, + updateIn, + merge, + mergeDeep, + mergeIn, + omit, + addDefaults +}; +var _default = timm; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/timm/package.json b/node_modules/timm/package.json new file mode 100644 index 00000000..dfd2c39a --- /dev/null +++ b/node_modules/timm/package.json @@ -0,0 +1,55 @@ +{ + "name": "timm", + "version": "1.7.1", + "description": "Immutability helpers with fast reads and acceptable writes", + "author": "Guillermo Grau Panea", + "license": "MIT", + "keywords": [ + "immutability" + ], + "homepage": "http://guigrpa.github.io/timm/", + "repository": { + "type": "git", + "url": "https://github.com/guigrpa/timm.git" + }, + "main": "lib/timm.js", + "types": "lib/timm.d.ts", + "scripts": { + "typecheck": "tsc --pretty", + "lint": "eslint src/timm.ts", + "jest": "yarn test --watch", + "test": "jest --coverage src", + "compile": "yarn compile:clean && yarn compile:main && yarn compile:types", + "compile:clean": "rm -rf ./lib", + "compile:main": "babel src -d lib --extensions '.ts'", + "compile:types": "yarn typecheck", + "docs": "extract-docs --template docs/README_TEMPLATE.md --output README.md", + "build": "yarn lint && yarn compile && yarn test && yarn docs && yarn xxl", + "xxl": "xxl", + "benchmarks": "node tools/benchmarks", + "prettier": "prettier --single-quote --trailing-comma es5 --write \"src/**/*.[jt]s\"" + }, + "dependencies": {}, + "devDependencies": { + "@babel/cli": "^7.11.6", + "@babel/core": "^7.11.6", + "@babel/preset-env": "^7.11.5", + "@babel/preset-typescript": "^7.10.1", + "@typescript-eslint/eslint-plugin": "^4.1.1", + "@typescript-eslint/parser": "^4.1.1", + "eslint": "^7.9.0", + "eslint-config-prettier": "^6.11.0", + "oao": "^2.0.0", + "typescript": "^4.0.2", + "babel-jest": "^26.3.0", + "chalk": "1.1.3", + "extract-docs": "^1.6.1", + "immutability-helper": "^2.8.1", + "immutable": "3.8.2", + "jest": "^26.4.2", + "lodash": "^4.17.20", + "prettier": "^2.1.2", + "seamless-immutable": "^7.1.4", + "xxl": "^1.3.0" + } +} diff --git a/node_modules/timm/src/timm.ts b/node_modules/timm/src/timm.ts new file mode 100644 index 00000000..c603f779 --- /dev/null +++ b/node_modules/timm/src/timm.ts @@ -0,0 +1,763 @@ +/* eslint-disable @typescript-eslint/ban-types */ + +/*! + * Timm + * + * Immutability helpers with fast reads and acceptable writes. + * + * @copyright Guillermo Grau Panea 2016 + * @license MIT + */ + +const INVALID_ARGS = 'INVALID_ARGS'; +const IS_DEV = (process as any).env.NODE_ENV !== 'production'; + +type Key = string | number; + +// =============================================== +// ### Helpers +// =============================================== +function throwStr(msg: string): never { + throw new Error(msg); +} + +function getKeysAndSymbols(obj: object): string[] { + const keys = Object.keys(obj); + if (Object.getOwnPropertySymbols) { + // @ts-ignore + return keys.concat(Object.getOwnPropertySymbols(obj)); + } + return keys; +} + +const hasOwnProperty = {}.hasOwnProperty; + +export function clone(obj0: T): T { + // As array + if (Array.isArray(obj0)) return obj0.slice() as T; + + // As object + const obj: any = obj0; + const keys = getKeysAndSymbols(obj); + const out: any = {}; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + out[key] = obj[key]; + } + // @ts-ignore (see type tests) + return out; +} + +// Custom guard +function isObject(o: unknown): any { + return o != null && typeof o === 'object'; +} + +// _deepFreeze = (obj) -> +// Object.freeze obj +// for key in Object.getOwnPropertyNames obj +// val = obj[key] +// if isObject(val) and not Object.isFrozen val +// _deepFreeze val +// obj + +// =============================================== +// -- ### Arrays +// =============================================== + +// -- #### addLast() +// -- Returns a new array with an appended item or items. +// -- +// -- Usage: `addLast(array, val)` +// -- +// -- ```js +// -- arr = ['a', 'b'] +// -- arr2 = addLast(arr, 'c') +// -- // ['a', 'b', 'c'] +// -- arr2 === arr +// -- // false +// -- arr3 = addLast(arr, ['c', 'd']) +// -- // ['a', 'b', 'c', 'd'] +// -- ``` +// `array.concat(val)` also handles the scalar case, +// but is apparently very slow +export function addLast(array: T[], val: T[] | T): T[] { + if (Array.isArray(val)) return array.concat(val); + return array.concat([val]); +} + +// -- #### addFirst() +// -- Returns a new array with a prepended item or items. +// -- +// -- Usage: `addFirst(array, val)` +// -- +// -- ```js +// -- arr = ['a', 'b'] +// -- arr2 = addFirst(arr, 'c') +// -- // ['c', 'a', 'b'] +// -- arr2 === arr +// -- // false +// -- arr3 = addFirst(arr, ['c', 'd']) +// -- // ['c', 'd', 'a', 'b'] +// -- ``` +export function addFirst(array: T[], val: T[] | T): T[] { + if (Array.isArray(val)) return val.concat(array); + return [val].concat(array); +} + +// -- #### removeLast() +// -- Returns a new array removing the last item. +// -- +// -- Usage: `removeLast(array)` +// -- +// -- ```js +// -- arr = ['a', 'b'] +// -- arr2 = removeLast(arr) +// -- // ['a'] +// -- arr2 === arr +// -- // false +// -- +// -- // The same array is returned if there are no changes: +// -- arr3 = [] +// -- removeLast(arr3) === arr3 +// -- // true +// -- ``` +export function removeLast(array: T[]): T[] { + if (!array.length) return array; + return array.slice(0, array.length - 1); +} + +// -- #### removeFirst() +// -- Returns a new array removing the first item. +// -- +// -- Usage: `removeFirst(array)` +// -- +// -- ```js +// -- arr = ['a', 'b'] +// -- arr2 = removeFirst(arr) +// -- // ['b'] +// -- arr2 === arr +// -- // false +// -- +// -- // The same array is returned if there are no changes: +// -- arr3 = [] +// -- removeFirst(arr3) === arr3 +// -- // true +// -- ``` +export function removeFirst(array: T[]): T[] { + if (!array.length) return array; + return array.slice(1); +} + +// -- #### insert() +// -- Returns a new array obtained by inserting an item or items +// -- at a specified index. +// -- +// -- Usage: `insert(array, idx, val)` +// -- +// -- ```js +// -- arr = ['a', 'b', 'c'] +// -- arr2 = insert(arr, 1, 'd') +// -- // ['a', 'd', 'b', 'c'] +// -- arr2 === arr +// -- // false +// -- insert(arr, 1, ['d', 'e']) +// -- // ['a', 'd', 'e', 'b', 'c'] +// -- ``` +export function insert(array: T[], idx: number, val: T[] | T): T[] { + return array + .slice(0, idx) + .concat(Array.isArray(val) ? val : [val]) + .concat(array.slice(idx)); +} + +// -- #### removeAt() +// -- Returns a new array obtained by removing an item at +// -- a specified index. +// -- +// -- Usage: `removeAt(array, idx)` +// -- +// -- ```js +// -- arr = ['a', 'b', 'c'] +// -- arr2 = removeAt(arr, 1) +// -- // ['a', 'c'] +// -- arr2 === arr +// -- // false +// -- +// -- // The same array is returned if there are no changes: +// -- removeAt(arr, 4) === arr +// -- // true +// -- ``` +export function removeAt(array: T[], idx: number): T[] { + if (idx >= array.length || idx < 0) return array; + return array.slice(0, idx).concat(array.slice(idx + 1)); +} + +// -- #### replaceAt() +// -- Returns a new array obtained by replacing an item at +// -- a specified index. If the provided item is the same as +// -- (*referentially equal to*) the previous item at that position, +// -- the original array is returned. +// -- +// -- Usage: `replaceAt(array, idx, newItem)` +// -- +// -- ```js +// -- arr = ['a', 'b', 'c'] +// -- arr2 = replaceAt(arr, 1, 'd') +// -- // ['a', 'd', 'c'] +// -- arr2 === arr +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- replaceAt(arr, 1, 'b') === arr +// -- // true +// -- ``` +export function replaceAt(array: T[], idx: number, newItem: T): T[] { + if (array[idx] === newItem) return array; + const len = array.length; + const result = Array(len); + for (let i = 0; i < len; i++) { + result[i] = array[i]; + } + result[idx] = newItem; + return result; +} + +// =============================================== +// -- ### Collections (objects and arrays) +// =============================================== +// -- #### getIn() +// -- Returns a value from an object at a given path. Works with +// -- nested arrays and objects. If the path does not exist, it returns +// -- `undefined`. +// -- +// -- Usage: `getIn(obj, path)` +// -- +// -- ```js +// -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: ['a', 'b', 'c'] } +// -- getIn(obj, ['d', 'd1']) +// -- // 3 +// -- getIn(obj, ['e', 1]) +// -- // 'b' +// -- ``` +export function getIn(obj: undefined, path: Key[]): undefined; +export function getIn(obj: null, path: Key[]): null; +export function getIn(obj: object, path: Key[]): unknown; +export function getIn(obj: any, path: Key[]): unknown { + if (!Array.isArray(path)) { + throwStr( + IS_DEV + ? 'A path array should be provided when calling getIn()' + : INVALID_ARGS + ); + } + if (obj == null) return undefined; + let ptr: any = obj; + for (let i = 0; i < path.length; i++) { + const key = path[i]; + ptr = ptr != null ? ptr[key] : undefined; + if (ptr === undefined) return ptr; + } + return ptr; +} + +// -- #### set() +// -- Returns a new object with a modified attribute. +// -- If the provided value is the same as (*referentially equal to*) +// -- the previous value, the original object is returned. +// -- +// -- Usage: `set(obj, key, val)` +// -- +// -- ```js +// -- obj = { a: 1, b: 2, c: 3 } +// -- obj2 = set(obj, 'b', 5) +// -- // { a: 1, b: 5, c: 3 } +// -- obj2 === obj +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- set(obj, 'b', 2) === obj +// -- // true +// -- ``` +// When called with an undefined/null `obj`, `set()` returns either +// a single-element array, or a single-key object +export function set( + obj: undefined | null, + key: K, + val: V +): { [P in K]: V }; +export function set(obj: undefined | null, key: number, val: V): [V]; +// Normal operation with an object/array +export function set( + obj: T, + key: K, + val: V +): Omit & { [P in K]: V }; +export function set(obj: V[], key: number, val: V): V[]; +// Implementation +export function set(obj0: any, key: Key, val: any): any { + let obj = obj0; + if (obj == null) obj = typeof key === 'number' ? [] : {}; + if (obj[key] === val) return obj; + const obj2 = clone(obj); + obj2[key] = val; + return obj2; +} + +// -- #### setIn() +// -- Returns a new object with a modified **nested** attribute. +// -- +// -- Notes: +// -- +// -- * If the provided value is the same as (*referentially equal to*) +// -- the previous value, the original object is returned. +// -- * If the path does not exist, it will be created before setting +// -- the new value. +// -- +// -- Usage: `setIn(obj, path, val)` +// -- +// -- ```js +// -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +// -- obj2 = setIn(obj, ['d', 'd1'], 4) +// -- // { a: 1, b: 2, d: { d1: 4, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +// -- obj2 === obj +// -- // false +// -- obj2.d === obj.d +// -- // false +// -- obj2.e === obj.e +// -- // true +// -- +// -- // The same object is returned if there are no changes: +// -- obj3 = setIn(obj, ['d', 'd1'], 3) +// -- // { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } } +// -- obj3 === obj +// -- // true +// -- obj3.d === obj.d +// -- // true +// -- obj3.e === obj.e +// -- // true +// -- +// -- // ... unknown paths create intermediate keys. Numeric segments are treated as array indices: +// -- setIn({ a: 3 }, ['unknown', 0, 'path'], 4) +// -- // { a: 3, unknown: [{ path: 4 }] } +// -- ``` +export function setIn( + obj: object | null | undefined, + path: Key[], + val: any +): unknown { + if (!path.length) return val; + return doSetIn(obj, path, val, 0); +} + +function doSetIn( + obj: object | null | undefined, + path: Key[], + val: any, + idx: number +): unknown { + let newValue; + const key: any = path[idx]; + if (idx === path.length - 1) { + newValue = val; + } else { + const nestedObj = + isObject(obj) && isObject((obj as any)[key]) + ? (obj as any)[key] + : typeof path[idx + 1] === 'number' + ? [] + : {}; + newValue = doSetIn(nestedObj, path, val, idx + 1); + } + return set(obj as any, key, newValue); +} + +// -- #### update() +// -- Returns a new object with a modified attribute, +// -- calculated via a user-provided callback based on the current value. +// -- If the calculated value is the same as (*referentially equal to*) +// -- the previous value, the original object is returned. +// -- +// -- Usage: `update(obj, key, fnUpdate)` +// -- +// -- ```js +// -- obj = { a: 1, b: 2, c: 3 } +// -- obj2 = update(obj, 'b', (val) => val + 1) +// -- // { a: 1, b: 3, c: 3 } +// -- obj2 === obj +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- update(obj, 'b', (val) => val) === obj +// -- // true +// -- ``` +export function update( + obj: object | null | undefined, + key: Key, + fnUpdate: (prevValue: any) => any +): unknown { + const prevVal = obj == null ? undefined : (obj as any)[key]; + const nextVal = fnUpdate(prevVal); + return set(obj as any, key as any, nextVal); +} + +// -- #### updateIn() +// -- Returns a new object with a modified **nested** attribute, +// -- calculated via a user-provided callback based on the current value. +// -- If the calculated value is the same as (*referentially equal to*) +// -- the previous value, the original object is returned. +// -- +// -- Usage: `updateIn(obj: T, path: Array, +// -- fnUpdate: (prevValue: any) => any): T` +// -- +// -- ```js +// -- obj = { a: 1, d: { d1: 3, d2: 4 } } +// -- obj2 = updateIn(obj, ['d', 'd1'], (val) => val + 1) +// -- // { a: 1, d: { d1: 4, d2: 4 } } +// -- obj2 === obj +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- obj3 = updateIn(obj, ['d', 'd1'], (val) => val) +// -- // { a: 1, d: { d1: 3, d2: 4 } } +// -- obj3 === obj +// -- // true +// -- ``` +export function updateIn( + obj: object | null | undefined, + path: Key[], + fnUpdate: (prevValue: any) => any +): unknown { + const prevVal = getIn(obj as any, path); + const nextVal = fnUpdate(prevVal); + return setIn(obj, path, nextVal); +} + +// -- #### merge() +// -- Returns a new object built as follows: the overlapping keys from the +// -- second one overwrite the corresponding entries from the first one. +// -- Similar to `Object.assign()`, but immutable. +// -- +// -- Usage: +// -- +// -- * `merge(obj1, obj2)` +// -- * `merge(obj1, ...objects)` +// -- +// -- The unmodified `obj1` is returned if `obj2` does not *provide something +// -- new to* `obj1`, i.e. if either of the following +// -- conditions are true: +// -- +// -- * `obj2` is `null` or `undefined` +// -- * `obj2` is an object, but it is empty +// -- * All attributes of `obj2` are `undefined` +// -- * All attributes of `obj2` are referentially equal to the +// -- corresponding attributes of `obj1` +// -- +// -- Note that `undefined` attributes in `obj2` do not modify the +// -- corresponding attributes in `obj1`. +// -- +// -- ```js +// -- obj1 = { a: 1, b: 2, c: 3 } +// -- obj2 = { c: 4, d: 5 } +// -- obj3 = merge(obj1, obj2) +// -- // { a: 1, b: 2, c: 4, d: 5 } +// -- obj3 === obj1 +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- merge(obj1, { c: 3 }) === obj1 +// -- // true +// -- ``` + +// Signatures: +// - 1 arg +export function merge(a: T): T; +// - 2 args +export function merge(a: T, b: undefined | null): T; +export function merge( + a: T, + b: U +): Omit & U; +// - 3 args +export function merge( + a: T, + b: undefined | null, + c: V +): Omit & V; +export function merge( + a: T, + b: U, + c: undefined | null +): Omit & U; +export function merge( + a: T, + b: undefined | null, + c: undefined | null +): T; +export function merge( + a: T, + b: U, + c: V +): Omit & U, keyof V> & V; +// - X args +export function merge(a: object, ...rest: Array): object; + +// Implementation +export function merge( + a: object, + b?: object | null, + c?: object | null, + d?: object | null, + e?: object | null, + f?: object | null, + ...rest: Array +): object { + return rest.length + ? doMerge.call(null, false, false, a, b, c, d, e, f, ...rest) + : doMerge(false, false, a, b, c, d, e, f); +} + +// -- #### mergeDeep() +// -- Returns a new object built as follows: the overlapping keys from the +// -- second one overwrite the corresponding entries from the first one. +// -- If both the first and second entries are objects they are merged recursively. +// -- Similar to `Object.assign()`, but immutable, and deeply merging. +// -- +// -- Usage: +// -- +// -- * `mergeDeep(obj1, obj2)` +// -- * `mergeDeep(obj1, ...objects)` +// -- +// -- The unmodified `obj1` is returned if `obj2` does not *provide something +// -- new to* `obj1`, i.e. if either of the following +// -- conditions are true: +// -- +// -- * `obj2` is `null` or `undefined` +// -- * `obj2` is an object, but it is empty +// -- * All attributes of `obj2` are `undefined` +// -- * All attributes of `obj2` are referentially equal to the +// -- corresponding attributes of `obj1` +// -- +// -- Note that `undefined` attributes in `obj2` do not modify the +// -- corresponding attributes in `obj1`. +// -- +// -- ```js +// -- obj1 = { a: 1, b: 2, c: { a: 1 } } +// -- obj2 = { b: 3, c: { b: 2 } } +// -- obj3 = mergeDeep(obj1, obj2) +// -- // { a: 1, b: 3, c: { a: 1, b: 2 } } +// -- obj3 === obj1 +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- mergeDeep(obj1, { c: { a: 1 } }) === obj1 +// -- // true +// -- ``` +export function mergeDeep( + a: object, + b?: object | null, + c?: object | null, + d?: object | null, + e?: object | null, + f?: object | null, + ...rest: Array +): object { + return rest.length + ? doMerge.call(null, false, true, a, b, c, d, e, f, ...rest) + : doMerge(false, true, a, b, c, d, e, f); +} + +// -- #### mergeIn() +// -- Similar to `merge()`, but merging the value at a given nested path. +// -- +// -- Usage examples: +// -- +// -- * `mergeIn(obj1, path, obj2)` +// -- * `mergeIn(obj1, path, ...objects)` +// -- +// -- ```js +// -- obj1 = { a: 1, d: { b: { d1: 3, d2: 4 } } } +// -- obj2 = { d3: 5 } +// -- obj3 = mergeIn(obj1, ['d', 'b'], obj2) +// -- // { a: 1, d: { b: { d1: 3, d2: 4, d3: 5 } } } +// -- obj3 === obj1 +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- mergeIn(obj1, ['d', 'b'], { d2: 4 }) === obj1 +// -- // true +// -- ``` +export function mergeIn( + a: any, + path: Key[], + b?: object | null, + c?: object | null, + d?: object | null, + e?: object | null, + f?: object | null, + ...rest: Array +): unknown { + let prevVal: any = getIn(a, path); + if (prevVal == null) prevVal = {}; + let nextVal; + if (rest.length) { + nextVal = doMerge.call(null, false, false, prevVal, b, c, d, e, f, ...rest); + } else { + nextVal = doMerge(false, false, prevVal, b, c, d, e, f); + } + return setIn(a, path, nextVal); +} + +// -- #### omit() +// -- Returns an object excluding one or several attributes. +// -- +// -- Usage: `omit(obj, attrs)` +// +// -- ```js +// -- obj = { a: 1, b: 2, c: 3, d: 4 } +// -- omit(obj, 'a') +// -- // { b: 2, c: 3, d: 4 } +// -- omit(obj, ['b', 'c']) +// -- // { a: 1, d: 4 } +// -- +// -- // The same object is returned if there are no changes: +// -- omit(obj, 'z') === obj1 +// -- // true +// -- ``` +export function omit( + obj: T, + attrs: K | K[] +): Omit { + const omitList = Array.isArray(attrs) ? attrs : [attrs]; + let fDoSomething = false; + for (let i = 0; i < omitList.length; i++) { + if (hasOwnProperty.call(obj, omitList[i])) { + fDoSomething = true; + break; + } + } + if (!fDoSomething) return obj; + const out: any = {}; + const keys = getKeysAndSymbols(obj); + for (let i = 0; i < keys.length; i++) { + const key: any = keys[i]; + if (omitList.indexOf(key) >= 0) continue; + out[key] = (obj as any)[key]; + } + return out; +} + +// -- #### addDefaults() +// -- Returns a new object built as follows: `undefined` keys in the first one +// -- are filled in with the corresponding values from the second one +// -- (even if they are `null`). +// -- +// -- Usage: +// -- +// -- * `addDefaults(obj, defaults)` +// -- * `addDefaults(obj, ...defaultObjects)` +// -- +// -- ```js +// -- obj1 = { a: 1, b: 2, c: 3 } +// -- obj2 = { c: 4, d: 5, e: null } +// -- obj3 = addDefaults(obj1, obj2) +// -- // { a: 1, b: 2, c: 3, d: 5, e: null } +// -- obj3 === obj1 +// -- // false +// -- +// -- // The same object is returned if there are no changes: +// -- addDefaults(obj1, { c: 4 }) === obj1 +// -- // true +// -- ``` +// Signatures: +// - 2 args +export function addDefaults( + a: T, + b: U +): Omit & T; +// - X args +export function addDefaults( + a: object, + b: object, + ...rest: Array +): object; + +// Implementation and catch-all +export function addDefaults( + a: object, + b: object, + c?: object | null, + d?: object | null, + e?: object | null, + f?: object | null, + ...rest: Array +): object { + return rest.length + ? doMerge.call(null, true, false, a, b, c, d, e, f, ...rest) + : doMerge(true, false, a, b, c, d, e, f); +} + +function doMerge( + fAddDefaults: boolean, + fDeep: boolean, + first: object, + ...rest: Array +) { + let out: any = first; + if (!(out != null)) { + throwStr( + IS_DEV + ? 'At least one object should be provided to merge()' + : INVALID_ARGS + ); + } + let fChanged = false; + for (let idx = 0; idx < rest.length; idx++) { + const obj = rest[idx]; + if (obj == null) continue; + const keys = getKeysAndSymbols(obj); + if (!keys.length) continue; + for (let j = 0; j <= keys.length; j++) { + const key = keys[j]; + if (fAddDefaults && out[key] !== undefined) continue; + let nextVal = (obj as any)[key]; + if (fDeep && isObject(out[key]) && isObject(nextVal)) { + nextVal = doMerge(fAddDefaults, fDeep, out[key], nextVal); + } + if (nextVal === undefined || nextVal === out[key]) continue; + if (!fChanged) { + fChanged = true; + out = clone(out); + } + out[key] = nextVal; + } + } + return out; +} + +// =============================================== +// ### Public API +// =============================================== +const timm = { + clone, + addLast, + addFirst, + removeLast, + removeFirst, + insert, + removeAt, + replaceAt, + + getIn, + set, + setIn, + update, + updateIn, + merge, + mergeDeep, + mergeIn, + omit, + addDefaults, +}; + +export default timm; diff --git a/node_modules/timm/tsconfig.json b/node_modules/timm/tsconfig.json new file mode 100644 index 00000000..673138d6 --- /dev/null +++ b/node_modules/timm/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "lib": ["ES2017", "DOM"], + "strict": true, + "downlevelIteration": true, + "declaration": true, + "emitDeclarationOnly": true, + "outDir": "lib", + "esModuleInterop": true + }, + "exclude": ["src/typeTests.ts"], + "include": ["src/**/*"] +} diff --git a/node_modules/tinycolor2/LICENSE b/node_modules/tinycolor2/LICENSE new file mode 100644 index 00000000..b6424d83 --- /dev/null +++ b/node_modules/tinycolor2/LICENSE @@ -0,0 +1,20 @@ +Copyright (c), Brian Grinstead, http://briangrinstead.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. \ No newline at end of file diff --git a/node_modules/tinycolor2/README.md b/node_modules/tinycolor2/README.md new file mode 100644 index 00000000..71b6d767 --- /dev/null +++ b/node_modules/tinycolor2/README.md @@ -0,0 +1,492 @@ +# TinyColor + +## JavaScript color tooling + +TinyColor is a small, fast library for color manipulation and conversion in JavaScript. It allows many forms of input, while providing color conversions and other color utility functions. It has no dependencies. + +## Including in node + +`tinycolor` can be installed from npm: + + npm install tinycolor2 + +Then it can be used in your script like so: + +```js +var tinycolor = require("tinycolor2"); +var color = tinycolor("red"); +``` + +Or in a module like so: + +```js +import tinycolor from "tinycolor2"; +var color = tinycolor("red"); +``` + +## Including in a browser + +The package can be bundled from npm, but if you prefer to download it locally you have two choices: + +### ESM + +It can be used as a module by downloading [npm/esm/tinycolor.js](https://github.com/bgrins/TinyColor/blob/master/npm/esm/tinycolor.js) or using https://esm.sh/tinycolor2. + +```html + +``` + +### UMD + +You can use it directly in a script tag by downloading the UMD file from [npm/cjs/tinycolor.js](https://github.com/bgrins/TinyColor/blob/master/npm/cjs/tinycolor.js): + +```html + + +``` + +## Usage + +Call `tinycolor(input)` or `new tinycolor(input)`, and you will have an object with the following properties. See Accepted String Input and Accepted Object Input below for more information about what is accepted. + +## Accepted String Input + +The string parsing is very permissive. It is meant to make typing a color as input as easy as possible. All commas, percentages, parenthesis are optional, and most input allow either 0-1, 0%-100%, or 0-n (where n is either 100, 255, or 360 depending on the value). + +HSL and HSV both require either 0%-100% or 0-1 for the `S`/`L`/`V` properties. The `H` (hue) can have values between 0%-100% or 0-360. + +RGB input requires either 0-255 or 0%-100%. + +If you call `tinycolor.fromRatio`, RGB and Hue input can also accept 0-1. + +Here are some examples of string input: + +### Hex, 8-digit (RGBA) Hex +```js +tinycolor("#000"); +tinycolor("000"); +tinycolor("#369C"); +tinycolor("369C"); +tinycolor("#f0f0f6"); +tinycolor("f0f0f6"); +tinycolor("#f0f0f688"); +tinycolor("f0f0f688"); +``` +### RGB, RGBA +```js +tinycolor("rgb (255, 0, 0)"); +tinycolor("rgb 255 0 0"); +tinycolor("rgba (255, 0, 0, .5)"); +tinycolor({ r: 255, g: 0, b: 0 }); +tinycolor.fromRatio({ r: 1, g: 0, b: 0 }); +tinycolor.fromRatio({ r: .5, g: .5, b: .5 }); +``` +### HSL, HSLA +```js +tinycolor("hsl(0, 100%, 50%)"); +tinycolor("hsla(0, 100%, 50%, .5)"); +tinycolor("hsl(0, 100%, 50%)"); +tinycolor("hsl 0 1.0 0.5"); +tinycolor({ h: 0, s: 1, l: .5 }); +tinycolor.fromRatio({ h: 1, s: 0, l: 0 }); +tinycolor.fromRatio({ h: .5, s: .5, l: .5 }); +``` +### HSV, HSVA +```js +tinycolor("hsv(0, 100%, 100%)"); +tinycolor("hsva(0, 100%, 100%, .5)"); +tinycolor("hsv (0 100% 100%)"); +tinycolor("hsv 0 1 1"); +tinycolor({ h: 0, s: 100, v: 100 }); +tinycolor.fromRatio({ h: 1, s: 0, v: 0 }); +tinycolor.fromRatio({ h: .5, s: .5, v: .5 }); +``` +### Named + +Case insenstive names are accepted, using the [list of colors in the CSS spec](https://www.w3.org/TR/css-color-4/#named-colors). + +```js +tinycolor("RED"); +tinycolor("blanchedalmond"); +tinycolor("darkblue"); +``` +### Accepted Object Input + +If you are calling this from code, you may want to use object input. Here are some examples of the different types of accepted object inputs: + + { r: 255, g: 0, b: 0 } + { r: 255, g: 0, b: 0, a: .5 } + { h: 0, s: 100, l: 50 } + { h: 0, s: 100, v: 100 } + +## Methods + +### getFormat + +Returns the format used to create the tinycolor instance +```js +var color = tinycolor("red"); +color.getFormat(); // "name" +color = tinycolor({r:255, g:255, b:255}); +color.getFormat(); // "rgb" +``` + +### getOriginalInput + +Returns the input passed into the constructor used to create the tinycolor instance +```js +var color = tinycolor("red"); +color.getOriginalInput(); // "red" +color = tinycolor({r:255, g:255, b:255}); +color.getOriginalInput(); // "{r: 255, g: 255, b: 255}" +``` + +### isValid + +Return a boolean indicating whether the color was successfully parsed. Note: if the color is not valid then it will act like `black` when being used with other methods. +```js +var color1 = tinycolor("red"); +color1.isValid(); // true +color1.toHexString(); // "#ff0000" + +var color2 = tinycolor("not a color"); +color2.isValid(); // false +color2.toString(); // "#000000" +``` +### getBrightness + +Returns the perceived brightness of a color, from `0-255`, as defined by [Web Content Accessibility Guidelines (Version 1.0)](http://www.w3.org/TR/AERT#color-contrast). +```js +var color1 = tinycolor("#fff"); +color1.getBrightness(); // 255 + +var color2 = tinycolor("#000"); +color2.getBrightness(); // 0 +``` +### isLight + +Return a boolean indicating whether the color's perceived brightness is light. +```js +var color1 = tinycolor("#fff"); +color1.isLight(); // true + +var color2 = tinycolor("#000"); +color2.isLight(); // false +``` +### isDark + +Return a boolean indicating whether the color's perceived brightness is dark. +```js +var color1 = tinycolor("#fff"); +color1.isDark(); // false + +var color2 = tinycolor("#000"); +color2.isDark(); // true +``` +### getLuminance + +Returns the perceived luminance of a color, from `0-1` as defined by [Web Content Accessibility Guidelines (Version 2.0).](http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef) +```js +var color1 = tinycolor("#fff"); +color1.getLuminance(); // 1 + +var color2 = tinycolor("#000"); +color2.getLuminance(); // 0 +``` +### getAlpha + +Returns the alpha value of a color, from `0-1`. +```js +var color1 = tinycolor("rgba(255, 0, 0, .5)"); +color1.getAlpha(); // 0.5 + +var color2 = tinycolor("rgb(255, 0, 0)"); +color2.getAlpha(); // 1 + +var color3 = tinycolor("transparent"); +color3.getAlpha(); // 0 +``` +### setAlpha + +Sets the alpha value on a current color. Accepted range is in between `0-1`. +```js +var color = tinycolor("red"); +color.getAlpha(); // 1 +color.setAlpha(.5); +color.getAlpha(); // .5 +color.toRgbString(); // "rgba(255, 0, 0, .5)" +``` +### String Representations + +The following methods will return a property for the `alpha` value, which can be ignored: `toHsv`, `toHsl`, `toRgb` + +### toHsv +```js +var color = tinycolor("red"); +color.toHsv(); // { h: 0, s: 1, v: 1, a: 1 } +``` +### toHsvString +```js +var color = tinycolor("red"); +color.toHsvString(); // "hsv(0, 100%, 100%)" +color.setAlpha(0.5); +color.toHsvString(); // "hsva(0, 100%, 100%, 0.5)" +``` +### toHsl +```js +var color = tinycolor("red"); +color.toHsl(); // { h: 0, s: 1, l: 0.5, a: 1 } +``` +### toHslString +```js +var color = tinycolor("red"); +color.toHslString(); // "hsl(0, 100%, 50%)" +color.setAlpha(0.5); +color.toHslString(); // "hsla(0, 100%, 50%, 0.5)" +``` +### toHex +```js +var color = tinycolor("red"); +color.toHex(); // "ff0000" +``` +### toHexString +```js +var color = tinycolor("red"); +color.toHexString(); // "#ff0000" +``` +### toHex8 +```js +var color = tinycolor("red"); +color.toHex8(); // "ff0000ff" +``` +### toHex8String +```js +var color = tinycolor("red"); +color.toHex8String(); // "#ff0000ff" +``` +### toRgb +```js +var color = tinycolor("red"); +color.toRgb(); // { r: 255, g: 0, b: 0, a: 1 } +``` +### toRgbString +```js +var color = tinycolor("red"); +color.toRgbString(); // "rgb(255, 0, 0)" +color.setAlpha(0.5); +color.toRgbString(); // "rgba(255, 0, 0, 0.5)" +``` +### toPercentageRgb +```js +var color = tinycolor("red"); +color.toPercentageRgb() // { r: "100%", g: "0%", b: "0%", a: 1 } +``` +### toPercentageRgbString +```js +var color = tinycolor("red"); +color.toPercentageRgbString(); // "rgb(100%, 0%, 0%)" +color.setAlpha(0.5); +color.toPercentageRgbString(); // "rgba(100%, 0%, 0%, 0.5)" +``` +### toName +```js +var color = tinycolor("red"); +color.toName(); // "red" +``` +### toFilter +``` +var color = tinycolor("red"); +color.toFilter(); // "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" +``` +### toString + +Print to a string, depending on the input format. You can also override this by passing one of `"rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv"` into the function. +```js +var color1 = tinycolor("red"); +color1.toString(); // "red" +color1.toString("hsv"); // "hsv(0, 100%, 100%)" + +var color2 = tinycolor("rgb(255, 0, 0)"); +color2.toString(); // "rgb(255, 0, 0)" +color2.setAlpha(.5); +color2.toString(); // "rgba(255, 0, 0, 0.5)" +``` +### Color Modification + +These methods manipulate the current color, and return it for chaining. For instance: +```js +tinycolor("red").lighten().desaturate().toHexString() // "#f53d3d" +``` +### lighten + +`lighten: function(amount = 10) -> TinyColor`. Lighten the color a given amount, from 0 to 100. Providing 100 will always return white. +```js +tinycolor("#f00").lighten().toString(); // "#ff3333" +tinycolor("#f00").lighten(100).toString(); // "#ffffff" +``` +### brighten + +`brighten: function(amount = 10) -> TinyColor`. Brighten the color a given amount, from 0 to 100. +```js +tinycolor("#f00").brighten().toString(); // "#ff1919" +``` +### darken + +`darken: function(amount = 10) -> TinyColor`. Darken the color a given amount, from 0 to 100. Providing 100 will always return black. +```js +tinycolor("#f00").darken().toString(); // "#cc0000" +tinycolor("#f00").darken(100).toString(); // "#000000" +``` +### desaturate + +`desaturate: function(amount = 10) -> TinyColor`. Desaturate the color a given amount, from 0 to 100. Providing 100 will is the same as calling `greyscale`. +```js +tinycolor("#f00").desaturate().toString(); // "#f20d0d" +tinycolor("#f00").desaturate(100).toString(); // "#808080" +``` +### saturate + +`saturate: function(amount = 10) -> TinyColor`. Saturate the color a given amount, from 0 to 100. +```js +tinycolor("hsl(0, 10%, 50%)").saturate().toString(); // "hsl(0, 20%, 50%)" +``` +### greyscale + +`greyscale: function() -> TinyColor`. Completely desaturates a color into greyscale. Same as calling `desaturate(100)`. +```js +tinycolor("#f00").greyscale().toString(); // "#808080" +``` +### spin + +`spin: function(amount = 0) -> TinyColor`. Spin the hue a given amount, from -360 to 360. Calling with 0, 360, or -360 will do nothing (since it sets the hue back to what it was before). +```js +tinycolor("#f00").spin(180).toString(); // "#00ffff" +tinycolor("#f00").spin(-90).toString(); // "#7f00ff" +tinycolor("#f00").spin(90).toString(); // "#80ff00" + +// spin(0) and spin(360) do nothing +tinycolor("#f00").spin(0).toString(); // "#ff0000" +tinycolor("#f00").spin(360).toString(); // "#ff0000" +``` +### Color Combinations + +Combination functions return an array of TinyColor objects unless otherwise noted. + +### analogous + +`analogous: function(, results = 6, slices = 30) -> array`. +```js +var colors = tinycolor("#f00").analogous(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#ff0066", "#ff0033", "#ff0000", "#ff3300", "#ff6600" ] +``` +### monochromatic + +`monochromatic: function(, results = 6) -> array`. +```js +var colors = tinycolor("#f00").monochromatic(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#2a0000", "#550000", "#800000", "#aa0000", "#d40000" ] +``` +### splitcomplement + +`splitcomplement: function() -> array`. +```js +var colors = tinycolor("#f00").splitcomplement(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#ccff00", "#0066ff" ] +``` +### triad + +`triad: function() -> array`. +```js +var colors = tinycolor("#f00").triad(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#00ff00", "#0000ff" ] +``` +### tetrad + +`tetrad: function() -> array`. +```js +var colors = tinycolor("#f00").tetrad(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#80ff00", "#00ffff", "#7f00ff" ] + +``` +### complement + +`complement: function() -> TinyColor`. +```js +tinycolor("#f00").complement().toHexString(); // "#00ffff" +``` +## Color Utilities +```js +tinycolor.equals(color1, color2) +tinycolor.mix(color1, color2, amount = 50) +``` +### random + +Returns a random color. +```js +var color = tinycolor.random(); +color.toRgb(); // "{r: 145, g: 40, b: 198, a: 1}" +``` + +### Readability + +TinyColor assesses readability based on the [Web Content Accessibility Guidelines (Version 2.0)](http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef). + +#### readability + +`readability: function(TinyColor, TinyColor) -> Object`. +Returns the contrast ratio between two colors. +```js +tinycolor.readability("#000", "#000"); // 1 +tinycolor.readability("#000", "#111"); // 1.1121078324840545 +tinycolor.readability("#000", "#fff"); // 21 +``` +Use the values in your own calculations, or use one of the convenience functions below. + +#### isReadable + +`isReadable: function(TinyColor, TinyColor, Object) -> Boolean`. Ensure that foreground and background color combinations meet WCAG guidelines. `Object` is optional, defaulting to `{level: "AA",size: "small"}`. `level` can be `"AA"` or "AAA" and `size` can be `"small"` or `"large"`. + +Here are links to read more about the [AA](http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html) and [AAA](http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast7.html) requirements. +```js +tinycolor.isReadable("#000", "#111", {}); // false +tinycolor.isReadable("#ff0088", "#5c1a72",{level:"AA",size:"small"}); //false +tinycolor.isReadable("#ff0088", "#5c1a72",{level:"AA",size:"large"}), //true +``` +#### mostReadable + +`mostReadable: function(TinyColor, [TinyColor, Tinycolor ...], Object) -> Boolean`. +Given a base color and a list of possible foreground or background colors for that base, returns the most readable color. +If none of the colors in the list is readable, `mostReadable` will return the better of black or white if `includeFallbackColors:true`. +```js +tinycolor.mostReadable("#000", ["#f00", "#0f0", "#00f"]).toHexString(); // "#00ff00" +tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" +tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" +tinycolor.mostReadable("#ff0088", ["#2e0c3a"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString() // "#2e0c3a", +tinycolor.mostReadable("#ff0088", ["#2e0c3a"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString() // "#000000", +``` +See [index.html](https://github.com/bgrins/TinyColor/blob/master/index.html) in the project for a demo. + +## Common operations + +### clone + +`clone: function() -> TinyColor`. +Instantiate a new TinyColor object with the same color. Any changes to the new one won't affect the old one. +```js +var color1 = tinycolor("#F00"); +var color2 = color1.clone(); +color2.setAlpha(.5); + +color1.toString(); // "#ff0000" +color2.toString(); // "rgba(255, 0, 0, 0.5)" +``` diff --git a/node_modules/tinycolor2/cjs/package.json b/node_modules/tinycolor2/cjs/package.json new file mode 100644 index 00000000..5bbefffb --- /dev/null +++ b/node_modules/tinycolor2/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/tinycolor2/cjs/test.js b/node_modules/tinycolor2/cjs/test.js new file mode 100644 index 00000000..40be5fdd --- /dev/null +++ b/node_modules/tinycolor2/cjs/test.js @@ -0,0 +1,2191 @@ +// This file is autogenerated. +// Ideally it wouldn't exist, but it's here to test cjs in node +// Changes should go into ./test.js, and if new assertions are needed +// they'll need to be shimmed here as well +const tinycolor = require("./tinycolor.js"); +const { Deno, testDefinitions } = require("@deno/shim-deno-test"); +async function runDenoTests() { + for (const test of testDefinitions) { + if (test.ignore) { + console.log(`Ignoring ${test.name}`); + continue; + } + console.log(`Running ${test.name}`); + await test.fn(); + console.log(`> Passed ${test.name}`); + } +} +(async () => { + const { assertEquals, assert, assertThrows } = await import( + "../deno_asserts@0.168.0.mjs" + ); + + // TEST_BEGINS_HERE + +Deno.test("TinyColor initialization", function () { + assert( + typeof tinycolor != "undefined", + "tinycolor is initialized on the page" + ); + assert( + typeof tinycolor("red") == "object", + "tinycolor is able to be instantiated" + ); + + var r = tinycolor("red"); + assert( + tinycolor(r) === r, + "when given a tinycolor instance, tinycolor() returns it" + ); + assert( + new tinycolor(r) === r, + "when given a tinycolor instance, new tinycolor() returns it" + ); + assertEquals( + tinycolor("red", { format: "hex" }).toString(), + "#ff0000", + "tinycolor options are being parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0 }, { format: "hex" }).toString(), + "#ff0000", + "tinycolor options are being parsed" + ); + + var obj = { h: 180, s: 0.5, l: 0.5 }; + var color = tinycolor(obj); + assert( + obj.s === 0.5, + "when given an object, the original object is not modified" + ); +}); + +Deno.test("Original input", function () { + var colorRgbUp = "RGB(39, 39, 39)"; + var colorRgbLow = "rgb(39, 39, 39)"; + var colorRgbMix = "RgB(39, 39, 39)"; + var tinycolorObj = tinycolor(colorRgbMix); + var inputObj = { r: 100, g: 100, b: 100 }; + var r = tinycolor("red"); + + assert( + tinycolor(colorRgbLow).getOriginalInput() === colorRgbLow, + "original lowercase input is returned" + ); + assert( + tinycolor(colorRgbUp).getOriginalInput() === colorRgbUp, + "original uppercase input is returned" + ); + assert( + tinycolor(colorRgbMix).getOriginalInput() === colorRgbMix, + "original mixed input is returned" + ); + assert( + tinycolor(tinycolorObj).getOriginalInput() === colorRgbMix, + "when given a tinycolor instance, the color string is returned" + ); + assert( + tinycolor(inputObj).getOriginalInput() === inputObj, + "when given an object, the object is returned" + ); + assert( + new tinycolor("").getOriginalInput() === "", + "when given an empty string, an empty string is returned" + ); + assert( + new tinycolor(null).getOriginalInput() === "", + "when given a null value, an empty string is returned" + ); +}); + +Deno.test("Cloning color", function () { + var originalColor = tinycolor("red"); + var originalColorRgbString = originalColor.toRgbString(); + + var clonedColor = originalColor.clone(); + assert( + clonedColor.toRgbString() === originalColor.toRgbString(), + "cloned color is identical" + ); + + clonedColor.setAlpha(0.5); + assert( + clonedColor.toRgbString() !== originalColor.toRgbString(), + "cloned color is changing independently from original color" + ); + assert( + originalColorRgbString === originalColor.toRgbString(), + "original color was not changed by cloned color change" + ); +}); +Deno.test("Random color", function () { + var randomColor = tinycolor.random(); + assertEquals(randomColor.getAlpha(), 1); + assertEquals(randomColor.getFormat(), "prgb"); + + randomColor.setAlpha(0.5); + assertEquals(randomColor.toHex8String().slice(-2), "80"); +}); + +// Taken from convertWikipediaColors.html +var conversions = [ + { + hex: "#FFFFFF", + hex8: "#FFFFFFFF", + rgb: { r: "100.0%", g: "100.0%", b: "100.0%" }, + hsv: { h: "0", s: "0.000", v: "1.000" }, + hsl: { h: "0", s: "0.000", l: "1.000" }, + }, + { + hex: "#808080", + hex8: "#808080FF", + rgb: { r: "050.0%", g: "050.0%", b: "050.0%" }, + hsv: { h: "0", s: "0.000", v: "0.500" }, + hsl: { h: "0", s: "0.000", l: "0.500" }, + }, + { + hex: "#000000", + hex8: "#000000FF", + rgb: { r: "000.0%", g: "000.0%", b: "000.0%" }, + hsv: { h: "0", s: "0.000", v: "0.000" }, + hsl: { h: "0", s: "0.000", l: "0.000" }, + }, + { + hex: "#FF0000", + hex8: "#FF0000FF", + rgb: { r: "100.0%", g: "000.0%", b: "000.0%" }, + hsv: { h: "0.0", s: "1.000", v: "1.000" }, + hsl: { h: "0.0", s: "1.000", l: "0.500" }, + }, + { + hex: "#BFBF00", + hex8: "#BFBF00FF", + rgb: { r: "075.0%", g: "075.0%", b: "000.0%" }, + hsv: { h: "60.0", s: "1.000", v: "0.750" }, + hsl: { h: "60.0", s: "1.000", l: "0.375" }, + }, + { + hex: "#008000", + hex8: "#008000FF", + rgb: { r: "000.0%", g: "050.0%", b: "000.0%" }, + hsv: { h: "120.0", s: "1.000", v: "0.500" }, + hsl: { h: "120.0", s: "1.000", l: "0.250" }, + }, + { + hex: "#80FFFF", + hex8: "#80FFFFFF", + rgb: { r: "050.0%", g: "100.0%", b: "100.0%" }, + hsv: { h: "180.0", s: "0.500", v: "1.000" }, + hsl: { h: "180.0", s: "1.000", l: "0.750" }, + }, + { + hex: "#8080FF", + hex8: "#8080FFFF", + rgb: { r: "050.0%", g: "050.0%", b: "100.0%" }, + hsv: { h: "240.0", s: "0.500", v: "1.000" }, + hsl: { h: "240.0", s: "1.000", l: "0.750" }, + }, + { + hex: "#BF40BF", + hex8: "#BF40BFFF", + rgb: { r: "075.0%", g: "025.0%", b: "075.0%" }, + hsv: { h: "300.0", s: "0.667", v: "0.750" }, + hsl: { h: "300.0", s: "0.500", l: "0.500" }, + }, + { + hex: "#A0A424", + hex8: "#A0A424FF", + rgb: { r: "062.8%", g: "064.3%", b: "014.2%" }, + hsv: { h: "61.8", s: "0.779", v: "0.643" }, + hsl: { h: "61.8", s: "0.638", l: "0.393" }, + }, + { + hex: "#1EAC41", + hex8: "#1EAC41FF", + rgb: { r: "011.6%", g: "067.5%", b: "025.5%" }, + hsv: { h: "134.9", s: "0.828", v: "0.675" }, + hsl: { h: "134.9", s: "0.707", l: "0.396" }, + }, + { + hex: "#B430E5", + hex8: "#B430E5FF", + rgb: { r: "070.4%", g: "018.7%", b: "089.7%" }, + hsv: { h: "283.7", s: "0.792", v: "0.897" }, + hsl: { h: "283.7", s: "0.775", l: "0.542" }, + }, + { + hex: "#FEF888", + hex8: "#FEF888FF", + rgb: { r: "099.8%", g: "097.4%", b: "053.2%" }, + hsv: { h: "56.9", s: "0.467", v: "0.998" }, + hsl: { h: "56.9", s: "0.991", l: "0.765" }, + }, + { + hex: "#19CB97", + hex8: "#19CB97FF", + rgb: { r: "009.9%", g: "079.5%", b: "059.1%" }, + hsv: { h: "162.4", s: "0.875", v: "0.795" }, + hsl: { h: "162.4", s: "0.779", l: "0.447" }, + }, + { + hex: "#362698", + hex8: "#362698FF", + rgb: { r: "021.1%", g: "014.9%", b: "059.7%" }, + hsv: { h: "248.3", s: "0.750", v: "0.597" }, + hsl: { h: "248.3", s: "0.601", l: "0.373" }, + }, + { + hex: "#7E7EB8", + hex8: "#7E7EB8FF", + rgb: { r: "049.5%", g: "049.3%", b: "072.1%" }, + hsv: { h: "240.5", s: "0.316", v: "0.721" }, + hsl: { h: "240.5", s: "0.290", l: "0.607" }, + }, +]; + +Deno.test("Color Equality", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + + assert(true, tiny.isValid()); + assert( + true, + "Testing " + + c.hex + + ": " + + tiny.toRgbString() + + " " + + tiny.toPercentageRgbString() + + " " + + tiny.toHsvString() + + " " + + tiny.toHslString() + + " " + + tiny.toHexString() + + "Original: " + + JSON.stringify(c.rgb) + + " " + + JSON.stringify(c.hsv) + + " " + + JSON.stringify(c.hsl) + ); + assert(tinycolor.equals(c.rgb, c.hex), "RGB equals hex " + c.hex); + assert(tinycolor.equals(c.rgb, c.hex8), "RGB equals hex " + c.hex); + assert(tinycolor.equals(c.rgb, c.hsl), "RGB equals HSL " + c.hex); + assert(tinycolor.equals(c.rgb, c.hsv), "RGB equals HSV " + c.hex); + assert(tinycolor.equals(c.rgb, c.rgb), "RGB equals RGB " + c.hex); + + assert(tinycolor.equals(c.hex, c.hex), "hex equals hex " + c.hex); + assert(tinycolor.equals(c.hex, c.hex8), "hex equals hex8 " + c.hex); + assert(tinycolor.equals(c.hex, c.hsl), "hex equals HSL " + c.hex); + assert(tinycolor.equals(c.hex, c.hsv), "hex equals HSV " + c.hex); + + assert(tinycolor.equals(c.hsl, c.hsv), "HSL equals HSV " + c.hex); + } +}); + +Deno.test("With Ratio", function () { + assertEquals( + tinycolor.fromRatio({ r: 1, g: 1, b: 1 }).toHexString(), + "#ffffff", + "white" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 0.5 }).toRgbString(), + "rgba(255, 0, 0, 0.5)", + "alpha works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 1 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha = 1 works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 10 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha > 1 works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: -1 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha < 1 works when ratio is parsed" + ); +}); + +Deno.test("Without Ratio", function () { + assertEquals( + tinycolor({ r: 1, g: 1, b: 1 }).toHexString(), + "#010101", + "010101" + ); + assertEquals( + tinycolor({ r: 0.1, g: 0.1, b: 0.1 }).toHexString(), + "#000000", + "000000" + ); + assertEquals(tinycolor("rgb .1 .1 .1").toHexString(), "#000000", "000000"); +}); + +Deno.test("RGB Text Parsing", function () { + assertEquals( + tinycolor("rgb 255 0 0").toHexString(), + "#ff0000", + "spaced input" + ); + assertEquals( + tinycolor("rgb(255, 0, 0)").toHexString(), + "#ff0000", + "parenthesized input" + ); + assertEquals( + tinycolor("rgb (255, 0, 0)").toHexString(), + "#ff0000", + "parenthesized spaced input" + ); + assertEquals( + tinycolor({ r: 255, g: 0, b: 0 }).toHexString(), + "#ff0000", + "object input" + ); + assertEquals( + tinycolor({ r: 255, g: 0, b: 0 }).toRgb(), + { + r: 255, + g: 0, + b: 0, + a: 1, + }, + "object input and compare" + ); + + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb(200, 100, 0)")); + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); + assert( + tinycolor.equals({ r: 200, g: 100, b: 0, a: 0.4 }, "rgba 200 100 0 .4") + ); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgba 200 100 0 1")); + + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb(200, 100, 0)")); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); + + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb(200, 100, 0)") + ); + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") + ); + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") + ); +}); + +Deno.test("Percentage RGB Text Parsing", function () { + assertEquals( + tinycolor("rgb 100% 0% 0%").toHexString(), + "#ff0000", + "spaced input" + ); + assertEquals( + tinycolor("rgb(100%, 0%, 0%)").toHexString(), + "#ff0000", + "parenthesized input" + ); + assertEquals( + tinycolor("rgb (100%, 0%, 0%)").toHexString(), + "#ff0000", + "parenthesized spaced input" + ); + assertEquals( + tinycolor({ r: "100%", g: "0%", b: "0%" }).toHexString(), + "#ff0000", + "object input" + ); + assertEquals( + tinycolor({ r: "100%", g: "0%", b: "0%" }).toRgb(), + { + r: 255, + g: 0, + b: 0, + a: 1, + }, + "object input and compare" + ); + + assert( + tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") + ); + assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert( + tinycolor.equals( + { r: "90%", g: "45%", b: "0%", a: 0.4 }, + "rgba 90% 45% 0% .4" + ) + ); + assert( + !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgba 90% 45% 0% 1") + ); + + assert( + !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") + ); + assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb(90%, 45%, 0%)" + ) + ); + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb 90% 45% 0%" + ) + ); + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb 90% 45% 0%" + ) + ); +}); + +Deno.test("HSL parsing", function () { + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toHexString(), + "#2400c2", + "to hex" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toRgbString(), + "rgb(36, 0, 194)", + "to rgb" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toHslString(), + "hsl(251, 100%, 38%)", + "to hsl" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38, a: 0.5 }).toHslString(), + "hsla(251, 100%, 38%, 0.5)", + "to hsla" + ); + assertEquals( + tinycolor("hsl(251, 100, 38)").toHexString(), + "#2400c2", + "to hex" + ); + assertEquals( + tinycolor("hsl(251, 100%, 38%)").toRgbString(), + "rgb(36, 0, 194)", + "to rgb" + ); + assertEquals( + tinycolor("hsl(251, 100%, 38%)").toHslString(), + "hsl(251, 100%, 38%)", + "to hsl" + ); + assertEquals( + tinycolor("hsl 100 20 10").toHslString(), + "hsl(100, 20%, 10%)", + "problematic hsl" + ); +}); + +Deno.test("Hex Parsing", function () { + assertEquals(tinycolor("rgb 255 0 0").toHexString(), "#ff0000"); + assertEquals(tinycolor("rgb 255 0 0").toHexString(true), "#f00"); + + assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8String(), "#ff000080"); + assertEquals(tinycolor("rgba 255 0 0 0").toHex8String(), "#ff000000"); + assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(), "#ff0000ff"); + assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(true), "#f00f"); + + assertEquals(tinycolor("rgb 255 0 0").toHex(), "ff0000"); + assertEquals(tinycolor("rgb 255 0 0").toHex(true), "f00"); + assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8(), "ff000080"); +}); + +Deno.test("HSV Parsing", function () { + assertEquals( + tinycolor("hsv 251.1 0.887 .918").toHsvString(), + "hsv(251, 89%, 92%)" + ); + assertEquals( + tinycolor("hsv 251.1 0.887 0.918").toHsvString(), + "hsv(251, 89%, 92%)" + ); + assertEquals( + tinycolor("hsva 251.1 0.887 0.918 0.5").toHsvString(), + "hsva(251, 89%, 92%, 0.5)" + ); +}); + +Deno.test("Invalid Parsing", function () { + var invalidColor = tinycolor("this is not a color"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor("#red"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor(" #red"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor("##123456"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor(" ##123456"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ r: "invalid", g: "invalid", b: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ h: "invalid", s: "invalid", l: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ h: "invalid", s: "invalid", v: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); +}); + +Deno.test("Named colors", function () { + assertEquals(tinycolor("aliceblue").toHex(), "f0f8ff"); + assertEquals(tinycolor("antiquewhite").toHex(), "faebd7"); + assertEquals(tinycolor("aqua").toHex(), "00ffff"); + assertEquals(tinycolor("aquamarine").toHex(), "7fffd4"); + assertEquals(tinycolor("azure").toHex(), "f0ffff"); + assertEquals(tinycolor("beige").toHex(), "f5f5dc"); + assertEquals(tinycolor("bisque").toHex(), "ffe4c4"); + assertEquals(tinycolor("black").toHex(), "000000"); + assertEquals(tinycolor("blanchedalmond").toHex(), "ffebcd"); + assertEquals(tinycolor("blue").toHex(), "0000ff"); + assertEquals(tinycolor("blueviolet").toHex(), "8a2be2"); + assertEquals(tinycolor("brown").toHex(), "a52a2a"); + assertEquals(tinycolor("burlywood").toHex(), "deb887"); + assertEquals(tinycolor("cadetblue").toHex(), "5f9ea0"); + assertEquals(tinycolor("chartreuse").toHex(), "7fff00"); + assertEquals(tinycolor("chocolate").toHex(), "d2691e"); + assertEquals(tinycolor("coral").toHex(), "ff7f50"); + assertEquals(tinycolor("cornflowerblue").toHex(), "6495ed"); + assertEquals(tinycolor("cornsilk").toHex(), "fff8dc"); + assertEquals(tinycolor("crimson").toHex(), "dc143c"); + assertEquals(tinycolor("cyan").toHex(), "00ffff"); + assertEquals(tinycolor("darkblue").toHex(), "00008b"); + assertEquals(tinycolor("darkcyan").toHex(), "008b8b"); + assertEquals(tinycolor("darkgoldenrod").toHex(), "b8860b"); + assertEquals(tinycolor("darkgray").toHex(), "a9a9a9"); + assertEquals(tinycolor("darkgreen").toHex(), "006400"); + assertEquals(tinycolor("darkkhaki").toHex(), "bdb76b"); + assertEquals(tinycolor("darkmagenta").toHex(), "8b008b"); + assertEquals(tinycolor("darkolivegreen").toHex(), "556b2f"); + assertEquals(tinycolor("darkorange").toHex(), "ff8c00"); + assertEquals(tinycolor("darkorchid").toHex(), "9932cc"); + assertEquals(tinycolor("darkred").toHex(), "8b0000"); + assertEquals(tinycolor("darksalmon").toHex(), "e9967a"); + assertEquals(tinycolor("darkseagreen").toHex(), "8fbc8f"); + assertEquals(tinycolor("darkslateblue").toHex(), "483d8b"); + assertEquals(tinycolor("darkslategray").toHex(), "2f4f4f"); + assertEquals(tinycolor("darkturquoise").toHex(), "00ced1"); + assertEquals(tinycolor("darkviolet").toHex(), "9400d3"); + assertEquals(tinycolor("deeppink").toHex(), "ff1493"); + assertEquals(tinycolor("deepskyblue").toHex(), "00bfff"); + assertEquals(tinycolor("dimgray").toHex(), "696969"); + assertEquals(tinycolor("dodgerblue").toHex(), "1e90ff"); + assertEquals(tinycolor("firebrick").toHex(), "b22222"); + assertEquals(tinycolor("floralwhite").toHex(), "fffaf0"); + assertEquals(tinycolor("forestgreen").toHex(), "228b22"); + assertEquals(tinycolor("fuchsia").toHex(), "ff00ff"); + assertEquals(tinycolor("gainsboro").toHex(), "dcdcdc"); + assertEquals(tinycolor("ghostwhite").toHex(), "f8f8ff"); + assertEquals(tinycolor("gold").toHex(), "ffd700"); + assertEquals(tinycolor("goldenrod").toHex(), "daa520"); + assertEquals(tinycolor("gray").toHex(), "808080"); + assertEquals(tinycolor("grey").toHex(), "808080"); + assertEquals(tinycolor("green").toHex(), "008000"); + assertEquals(tinycolor("greenyellow").toHex(), "adff2f"); + assertEquals(tinycolor("honeydew").toHex(), "f0fff0"); + assertEquals(tinycolor("hotpink").toHex(), "ff69b4"); + assertEquals(tinycolor("indianred ").toHex(), "cd5c5c"); + assertEquals(tinycolor("indigo ").toHex(), "4b0082"); + assertEquals(tinycolor("ivory").toHex(), "fffff0"); + assertEquals(tinycolor("khaki").toHex(), "f0e68c"); + assertEquals(tinycolor("lavender").toHex(), "e6e6fa"); + assertEquals(tinycolor("lavenderblush").toHex(), "fff0f5"); + assertEquals(tinycolor("lawngreen").toHex(), "7cfc00"); + assertEquals(tinycolor("lemonchiffon").toHex(), "fffacd"); + assertEquals(tinycolor("lightblue").toHex(), "add8e6"); + assertEquals(tinycolor("lightcoral").toHex(), "f08080"); + assertEquals(tinycolor("lightcyan").toHex(), "e0ffff"); + assertEquals(tinycolor("lightgoldenrodyellow").toHex(), "fafad2"); + assertEquals(tinycolor("lightgrey").toHex(), "d3d3d3"); + assertEquals(tinycolor("lightgreen").toHex(), "90ee90"); + assertEquals(tinycolor("lightpink").toHex(), "ffb6c1"); + assertEquals(tinycolor("lightsalmon").toHex(), "ffa07a"); + assertEquals(tinycolor("lightseagreen").toHex(), "20b2aa"); + assertEquals(tinycolor("lightskyblue").toHex(), "87cefa"); + assertEquals(tinycolor("lightslategray").toHex(), "778899"); + assertEquals(tinycolor("lightsteelblue").toHex(), "b0c4de"); + assertEquals(tinycolor("lightyellow").toHex(), "ffffe0"); + assertEquals(tinycolor("lime").toHex(), "00ff00"); + assertEquals(tinycolor("limegreen").toHex(), "32cd32"); + assertEquals(tinycolor("linen").toHex(), "faf0e6"); + assertEquals(tinycolor("magenta").toHex(), "ff00ff"); + assertEquals(tinycolor("maroon").toHex(), "800000"); + assertEquals(tinycolor("mediumaquamarine").toHex(), "66cdaa"); + assertEquals(tinycolor("mediumblue").toHex(), "0000cd"); + assertEquals(tinycolor("mediumorchid").toHex(), "ba55d3"); + assertEquals(tinycolor("mediumpurple").toHex(), "9370db"); + assertEquals(tinycolor("mediumseagreen").toHex(), "3cb371"); + assertEquals(tinycolor("mediumslateblue").toHex(), "7b68ee"); + assertEquals(tinycolor("mediumspringgreen").toHex(), "00fa9a"); + assertEquals(tinycolor("mediumturquoise").toHex(), "48d1cc"); + assertEquals(tinycolor("mediumvioletred").toHex(), "c71585"); + assertEquals(tinycolor("midnightblue").toHex(), "191970"); + assertEquals(tinycolor("mintcream").toHex(), "f5fffa"); + assertEquals(tinycolor("mistyrose").toHex(), "ffe4e1"); + assertEquals(tinycolor("moccasin").toHex(), "ffe4b5"); + assertEquals(tinycolor("navajowhite").toHex(), "ffdead"); + assertEquals(tinycolor("navy").toHex(), "000080"); + assertEquals(tinycolor("oldlace").toHex(), "fdf5e6"); + assertEquals(tinycolor("olive").toHex(), "808000"); + assertEquals(tinycolor("olivedrab").toHex(), "6b8e23"); + assertEquals(tinycolor("orange").toHex(), "ffa500"); + assertEquals(tinycolor("orangered").toHex(), "ff4500"); + assertEquals(tinycolor("orchid").toHex(), "da70d6"); + assertEquals(tinycolor("palegoldenrod").toHex(), "eee8aa"); + assertEquals(tinycolor("palegreen").toHex(), "98fb98"); + assertEquals(tinycolor("paleturquoise").toHex(), "afeeee"); + assertEquals(tinycolor("palevioletred").toHex(), "db7093"); + assertEquals(tinycolor("papayawhip").toHex(), "ffefd5"); + assertEquals(tinycolor("peachpuff").toHex(), "ffdab9"); + assertEquals(tinycolor("peru").toHex(), "cd853f"); + assertEquals(tinycolor("pink").toHex(), "ffc0cb"); + assertEquals(tinycolor("plum").toHex(), "dda0dd"); + assertEquals(tinycolor("powderblue").toHex(), "b0e0e6"); + assertEquals(tinycolor("purple").toHex(), "800080"); + assertEquals(tinycolor("rebeccapurple").toHex(), "663399"); + assertEquals(tinycolor("red").toHex(), "ff0000"); + assertEquals(tinycolor("rosybrown").toHex(), "bc8f8f"); + assertEquals(tinycolor("royalblue").toHex(), "4169e1"); + assertEquals(tinycolor("saddlebrown").toHex(), "8b4513"); + assertEquals(tinycolor("salmon").toHex(), "fa8072"); + assertEquals(tinycolor("sandybrown").toHex(), "f4a460"); + assertEquals(tinycolor("seagreen").toHex(), "2e8b57"); + assertEquals(tinycolor("seashell").toHex(), "fff5ee"); + assertEquals(tinycolor("sienna").toHex(), "a0522d"); + assertEquals(tinycolor("silver").toHex(), "c0c0c0"); + assertEquals(tinycolor("skyblue").toHex(), "87ceeb"); + assertEquals(tinycolor("slateblue").toHex(), "6a5acd"); + assertEquals(tinycolor("slategray").toHex(), "708090"); + assertEquals(tinycolor("snow").toHex(), "fffafa"); + assertEquals(tinycolor("springgreen").toHex(), "00ff7f"); + assertEquals(tinycolor("steelblue").toHex(), "4682b4"); + assertEquals(tinycolor("tan").toHex(), "d2b48c"); + assertEquals(tinycolor("teal").toHex(), "008080"); + assertEquals(tinycolor("thistle").toHex(), "d8bfd8"); + assertEquals(tinycolor("tomato").toHex(), "ff6347"); + assertEquals(tinycolor("turquoise").toHex(), "40e0d0"); + assertEquals(tinycolor("violet").toHex(), "ee82ee"); + assertEquals(tinycolor("wheat").toHex(), "f5deb3"); + assertEquals(tinycolor("white").toHex(), "ffffff"); + assertEquals(tinycolor("whitesmoke").toHex(), "f5f5f5"); + assertEquals(tinycolor("yellow").toHex(), "ffff00"); + assertEquals(tinycolor("yellowgreen").toHex(), "9acd32"); + + assertEquals(tinycolor("#f00").toName(), "red"); + assertEquals(tinycolor("#fa0a0a").toName(), false); +}); + +Deno.test("Invalid alpha should normalize to 1", function () { + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: -1 }).toRgbString(), + "rgb(255, 20, 10)", + "Negative value" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: -0 }).toRgbString(), + "rgba(255, 20, 10, 0)", + "Negative 0" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toRgbString(), + "rgba(255, 20, 10, 0)", + "0" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0.5 }).toRgbString(), + "rgba(255, 20, 10, 0.5)", + ".5" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 1 }).toRgbString(), + "rgb(255, 20, 10)", + "1" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 100 }).toRgbString(), + "rgb(255, 20, 10)", + "Greater than 1" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: "asdfasd" }).toRgbString(), + "rgb(255, 20, 10)", + "Non Numeric" + ); + + assertEquals( + tinycolor("#fff").toRgbString(), + "rgb(255, 255, 255)", + "Hex should be 1" + ); + assertEquals( + tinycolor("rgba 255 0 0 100").toRgbString(), + "rgb(255, 0, 0)", + "Greater than 1 in string parsing" + ); +}); + +Deno.test("toString() with alpha set", function () { + var redNamed = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0.6 }, + { + format: "name", + } + ); + var transparentNamed = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0 }, + { + format: "name", + } + ); + var redHex = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0.4 }, + { + format: "hex", + } + ); + + assertEquals(redNamed.getFormat(), "name", "getFormat() is correct"); + assertEquals(redHex.getFormat(), "hex", "getFormat() is correct"); + + assertEquals( + redNamed.toString(), + "rgba(255, 0, 0, 0.6)", + "Names should default to rgba if alpha is < 1" + ); + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0.4)", + "Hex should default to rgba if alpha is < 1" + ); + + assertEquals( + redNamed.toString("hex"), + "#ff0000", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex6"), + "#ff0000", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex3"), + "#f00", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex8"), + "#ff000099", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex4"), + "#f009", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("name"), + "#ff0000", + "Semi transparent names should return hex in toString() if name format is specified" + ); + + assertEquals( + redNamed.toName(), + false, + "Semi transparent names should be false in toName()" + ); + + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0.4)", + "Hex should default to rgba if alpha is < 1" + ); + assertEquals( + transparentNamed.toString(), + "transparent", + "Named color should equal transparent if alpha == 0" + ); + + redHex.setAlpha(0); + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0)", + "Hex should default to rgba if alpha is = 0" + ); +}); + +Deno.test("setting alpha", function () { + var hexSetter = tinycolor("rgba(255, 0, 0, 1)"); + assertEquals(hexSetter.getAlpha(), 1, "Alpha should start as 1"); + var returnedFromSetAlpha = hexSetter.setAlpha(0.9); + assertEquals( + returnedFromSetAlpha, + hexSetter, + "setAlpha return value should be the color." + ); + assertEquals(hexSetter.getAlpha(), 0.9, "setAlpha should change alpha value"); + hexSetter.setAlpha(0.5); + assertEquals(hexSetter.getAlpha(), 0.5, "setAlpha should change alpha value"); + hexSetter.setAlpha(0); + assertEquals(hexSetter.getAlpha(), 0, "setAlpha should change alpha value"); + hexSetter.setAlpha(-1); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with value < 0 should be bound to 1" + ); + hexSetter.setAlpha(2); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with value > 1 should be bound to 1" + ); + hexSetter.setAlpha(); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); + hexSetter.setAlpha(null); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); + hexSetter.setAlpha("test"); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); +}); + +Deno.test("Alpha = 0 should act differently on toName()", function () { + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toName(), + "transparent", + "0" + ); + assertEquals( + tinycolor("transparent").toString(), + "transparent", + "toString when passed" + ); + assertEquals(tinycolor("transparent").toHex(), "000000", "toHex"); +}); + +Deno.test("getBrightness", function () { + assertEquals(tinycolor("#000").getBrightness(), 0, "returns 0 for #000"); + assertEquals(tinycolor("#fff").getBrightness(), 255, "returns 255 for #fff"); +}); + +Deno.test("getLuminance", function () { + assertEquals(tinycolor("#000").getLuminance(), 0, "returns 0 for #000"); + assertEquals(tinycolor("#fff").getLuminance(), 1, "returns 1 for #fff"); +}); + +Deno.test("isDark returns true/false for dark/light colors", function () { + assertEquals(tinycolor("#000").isDark(), true, "#000 is dark"); + assertEquals(tinycolor("#111").isDark(), true, "#111 is dark"); + assertEquals(tinycolor("#222").isDark(), true, "#222 is dark"); + assertEquals(tinycolor("#333").isDark(), true, "#333 is dark"); + assertEquals(tinycolor("#444").isDark(), true, "#444 is dark"); + assertEquals(tinycolor("#555").isDark(), true, "#555 is dark"); + assertEquals(tinycolor("#666").isDark(), true, "#666 is dark"); + assertEquals(tinycolor("#777").isDark(), true, "#777 is dark"); + assertEquals(tinycolor("#888").isDark(), false, "#888 is not dark"); + assertEquals(tinycolor("#999").isDark(), false, "#999 is not dark"); + assertEquals(tinycolor("#aaa").isDark(), false, "#aaa is not dark"); + assertEquals(tinycolor("#bbb").isDark(), false, "#bbb is not dark"); + assertEquals(tinycolor("#ccc").isDark(), false, "#ccc is not dark"); + assertEquals(tinycolor("#ddd").isDark(), false, "#ddd is not dark"); + assertEquals(tinycolor("#eee").isDark(), false, "#eee is not dark"); + assertEquals(tinycolor("#fff").isDark(), false, "#fff is not dark"); +}); + +Deno.test("isLight returns true/false for light/dark colors", function () { + assertEquals(tinycolor("#000").isLight(), false, "#000 is not light"); + assertEquals(tinycolor("#111").isLight(), false, "#111 is not light"); + assertEquals(tinycolor("#222").isLight(), false, "#222 is not light"); + assertEquals(tinycolor("#333").isLight(), false, "#333 is not light"); + assertEquals(tinycolor("#444").isLight(), false, "#444 is not light"); + assertEquals(tinycolor("#555").isLight(), false, "#555 is not light"); + assertEquals(tinycolor("#666").isLight(), false, "#666 is not light"); + assertEquals(tinycolor("#777").isLight(), false, "#777 is not light"); + assertEquals(tinycolor("#888").isLight(), true, "#888 is light"); + assertEquals(tinycolor("#999").isLight(), true, "#999 is light"); + assertEquals(tinycolor("#aaa").isLight(), true, "#aaa is light"); + assertEquals(tinycolor("#bbb").isLight(), true, "#bbb is light"); + assertEquals(tinycolor("#ccc").isLight(), true, "#ccc is light"); + assertEquals(tinycolor("#ddd").isLight(), true, "#ddd is light"); + assertEquals(tinycolor("#eee").isLight(), true, "#eee is light"); + assertEquals(tinycolor("#fff").isLight(), true, "#fff is light"); +}); + +Deno.test("HSL Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toHsl()).toHexString(), + "HSL Object" + ); + } +}); + +Deno.test("HSL String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toHslString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "toHslString red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "toHslString green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "toHslString blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("HSV String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toHsvString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "toHsvString red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "toHsvString green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "toHsvString blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("HSV Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toHsv()).toHexString(), + "HSV Object" + ); + } +}); + +Deno.test("RGB Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toRgb()).toHexString(), + "RGB Object" + ); + } +}); + +Deno.test("RGB String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toRgbString()).toHexString(), + "RGB String" + ); + } +}); + +Deno.test("PRGB Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toPercentageRgb()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "Red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "Green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "Blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("PRGB String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toPercentageRgbString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "Red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "Green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "Blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals(tiny.toHexString(), tinycolor(tiny).toHexString(), "Object"); + } +}); + +Deno.test("Color equality", function () { + assert(tinycolor.equals("#ff0000", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#ff0000", "rgb(255, 0, 0)"), "Same alphas"); + assert( + !tinycolor.equals("#ff0000", "rgba(255, 0, 0, .1)"), + "Different alphas" + ); + assert(tinycolor.equals("#ff000066", "rgba(255, 0, 0, .4)"), "Same alphas"); + assert(tinycolor.equals("#f009", "rgba(255, 0, 0, .6)"), "Same alphas"); + assert(tinycolor.equals("#336699CC", "369C"), "Same hex"); + assert(tinycolor.equals("ff0000", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); + assert(tinycolor.equals("f00", "#ff0000"), "Same hex"); + assertEquals(tinycolor("010101").toHexString(), "#010101"); + assert(!tinycolor.equals("#ff0000", "#00ff00"), "Different hex"); + assert( + tinycolor.equals("#ff8000", "rgb(100%, 50%, 0%)"), + "Percentage bounds checking" + ); +}); + +Deno.test("isReadable", function () { + // "#ff0088", "#8822aa" (values used in old WCAG1 tests) + assert( + tinycolor.isReadable("#000000", "#ffffff", { level: "AA", size: "small" }), + "white/black is readable" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", {}), + "not readable - empty wcag2 object" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "small" }), + "not readable - AA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "large" }), + "not readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { + level: "AAA", + size: "large", + }), + "not readable - AAA large" + ); + + // values derived from and validated using the calculators at http://www.dasplankton.de/ContrastA/ + // and http://webaim.org/resources/contrastchecker/ + + // "#ff0088", "#5c1a72": contrast ratio 3.04 + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "small" }), + "not readable - AA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { + level: "AAA", + size: "large", + }), + "not readable - AAA large" + ); + + // "#ff0088", "#2e0c3a": contrast ratio 4.56 + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "small" }), + "readable - AA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#2e0c3a", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AAA", size: "large" }), + "readable - AAA large" + ); + + // "#db91b8", "#2e0c3a": contrast ratio 7.12 + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "small" }), + "readable - AA small" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "small" }), + "readable - AAA small" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "large" }), + "readable - AAA large" + ); +}); + +Deno.test("readability", function () { + // check return values from readability function. See isReadable above for standards tests. + assertEquals( + tinycolor.readability("#000", "#000"), + 1, + "Readability function test 0" + ); + assertEquals( + tinycolor.readability("#000", "#111"), + 1.1121078324840545, + "Readability function test 1" + ); + assertEquals( + tinycolor.readability("#000", "#fff"), + 21, + "Readability function test 2" + ); +}); + +Deno.test("mostReadable", function () { + assertEquals( + tinycolor + .mostReadable("#000", ["#111", "#222", { wcag2: {} }]) + .toHexString(), + "#222222", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#f00", ["#d00", "#0d0"], { wcag2: {} }) + .toHexString(), + "#00dd00", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#fff", ["#fff", "#fff"], { wcag2: {} }) + .toHexString(), + "#ffffff", + "no different color in list" + ); + //includeFallbackColors + assertEquals( + tinycolor + .mostReadable("#fff", ["#fff", "#fff"], { + includeFallbackColors: true, + }) + .toHexString(), + "#000000", + "no different color in list" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#124", "#125"], { + includeFallbackColors: false, + }) + .toHexString(), + "#112255", + "no readable color in list" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#ffffff", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#124", "#125"], { + includeFallbackColors: true, + }) + .toHexString(), + "#ffffff", + "no readable color in list" + ); + + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#000000", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#2e0c3a"], { + includeFallbackColors: true, + level: "AAA", + size: "large", + }) + .toHexString(), + "#2e0c3a", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#2e0c3a"], { + includeFallbackColors: true, + level: "AAA", + size: "small", + }) + .toHexString(), + "#000000", + "no readable color in list" + ); + + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#ffffff", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#a9acb6"], { + includeFallbackColors: true, + level: "AAA", + size: "large", + }) + .toHexString(), + "#a9acb6", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#a9acb6"], { + includeFallbackColors: true, + level: "AAA", + size: "small", + }) + .toHexString(), + "#ffffff", + "no readable color in list" + ); +}); + +Deno.test("Filters", function () { + assertEquals( + tinycolor("red").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" + ); + assertEquals( + tinycolor("red").toFilter("blue"), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ff0000ff)" + ); + + assertEquals( + tinycolor("transparent").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#00000000)" + ); + assertEquals( + tinycolor("transparent").toFilter("red"), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#ffff0000)" + ); + + assertEquals( + tinycolor("#f0f0f0dd").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ddf0f0f0,endColorstr=#ddf0f0f0)" + ); + assertEquals( + tinycolor("rgba(0, 0, 255, .5").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#800000ff,endColorstr=#800000ff)" + ); +}); + +/* Originally generated with: +var results = []; +for (var i = 0; i <= 100; i++) results.push( tinycolor.saturate("red", i).toHex() ) +console.log(JSON.stringify(results)) +*/ +var DESATURATIONS = [ + "ff0000", + "fe0101", + "fc0303", + "fb0404", + "fa0505", + "f90606", + "f70808", + "f60909", + "f50a0a", + "f40b0b", + "f20d0d", + "f10e0e", + "f00f0f", + "ee1111", + "ed1212", + "ec1313", + "eb1414", + "e91616", + "e81717", + "e71818", + "e61919", + "e41b1b", + "e31c1c", + "e21d1d", + "e01f1f", + "df2020", + "de2121", + "dd2222", + "db2424", + "da2525", + "d92626", + "d72828", + "d62929", + "d52a2a", + "d42b2b", + "d22d2d", + "d12e2e", + "d02f2f", + "cf3030", + "cd3232", + "cc3333", + "cb3434", + "c93636", + "c83737", + "c73838", + "c63939", + "c43b3b", + "c33c3c", + "c23d3d", + "c13e3e", + "bf4040", + "be4141", + "bd4242", + "bb4444", + "ba4545", + "b94646", + "b84747", + "b64949", + "b54a4a", + "b44b4b", + "b34d4d", + "b14e4e", + "b04f4f", + "af5050", + "ad5252", + "ac5353", + "ab5454", + "aa5555", + "a85757", + "a75858", + "a65959", + "a45b5b", + "a35c5c", + "a25d5d", + "a15e5e", + "9f6060", + "9e6161", + "9d6262", + "9c6363", + "9a6565", + "996666", + "986767", + "966969", + "956a6a", + "946b6b", + "936c6c", + "916e6e", + "906f6f", + "8f7070", + "8e7171", + "8c7373", + "8b7474", + "8a7575", + "887777", + "877878", + "867979", + "857a7a", + "837c7c", + "827d7d", + "817e7e", + "808080", +]; +var SATURATIONS = [ + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", +]; +var LIGHTENS = [ + "ff0000", + "ff0505", + "ff0a0a", + "ff0f0f", + "ff1414", + "ff1a1a", + "ff1f1f", + "ff2424", + "ff2929", + "ff2e2e", + "ff3333", + "ff3838", + "ff3d3d", + "ff4242", + "ff4747", + "ff4d4d", + "ff5252", + "ff5757", + "ff5c5c", + "ff6161", + "ff6666", + "ff6b6b", + "ff7070", + "ff7575", + "ff7a7a", + "ff8080", + "ff8585", + "ff8a8a", + "ff8f8f", + "ff9494", + "ff9999", + "ff9e9e", + "ffa3a3", + "ffa8a8", + "ffadad", + "ffb3b3", + "ffb8b8", + "ffbdbd", + "ffc2c2", + "ffc7c7", + "ffcccc", + "ffd1d1", + "ffd6d6", + "ffdbdb", + "ffe0e0", + "ffe5e5", + "ffebeb", + "fff0f0", + "fff5f5", + "fffafa", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", +]; +var BRIGHTENS = [ + "ff0000", + "ff0303", + "ff0505", + "ff0808", + "ff0a0a", + "ff0d0d", + "ff0f0f", + "ff1212", + "ff1414", + "ff1717", + "ff1919", + "ff1c1c", + "ff1f1f", + "ff2121", + "ff2424", + "ff2626", + "ff2929", + "ff2b2b", + "ff2e2e", + "ff3030", + "ff3333", + "ff3636", + "ff3838", + "ff3b3b", + "ff3d3d", + "ff4040", + "ff4242", + "ff4545", + "ff4747", + "ff4a4a", + "ff4c4c", + "ff4f4f", + "ff5252", + "ff5454", + "ff5757", + "ff5959", + "ff5c5c", + "ff5e5e", + "ff6161", + "ff6363", + "ff6666", + "ff6969", + "ff6b6b", + "ff6e6e", + "ff7070", + "ff7373", + "ff7575", + "ff7878", + "ff7a7a", + "ff7d7d", + "ff7f7f", + "ff8282", + "ff8585", + "ff8787", + "ff8a8a", + "ff8c8c", + "ff8f8f", + "ff9191", + "ff9494", + "ff9696", + "ff9999", + "ff9c9c", + "ff9e9e", + "ffa1a1", + "ffa3a3", + "ffa6a6", + "ffa8a8", + "ffabab", + "ffadad", + "ffb0b0", + "ffb2b2", + "ffb5b5", + "ffb8b8", + "ffbaba", + "ffbdbd", + "ffbfbf", + "ffc2c2", + "ffc4c4", + "ffc7c7", + "ffc9c9", + "ffcccc", + "ffcfcf", + "ffd1d1", + "ffd4d4", + "ffd6d6", + "ffd9d9", + "ffdbdb", + "ffdede", + "ffe0e0", + "ffe3e3", + "ffe5e5", + "ffe8e8", + "ffebeb", + "ffeded", + "fff0f0", + "fff2f2", + "fff5f5", + "fff7f7", + "fffafa", + "fffcfc", + "ffffff", +]; +var DARKENS = [ + "ff0000", + "fa0000", + "f50000", + "f00000", + "eb0000", + "e60000", + "e00000", + "db0000", + "d60000", + "d10000", + "cc0000", + "c70000", + "c20000", + "bd0000", + "b80000", + "b30000", + "ad0000", + "a80000", + "a30000", + "9e0000", + "990000", + "940000", + "8f0000", + "8a0000", + "850000", + "800000", + "7a0000", + "750000", + "700000", + "6b0000", + "660000", + "610000", + "5c0000", + "570000", + "520000", + "4d0000", + "470000", + "420000", + "3d0000", + "380000", + "330000", + "2e0000", + "290000", + "240000", + "1f0000", + "190000", + "140000", + "0f0000", + "0a0000", + "050000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", +]; + +Deno.test("Modifications", function () { + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").desaturate(i).toHex(), + DESATURATIONS[i], + "Desaturation " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").saturate(i).toHex(), + SATURATIONS[i], + "Saturation " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").lighten(i).toHex(), + LIGHTENS[i], + "Lighten " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").brighten(i).toHex(), + BRIGHTENS[i], + "Brighter " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").darken(i).toHex(), + DARKENS[i], + "Darken " + i + " works" + ); + } + + assertEquals( + tinycolor("red").greyscale().toHex(), + "808080", + "Greyscale works" + ); +}); + +Deno.test("Spin", function () { + assertEquals( + Math.round(tinycolor("#f00").spin(-1234).toHsl().h), + 206, + "Spinning -1234 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(-360).toHsl().h), + 0, + "Spinning -360 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(-120).toHsl().h), + 240, + "Spinning -120 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(0).toHsl().h), + 0, + "Spinning 0 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(10).toHsl().h), + 10, + "Spinning 10 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(360).toHsl().h), + 0, + "Spinning 360 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(2345).toHsl().h), + 185, + "Spinning 2345 works" + ); + + [-360, 0, 360].forEach(function (delta) { + Object.keys(tinycolor.names).forEach(function (name) { + assertEquals( + tinycolor(name).toHex(), + tinycolor(name).spin(delta).toHex(), + "Spinning " + delta.toString() + " has no effect" + ); + }); + }); +}); + +Deno.test("Mix", function () { + // amount 0 or none + assertEquals( + tinycolor.mix("#000", "#fff").toHsl().l, + 0.5, + "Mixing without amount works" + ); + assertEquals( + tinycolor.mix("#f00", "#000", 0).toHex(), + "ff0000", + "Mixing with 0 amount works" + ); + // This case checks the the problem with floating point numbers (eg 255/90) + assertEquals( + tinycolor.mix("#fff", "#000", 90).toHex(), + "1a1a1a", + "Mixing with 90 amount works correctly" + ); + + // black and white + for (var i = 0; i < 100; i++) { + assertEquals( + Math.round(tinycolor.mix("#000", "#fff", i).toHsl().l * 100) / 100, + i / 100, + "Mixing black and white with " + i + " amount works" + ); + } + + // with colors + for (var i = 0; i < 100; i++) { + var new_hex = Math.round((255 * (100 - i)) / 100).toString(16); + + if (new_hex.length === 1) { + new_hex = "0" + new_hex; + } + + assertEquals( + tinycolor.mix("#f00", "#000", i).toHex(), + new_hex + "0000", + "Mixing " + i + " (red channel)" + ); + assertEquals( + tinycolor.mix("#0f0", "#000", i).toHex(), + "00" + new_hex + "00", + "Mixing " + i + " (green channel)" + ); + assertEquals( + tinycolor.mix("#00f", "#000", i).toHex(), + "0000" + new_hex, + "Mixing " + i + " (blue channel)" + ); + assertEquals( + tinycolor.mix(tinycolor("transparent"), "#000", i).toRgb().a, + i / 100, + "Mixing " + i + " (alpha channel)" + ); + } +}); + +// The combination tests need to be expanded furthe + +function colorsToHexString(colors) { + return colors + .map(function (c) { + return c.toHex(); + }) + .join(","); +} + +Deno.test("complement", function () { + var complementDoesntModifyInstance = tinycolor("red"); + assertEquals( + complementDoesntModifyInstance.complement().toHex(), + "00ffff", + "Complement works" + ); + assertEquals( + complementDoesntModifyInstance.toHex(), + "ff0000", + "Complement did not modify this color" + ); +}); + +Deno.test("analogous", function () { + var combination = tinycolor("red").analogous(); + assertEquals( + colorsToHexString(combination), + "ff0000,ff0066,ff0033,ff0000,ff3300,ff6600", + "Correct Combination" + ); +}); + +Deno.test("monochromatic", function () { + var combination = tinycolor("red").monochromatic(); + assertEquals( + colorsToHexString(combination), + "ff0000,2a0000,550000,800000,aa0000,d40000", + "Correct Combination" + ); +}); + +Deno.test("splitcomplement", function () { + var combination = tinycolor("red").splitcomplement(); + assertEquals( + colorsToHexString(combination), + "ff0000,ccff00,0066ff", + "Correct Combination" + ); +}); + +Deno.test("triad", function () { + var combination = tinycolor("red").triad(); + assertEquals( + colorsToHexString(combination), + "ff0000,00ff00,0000ff", + "Correct Combination" + ); +}); + +Deno.test("tetrad", function () { + var combination = tinycolor("red").tetrad(); + assertEquals( + colorsToHexString(combination), + "ff0000,80ff00,00ffff,7f00ff", + "Correct Combination" + ); +}); + +Deno.test({ + name: "polyad", + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + ignore: true, + fn: function () { + assertThrows(() => { + tinycolor("red").polyad(); + }); + assertThrows(() => { + tinycolor("red").polyad(-1); + }); + assertThrows(() => { + tinycolor("red").polyad("invalid"); + }); + assertEquals(colorsToHexString(tinycolor("red").polyad(1)), "ff0000"); + assertEquals(colorsToHexString(tinycolor("red").polyad("1")), "ff0000"); + assertEquals( + colorsToHexString(tinycolor("red").polyad(2)), + "ff0000,00ffff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(3)), + "ff0000,00ff00,0000ff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(4)), + "ff0000,80ff00,00ffff,7f00ff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(5)), + "ff0000,ccff00,00ff66,0066ff,cc00ff" + ); + }, +}); + + runDenoTests(); +})(); diff --git a/node_modules/tinycolor2/cjs/test_template.js b/node_modules/tinycolor2/cjs/test_template.js new file mode 100644 index 00000000..d170c2cd --- /dev/null +++ b/node_modules/tinycolor2/cjs/test_template.js @@ -0,0 +1,26 @@ +// This file is autogenerated. +// Ideally it wouldn't exist, but it's here to test cjs in node +// Changes should go into ./test.js, and if new assertions are needed +// they'll need to be shimmed here as well +const tinycolor = require("./tinycolor.js"); +const { Deno, testDefinitions } = require("@deno/shim-deno-test"); +async function runDenoTests() { + for (const test of testDefinitions) { + if (test.ignore) { + console.log(`Ignoring ${test.name}`); + continue; + } + console.log(`Running ${test.name}`); + await test.fn(); + console.log(`> Passed ${test.name}`); + } +} +(async () => { + const { assertEquals, assert, assertThrows } = await import( + "../deno_asserts@0.168.0.mjs" + ); + + // CONTENT_GOES_HERE + + runDenoTests(); +})(); diff --git a/node_modules/tinycolor2/cjs/tinycolor.js b/node_modules/tinycolor2/cjs/tinycolor.js new file mode 100644 index 00000000..4f584cab --- /dev/null +++ b/node_modules/tinycolor2/cjs/tinycolor.js @@ -0,0 +1,1188 @@ +// This file is autogenerated. It's used to publish CJS to npm. +(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.tinycolor = factory()); +})(this, (function () { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); + } + + // https://github.com/bgrins/TinyColor + // Brian Grinstead, MIT License + + var trimLeft = /^\s+/; + var trimRight = /\s+$/; + function tinycolor(color, opts) { + color = color ? color : ""; + opts = opts || {}; + + // If input is already a tinycolor, return itself + if (color instanceof tinycolor) { + return color; + } + // If we are called as a function, call using new instead + if (!(this instanceof tinycolor)) { + return new tinycolor(color, opts); + } + var rgb = inputToRGB(color); + this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; + this._gradientType = opts.gradientType; + + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (this._r < 1) this._r = Math.round(this._r); + if (this._g < 1) this._g = Math.round(this._g); + if (this._b < 1) this._b = Math.round(this._b); + this._ok = rgb.ok; + } + tinycolor.prototype = { + isDark: function isDark() { + return this.getBrightness() < 128; + }, + isLight: function isLight() { + return !this.isDark(); + }, + isValid: function isValid() { + return this._ok; + }, + getOriginalInput: function getOriginalInput() { + return this._originalInput; + }, + getFormat: function getFormat() { + return this._format; + }, + getAlpha: function getAlpha() { + return this._a; + }, + getBrightness: function getBrightness() { + //http://www.w3.org/TR/AERT#color-contrast + var rgb = this.toRgb(); + return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; + }, + getLuminance: function getLuminance() { + //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + var rgb = this.toRgb(); + var RsRGB, GsRGB, BsRGB, R, G, B; + RsRGB = rgb.r / 255; + GsRGB = rgb.g / 255; + BsRGB = rgb.b / 255; + if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); + if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); + if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; + }, + setAlpha: function setAlpha(value) { + this._a = boundAlpha(value); + this._roundA = Math.round(100 * this._a) / 100; + return this; + }, + toHsv: function toHsv() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { + h: hsv.h * 360, + s: hsv.s, + v: hsv.v, + a: this._a + }; + }, + toHsvString: function toHsvString() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = Math.round(hsv.h * 360), + s = Math.round(hsv.s * 100), + v = Math.round(hsv.v * 100); + return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; + }, + toHsl: function toHsl() { + var hsl = rgbToHsl(this._r, this._g, this._b); + return { + h: hsl.h * 360, + s: hsl.s, + l: hsl.l, + a: this._a + }; + }, + toHslString: function toHslString() { + var hsl = rgbToHsl(this._r, this._g, this._b); + var h = Math.round(hsl.h * 360), + s = Math.round(hsl.s * 100), + l = Math.round(hsl.l * 100); + return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; + }, + toHex: function toHex(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function toHexString(allow3Char) { + return "#" + this.toHex(allow3Char); + }, + toHex8: function toHex8(allow4Char) { + return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); + }, + toHex8String: function toHex8String(allow4Char) { + return "#" + this.toHex8(allow4Char); + }, + toRgb: function toRgb() { + return { + r: Math.round(this._r), + g: Math.round(this._g), + b: Math.round(this._b), + a: this._a + }; + }, + toRgbString: function toRgbString() { + return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; + }, + toPercentageRgb: function toPercentageRgb() { + return { + r: Math.round(bound01(this._r, 255) * 100) + "%", + g: Math.round(bound01(this._g, 255) * 100) + "%", + b: Math.round(bound01(this._b, 255) * 100) + "%", + a: this._a + }; + }, + toPercentageRgbString: function toPercentageRgbString() { + return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; + }, + toName: function toName() { + if (this._a === 0) { + return "transparent"; + } + if (this._a < 1) { + return false; + } + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function toFilter(secondColor) { + var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? "GradientType = 1, " : ""; + if (secondColor) { + var s = tinycolor(secondColor); + secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); + } + return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; + }, + toString: function toString(format) { + var formatSet = !!format; + format = format || this._format; + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex4") { + formattedString = this.toHex8String(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } + return formattedString || this.toHexString(); + }, + clone: function clone() { + return tinycolor(this.toString()); + }, + _applyModification: function _applyModification(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function lighten() { + return this._applyModification(_lighten, arguments); + }, + brighten: function brighten() { + return this._applyModification(_brighten, arguments); + }, + darken: function darken() { + return this._applyModification(_darken, arguments); + }, + desaturate: function desaturate() { + return this._applyModification(_desaturate, arguments); + }, + saturate: function saturate() { + return this._applyModification(_saturate, arguments); + }, + greyscale: function greyscale() { + return this._applyModification(_greyscale, arguments); + }, + spin: function spin() { + return this._applyModification(_spin, arguments); + }, + _applyCombination: function _applyCombination(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function analogous() { + return this._applyCombination(_analogous, arguments); + }, + complement: function complement() { + return this._applyCombination(_complement, arguments); + }, + monochromatic: function monochromatic() { + return this._applyCombination(_monochromatic, arguments); + }, + splitcomplement: function splitcomplement() { + return this._applyCombination(_splitcomplement, arguments); + }, + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + // polyad: function (number) { + // return this._applyCombination(polyad, [number]); + // }, + triad: function triad() { + return this._applyCombination(polyad, [3]); + }, + tetrad: function tetrad() { + return this._applyCombination(polyad, [4]); + } + }; + + // If input is an object, force 1 into "1.0" to handle ratios properly + // String input requires "1.0" as input, so 1 will be treated as 1 + tinycolor.fromRatio = function (color, opts) { + if (_typeof(color) == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; + } + return tinycolor(color, opts); + }; + + // Given a string or object, convert that input to RGB + // Possible string inputs: + // + // "red" + // "#f00" or "f00" + // "#ff0000" or "ff0000" + // "#ff000000" or "ff000000" + // "rgb 255 0 0" or "rgb (255, 0, 0)" + // "rgb 1.0 0 0" or "rgb (1, 0, 0)" + // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" + // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" + // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" + // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" + // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" + // + function inputToRGB(color) { + var rgb = { + r: 0, + g: 0, + b: 0 + }; + var a = 1; + var s = null; + var v = null; + var l = null; + var ok = false; + var format = false; + if (typeof color == "string") { + color = stringInputToObject(color); + } + if (_typeof(color) == "object") { + if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { + s = convertToPercentage(color.s); + v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, s, v); + ok = true; + format = "hsv"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { + s = convertToPercentage(color.s); + l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, s, l); + ok = true; + format = "hsl"; + } + if (color.hasOwnProperty("a")) { + a = color.a; + } + } + a = boundAlpha(a); + return { + ok: ok, + format: color.format || format, + r: Math.min(255, Math.max(rgb.r, 0)), + g: Math.min(255, Math.max(rgb.g, 0)), + b: Math.min(255, Math.max(rgb.b, 0)), + a: a + }; + } + + // Conversion Functions + // -------------------- + + // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: + // + + // `rgbToRgb` + // Handle bounds / percentage checking to conform to CSS color spec + // + // *Assumes:* r, g, b in [0, 255] or [0, 1] + // *Returns:* { r, g, b } in [0, 255] + function rgbToRgb(r, g, b) { + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; + } + + // `rgbToHsl` + // Converts an RGB color value to HSL. + // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] + // *Returns:* { h, s, l } in [0,1] + function rgbToHsl(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + l = (max + min) / 2; + if (max == min) { + h = s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + l: l + }; + } + + // `hslToRgb` + // Converts an HSL color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hslToRgb(h, s, l) { + var r, g, b; + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + + // `rgbToHsv` + // Converts an RGB color value to HSV + // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] + // *Returns:* { h, s, v } in [0,1] + function rgbToHsv(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + v = max; + var d = max - min; + s = max === 0 ? 0 : d / max; + if (max == min) { + h = 0; // achromatic + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + v: v + }; + } + + // `hsvToRgb` + // Converts an HSV color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + var i = Math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + + // `rgbToHex` + // Converts an RGB color to hex + // Assumes r, g, and b are contained in the set [0, 255] + // Returns a 3 or 6 character hex + function rgbToHex(r, g, b, allow3Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + } + return hex.join(""); + } + + // `rgbaToHex` + // Converts an RGBA color plus alpha transparency to hex + // Assumes r, g, b are contained in the set [0, 255] and + // a in [0, 1]. Returns a 4 or 8 character rgba hex + function rgbaToHex(r, g, b, a, allow4Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; + + // Return a 4 character hex if possible + if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); + } + return hex.join(""); + } + + // `rgbaToArgbHex` + // Converts an RGBA color to an ARGB Hex8 string + // Rarely used, but required for "toFilter()" + function rgbaToArgbHex(r, g, b, a) { + var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + return hex.join(""); + } + + // `equals` + // Can be called with any tinycolor input + tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) return false; + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); + }; + tinycolor.random = function () { + return tinycolor.fromRatio({ + r: Math.random(), + g: Math.random(), + b: Math.random() + }); + }; + + // Modification Functions + // ---------------------- + // Thanks to less.js for some of the basics here + // + + function _desaturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + function _saturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + function _greyscale(color) { + return tinycolor(color).desaturate(100); + } + function _lighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + function _brighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var rgb = tinycolor(color).toRgb(); + rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); + rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); + rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); + return tinycolor(rgb); + } + function _darken(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + + // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. + // Values outside of this range will be wrapped into this range. + function _spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (hsl.h + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); + } + + // Combination Functions + // --------------------- + // Thanks to jQuery xColor for some of the ideas behind these + // + + function _complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); + } + function polyad(color, number) { + if (isNaN(number) || number <= 0) { + throw new Error("Argument to polyad must be a positive number"); + } + var hsl = tinycolor(color).toHsl(); + var result = [tinycolor(color)]; + var step = 360 / number; + for (var i = 1; i < number; i++) { + result.push(tinycolor({ + h: (hsl.h + i * step) % 360, + s: hsl.s, + l: hsl.l + })); + } + return result; + } + function _splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [tinycolor(color), tinycolor({ + h: (h + 72) % 360, + s: hsl.s, + l: hsl.l + }), tinycolor({ + h: (h + 216) % 360, + s: hsl.s, + l: hsl.l + })]; + } + function _analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; + for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; + } + function _monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, + s = hsv.s, + v = hsv.v; + var ret = []; + var modification = 1 / results; + while (results--) { + ret.push(tinycolor({ + h: h, + s: s, + v: v + })); + v = (v + modification) % 1; + } + return ret; + } + + // Utility Functions + // --------------------- + + tinycolor.mix = function (color1, color2, amount) { + amount = amount === 0 ? 0 : amount || 50; + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); + var p = amount / 100; + var rgba = { + r: (rgb2.r - rgb1.r) * p + rgb1.r, + g: (rgb2.g - rgb1.g) * p + rgb1.g, + b: (rgb2.b - rgb1.b) * p + rgb1.b, + a: (rgb2.a - rgb1.a) * p + rgb1.a + }; + return tinycolor(rgba); + }; + + // Readability Functions + // --------------------- + // false + // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false + tinycolor.isReadable = function (color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; + out = false; + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; + } + return out; + }; + + // `mostReadable` + // Given a base color and a list of possible foreground or background + // colors for that base, returns the most readable color. + // Optionally returns Black or White if the most readable color is unreadable. + // *Example* + // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" + // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" + // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" + // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" + tinycolor.mostReadable = function (baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size; + args = args || {}; + includeFallbackColors = args.includeFallbackColors; + level = args.level; + size = args.size; + for (var i = 0; i < colorList.length; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); + } + } + if (tinycolor.isReadable(baseColor, bestColor, { + level: level, + size: size + }) || !includeFallbackColors) { + return bestColor; + } else { + args.includeFallbackColors = false; + return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); + } + }; + + // Big List of Colors + // ------------------ + // + var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" + }; + + // Make it easy to access colors via `hexNames[hex]` + var hexNames = tinycolor.hexNames = flip(names); + + // Utilities + // --------- + + // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` + function flip(o) { + var flipped = {}; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; + } + + // Return a valid alpha value [0,1] with all invalid values being set to 1 + function boundAlpha(a) { + a = parseFloat(a); + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } + return a; + } + + // Take input from [0, n] and return it as [0, 1] + function bound01(n, max) { + if (isOnePointZero(n)) n = "100%"; + var processPercent = isPercentage(n); + n = Math.min(max, Math.max(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; + } + + // Handle floating point rounding errors + if (Math.abs(n - max) < 0.000001) { + return 1; + } + + // Convert into [0, 1] range if it isn't already + return n % max / parseFloat(max); + } + + // Force a number between 0 and 1 + function clamp01(val) { + return Math.min(1, Math.max(0, val)); + } + + // Parse a base-16 hex value into a base-10 integer + function parseIntFromHex(val) { + return parseInt(val, 16); + } + + // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 + // + function isOnePointZero(n) { + return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; + } + + // Check to see if string passed in is a percentage + function isPercentage(n) { + return typeof n === "string" && n.indexOf("%") != -1; + } + + // Force a hex value to have 2 characters + function pad2(c) { + return c.length == 1 ? "0" + c : "" + c; + } + + // Replace a decimal with it's percentage value + function convertToPercentage(n) { + if (n <= 1) { + n = n * 100 + "%"; + } + return n; + } + + // Converts a decimal to a hex value + function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); + } + // Converts a hex value to a decimal + function convertHexToDecimal(h) { + return parseIntFromHex(h) / 255; + } + var matchers = function () { + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + return { + CSS_UNIT: new RegExp(CSS_UNIT), + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; + }(); + + // `isValidCSSUnit` + // Take in a single string / number and check to see if it looks like a CSS unit + // (see `matchers` above for definition). + function isValidCSSUnit(color) { + return !!matchers.CSS_UNIT.exec(color); + } + + // `stringInputToObject` + // Permissive string parsing. Take in a number of formats, and output an object + // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` + function stringInputToObject(color) { + color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } else if (color == "transparent") { + return { + r: 0, + g: 0, + b: 0, + a: 0, + format: "name" + }; + } + + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if (match = matchers.rgb.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3] + }; + } + if (match = matchers.rgba.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3], + a: match[4] + }; + } + if (match = matchers.hsl.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3] + }; + } + if (match = matchers.hsla.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3], + a: match[4] + }; + } + if (match = matchers.hsv.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3] + }; + } + if (match = matchers.hsva.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3], + a: match[4] + }; + } + if (match = matchers.hex8.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + a: convertHexToDecimal(match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex6.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if (match = matchers.hex4.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + a: convertHexToDecimal(match[4] + "" + match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex3.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + format: named ? "name" : "hex" + }; + } + return false; + } + function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || { + level: "AA", + size: "small" + }; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return { + level: level, + size: size + }; + } + + return tinycolor; + +})); diff --git a/node_modules/tinycolor2/deno_asserts@0.168.0.mjs b/node_modules/tinycolor2/deno_asserts@0.168.0.mjs new file mode 100644 index 00000000..685fdd20 --- /dev/null +++ b/node_modules/tinycolor2/deno_asserts@0.168.0.mjs @@ -0,0 +1,807 @@ +// deno-fmt-ignore-file +// deno-lint-ignore-file +// This code was bundled using `deno bundle` and it's not recommended to edit it manually +// Using `deno bundle https://deno.land/std@0.168.0/testing/asserts.ts > npm/deno_asserts@0.168.0.mjs` + +const { Deno } = globalThis; +const noColor = typeof Deno?.noColor === "boolean" ? Deno.noColor : true; +let enabled = !noColor; +function code(open, close) { + return { + open: `\x1b[${open.join(";")}m`, + close: `\x1b[${close}m`, + regexp: new RegExp(`\\x1b\\[${close}m`, "g") + }; +} +function run(str, code) { + return enabled ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` : str; +} +function bold(str) { + return run(str, code([ + 1 + ], 22)); +} +function red(str) { + return run(str, code([ + 31 + ], 39)); +} +function green(str) { + return run(str, code([ + 32 + ], 39)); +} +function white(str) { + return run(str, code([ + 37 + ], 39)); +} +function gray(str) { + return brightBlack(str); +} +function brightBlack(str) { + return run(str, code([ + 90 + ], 39)); +} +function bgRed(str) { + return run(str, code([ + 41 + ], 49)); +} +function bgGreen(str) { + return run(str, code([ + 42 + ], 49)); +} +const ANSI_PATTERN = new RegExp([ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))" +].join("|"), "g"); +function stripColor(string) { + return string.replace(ANSI_PATTERN, ""); +} +var DiffType; +(function(DiffType) { + DiffType["removed"] = "removed"; + DiffType["common"] = "common"; + DiffType["added"] = "added"; +})(DiffType || (DiffType = {})); +const REMOVED = 1; +const COMMON = 2; +const ADDED = 3; +function createCommon(A, B, reverse) { + const common = []; + if (A.length === 0 || B.length === 0) return []; + for(let i = 0; i < Math.min(A.length, B.length); i += 1){ + if (A[reverse ? A.length - i - 1 : i] === B[reverse ? B.length - i - 1 : i]) { + common.push(A[reverse ? A.length - i - 1 : i]); + } else { + return common; + } + } + return common; +} +function diff(A, B) { + const prefixCommon = createCommon(A, B); + const suffixCommon = createCommon(A.slice(prefixCommon.length), B.slice(prefixCommon.length), true).reverse(); + A = suffixCommon.length ? A.slice(prefixCommon.length, -suffixCommon.length) : A.slice(prefixCommon.length); + B = suffixCommon.length ? B.slice(prefixCommon.length, -suffixCommon.length) : B.slice(prefixCommon.length); + const swapped = B.length > A.length; + [A, B] = swapped ? [ + B, + A + ] : [ + A, + B + ]; + const M = A.length; + const N = B.length; + if (!M && !N && !suffixCommon.length && !prefixCommon.length) return []; + if (!N) { + return [ + ...prefixCommon.map((c)=>({ + type: DiffType.common, + value: c + })), + ...A.map((a)=>({ + type: swapped ? DiffType.added : DiffType.removed, + value: a + })), + ...suffixCommon.map((c)=>({ + type: DiffType.common, + value: c + })) + ]; + } + const offset = N; + const delta = M - N; + const size = M + N + 1; + const fp = Array.from({ + length: size + }, ()=>({ + y: -1, + id: -1 + })); + const routes = new Uint32Array((M * N + size + 1) * 2); + const diffTypesPtrOffset = routes.length / 2; + let ptr = 0; + let p = -1; + function backTrace(A, B, current, swapped) { + const M = A.length; + const N = B.length; + const result = []; + let a = M - 1; + let b = N - 1; + let j = routes[current.id]; + let type = routes[current.id + diffTypesPtrOffset]; + while(true){ + if (!j && !type) break; + const prev = j; + if (type === 1) { + result.unshift({ + type: swapped ? DiffType.removed : DiffType.added, + value: B[b] + }); + b -= 1; + } else if (type === 3) { + result.unshift({ + type: swapped ? DiffType.added : DiffType.removed, + value: A[a] + }); + a -= 1; + } else { + result.unshift({ + type: DiffType.common, + value: A[a] + }); + a -= 1; + b -= 1; + } + j = routes[prev]; + type = routes[prev + diffTypesPtrOffset]; + } + return result; + } + function createFP(slide, down, k, M) { + if (slide && slide.y === -1 && down && down.y === -1) { + return { + y: 0, + id: 0 + }; + } + if (down && down.y === -1 || k === M || (slide && slide.y) > (down && down.y) + 1) { + const prev = slide.id; + ptr++; + routes[ptr] = prev; + routes[ptr + diffTypesPtrOffset] = ADDED; + return { + y: slide.y, + id: ptr + }; + } else { + const prev1 = down.id; + ptr++; + routes[ptr] = prev1; + routes[ptr + diffTypesPtrOffset] = REMOVED; + return { + y: down.y + 1, + id: ptr + }; + } + } + function snake(k, slide, down, _offset, A, B) { + const M = A.length; + const N = B.length; + if (k < -N || M < k) return { + y: -1, + id: -1 + }; + const fp = createFP(slide, down, k, M); + while(fp.y + k < M && fp.y < N && A[fp.y + k] === B[fp.y]){ + const prev = fp.id; + ptr++; + fp.id = ptr; + fp.y += 1; + routes[ptr] = prev; + routes[ptr + diffTypesPtrOffset] = COMMON; + } + return fp; + } + while(fp[delta + offset].y < N){ + p = p + 1; + for(let k = -p; k < delta; ++k){ + fp[k + offset] = snake(k, fp[k - 1 + offset], fp[k + 1 + offset], offset, A, B); + } + for(let k1 = delta + p; k1 > delta; --k1){ + fp[k1 + offset] = snake(k1, fp[k1 - 1 + offset], fp[k1 + 1 + offset], offset, A, B); + } + fp[delta + offset] = snake(delta, fp[delta - 1 + offset], fp[delta + 1 + offset], offset, A, B); + } + return [ + ...prefixCommon.map((c)=>({ + type: DiffType.common, + value: c + })), + ...backTrace(A, B, fp[delta + offset], swapped), + ...suffixCommon.map((c)=>({ + type: DiffType.common, + value: c + })) + ]; +} +function diffstr(A, B) { + function unescape(string) { + return string.replaceAll("\b", "\\b").replaceAll("\f", "\\f").replaceAll("\t", "\\t").replaceAll("\v", "\\v").replaceAll(/\r\n|\r|\n/g, (str)=>str === "\r" ? "\\r" : str === "\n" ? "\\n\n" : "\\r\\n\r\n"); + } + function tokenize(string, { wordDiff =false } = {}) { + if (wordDiff) { + const tokens = string.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); + const words = /^[a-zA-Z\u{C0}-\u{FF}\u{D8}-\u{F6}\u{F8}-\u{2C6}\u{2C8}-\u{2D7}\u{2DE}-\u{2FF}\u{1E00}-\u{1EFF}]+$/u; + for(let i = 0; i < tokens.length - 1; i++){ + if (!tokens[i + 1] && tokens[i + 2] && words.test(tokens[i]) && words.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + return tokens.filter((token)=>token); + } else { + const tokens1 = [], lines = string.split(/(\n|\r\n)/); + if (!lines[lines.length - 1]) { + lines.pop(); + } + for(let i1 = 0; i1 < lines.length; i1++){ + if (i1 % 2) { + tokens1[tokens1.length - 1] += lines[i1]; + } else { + tokens1.push(lines[i1]); + } + } + return tokens1; + } + } + function createDetails(line, tokens) { + return tokens.filter(({ type })=>type === line.type || type === DiffType.common).map((result, i, t)=>{ + if (result.type === DiffType.common && t[i - 1] && t[i - 1]?.type === t[i + 1]?.type && /\s+/.test(result.value)) { + result.type = t[i - 1].type; + } + return result; + }); + } + const diffResult = diff(tokenize(`${unescape(A)}\n`), tokenize(`${unescape(B)}\n`)); + const added = [], removed = []; + for (const result of diffResult){ + if (result.type === DiffType.added) { + added.push(result); + } + if (result.type === DiffType.removed) { + removed.push(result); + } + } + const aLines = added.length < removed.length ? added : removed; + const bLines = aLines === removed ? added : removed; + for (const a of aLines){ + let tokens = [], b; + while(bLines.length){ + b = bLines.shift(); + tokens = diff(tokenize(a.value, { + wordDiff: true + }), tokenize(b?.value ?? "", { + wordDiff: true + })); + if (tokens.some(({ type , value })=>type === DiffType.common && value.trim().length)) { + break; + } + } + a.details = createDetails(a, tokens); + if (b) { + b.details = createDetails(b, tokens); + } + } + return diffResult; +} +function createColor(diffType, { background =false } = {}) { + background = false; + switch(diffType){ + case DiffType.added: + return (s)=>background ? bgGreen(white(s)) : green(bold(s)); + case DiffType.removed: + return (s)=>background ? bgRed(white(s)) : red(bold(s)); + default: + return white; + } +} +function createSign(diffType) { + switch(diffType){ + case DiffType.added: + return "+ "; + case DiffType.removed: + return "- "; + default: + return " "; + } +} +function buildMessage(diffResult, { stringDiff =false } = {}) { + const messages = [], diffMessages = []; + messages.push(""); + messages.push(""); + messages.push(` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${green(bold("Expected"))}`); + messages.push(""); + messages.push(""); + diffResult.forEach((result)=>{ + const c = createColor(result.type); + const line = result.details?.map((detail)=>detail.type !== DiffType.common ? createColor(detail.type, { + background: true + })(detail.value) : detail.value).join("") ?? result.value; + diffMessages.push(c(`${createSign(result.type)}${line}`)); + }); + messages.push(...stringDiff ? [ + diffMessages.join("") + ] : diffMessages); + messages.push(""); + return messages; +} +function format(v) { + const { Deno } = globalThis; + return typeof Deno?.inspect === "function" ? Deno.inspect(v, { + depth: Infinity, + sorted: true, + trailingComma: true, + compact: false, + iterableLimit: Infinity, + getters: true + }) : `"${String(v).replace(/(?=["\\])/g, "\\")}"`; +} +const CAN_NOT_DISPLAY = "[Cannot display]"; +class AssertionError extends Error { + name = "AssertionError"; + constructor(message){ + super(message); + } +} +function isKeyedCollection(x) { + return [ + Symbol.iterator, + "size" + ].every((k)=>k in x); +} +function equal(c, d) { + const seen = new Map(); + return function compare(a, b) { + if (a && b && (a instanceof RegExp && b instanceof RegExp || a instanceof URL && b instanceof URL)) { + return String(a) === String(b); + } + if (a instanceof Date && b instanceof Date) { + const aTime = a.getTime(); + const bTime = b.getTime(); + if (Number.isNaN(aTime) && Number.isNaN(bTime)) { + return true; + } + return aTime === bTime; + } + if (typeof a === "number" && typeof b === "number") { + return Number.isNaN(a) && Number.isNaN(b) || a === b; + } + if (Object.is(a, b)) { + return true; + } + if (a && typeof a === "object" && b && typeof b === "object") { + if (a && b && !constructorsEqual(a, b)) { + return false; + } + if (a instanceof WeakMap || b instanceof WeakMap) { + if (!(a instanceof WeakMap && b instanceof WeakMap)) return false; + throw new TypeError("cannot compare WeakMap instances"); + } + if (a instanceof WeakSet || b instanceof WeakSet) { + if (!(a instanceof WeakSet && b instanceof WeakSet)) return false; + throw new TypeError("cannot compare WeakSet instances"); + } + if (seen.get(a) === b) { + return true; + } + if (Object.keys(a || {}).length !== Object.keys(b || {}).length) { + return false; + } + seen.set(a, b); + if (isKeyedCollection(a) && isKeyedCollection(b)) { + if (a.size !== b.size) { + return false; + } + let unmatchedEntries = a.size; + for (const [aKey, aValue] of a.entries()){ + for (const [bKey, bValue] of b.entries()){ + if (aKey === aValue && bKey === bValue && compare(aKey, bKey) || compare(aKey, bKey) && compare(aValue, bValue)) { + unmatchedEntries--; + break; + } + } + } + return unmatchedEntries === 0; + } + const merged = { + ...a, + ...b + }; + for (const key of [ + ...Object.getOwnPropertyNames(merged), + ...Object.getOwnPropertySymbols(merged) + ]){ + if (!compare(a && a[key], b && b[key])) { + return false; + } + if (key in a && !(key in b) || key in b && !(key in a)) { + return false; + } + } + if (a instanceof WeakRef || b instanceof WeakRef) { + if (!(a instanceof WeakRef && b instanceof WeakRef)) return false; + return compare(a.deref(), b.deref()); + } + return true; + } + return false; + }(c, d); +} +function constructorsEqual(a, b) { + return a.constructor === b.constructor || a.constructor === Object && !b.constructor || !a.constructor && b.constructor === Object; +} +function assert(expr, msg = "") { + if (!expr) { + throw new AssertionError(msg); + } +} +function assertFalse(expr, msg = "") { + if (expr) { + throw new AssertionError(msg); + } +} +function assertEquals(actual, expected, msg) { + if (equal(actual, expected)) { + return; + } + let message = ""; + const actualString = format(actual); + const expectedString = format(expected); + try { + const stringDiff = typeof actual === "string" && typeof expected === "string"; + const diffResult = stringDiff ? diffstr(actual, expected) : diff(actualString.split("\n"), expectedString.split("\n")); + const diffMsg = buildMessage(diffResult, { + stringDiff + }).join("\n"); + message = `Values are not equal:\n${diffMsg}`; + } catch { + message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`; + } + if (msg) { + message = msg; + } + throw new AssertionError(message); +} +function assertNotEquals(actual, expected, msg) { + if (!equal(actual, expected)) { + return; + } + let actualString; + let expectedString; + try { + actualString = String(actual); + } catch { + actualString = "[Cannot display]"; + } + try { + expectedString = String(expected); + } catch { + expectedString = "[Cannot display]"; + } + if (!msg) { + msg = `actual: ${actualString} expected not to be: ${expectedString}`; + } + throw new AssertionError(msg); +} +function assertStrictEquals(actual, expected, msg) { + if (Object.is(actual, expected)) { + return; + } + let message; + if (msg) { + message = msg; + } else { + const actualString = format(actual); + const expectedString = format(expected); + if (actualString === expectedString) { + const withOffset = actualString.split("\n").map((l)=>` ${l}`).join("\n"); + message = `Values have the same structure but are not reference-equal:\n\n${red(withOffset)}\n`; + } else { + try { + const stringDiff = typeof actual === "string" && typeof expected === "string"; + const diffResult = stringDiff ? diffstr(actual, expected) : diff(actualString.split("\n"), expectedString.split("\n")); + const diffMsg = buildMessage(diffResult, { + stringDiff + }).join("\n"); + message = `Values are not strictly equal:\n${diffMsg}`; + } catch { + message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`; + } + } + } + throw new AssertionError(message); +} +function assertNotStrictEquals(actual, expected, msg) { + if (!Object.is(actual, expected)) { + return; + } + throw new AssertionError(msg ?? `Expected "actual" to be strictly unequal to: ${format(actual)}\n`); +} +function assertAlmostEquals(actual, expected, tolerance = 1e-7, msg) { + if (Object.is(actual, expected)) { + return; + } + const delta = Math.abs(expected - actual); + if (delta <= tolerance) { + return; + } + const f = (n)=>Number.isInteger(n) ? n : n.toExponential(); + throw new AssertionError(msg ?? `actual: "${f(actual)}" expected to be close to "${f(expected)}": \ +delta "${f(delta)}" is greater than "${f(tolerance)}"`); +} +function assertInstanceOf(actual, expectedType, msg = "") { + if (!msg) { + const expectedTypeStr = expectedType.name; + let actualTypeStr = ""; + if (actual === null) { + actualTypeStr = "null"; + } else if (actual === undefined) { + actualTypeStr = "undefined"; + } else if (typeof actual === "object") { + actualTypeStr = actual.constructor?.name ?? "Object"; + } else { + actualTypeStr = typeof actual; + } + if (expectedTypeStr == actualTypeStr) { + msg = `Expected object to be an instance of "${expectedTypeStr}".`; + } else if (actualTypeStr == "function") { + msg = `Expected object to be an instance of "${expectedTypeStr}" but was not an instanced object.`; + } else { + msg = `Expected object to be an instance of "${expectedTypeStr}" but was "${actualTypeStr}".`; + } + } + assert(actual instanceof expectedType, msg); +} +function assertNotInstanceOf(actual, unexpectedType, msg = `Expected object to not be an instance of "${typeof unexpectedType}"`) { + assertFalse(actual instanceof unexpectedType, msg); +} +function assertExists(actual, msg) { + if (actual === undefined || actual === null) { + if (!msg) { + msg = `actual: "${actual}" expected to not be null or undefined`; + } + throw new AssertionError(msg); + } +} +function assertStringIncludes(actual, expected, msg) { + if (!actual.includes(expected)) { + if (!msg) { + msg = `actual: "${actual}" expected to contain: "${expected}"`; + } + throw new AssertionError(msg); + } +} +function assertArrayIncludes(actual, expected, msg) { + const missing = []; + for(let i = 0; i < expected.length; i++){ + let found = false; + for(let j = 0; j < actual.length; j++){ + if (equal(expected[i], actual[j])) { + found = true; + break; + } + } + if (!found) { + missing.push(expected[i]); + } + } + if (missing.length === 0) { + return; + } + if (!msg) { + msg = `actual: "${format(actual)}" expected to include: "${format(expected)}"\nmissing: ${format(missing)}`; + } + throw new AssertionError(msg); +} +function assertMatch(actual, expected, msg) { + if (!expected.test(actual)) { + if (!msg) { + msg = `actual: "${actual}" expected to match: "${expected}"`; + } + throw new AssertionError(msg); + } +} +function assertNotMatch(actual, expected, msg) { + if (expected.test(actual)) { + if (!msg) { + msg = `actual: "${actual}" expected to not match: "${expected}"`; + } + throw new AssertionError(msg); + } +} +function assertObjectMatch(actual, expected) { + function filter(a, b) { + const seen = new WeakMap(); + return fn(a, b); + function fn(a, b) { + if (seen.has(a) && seen.get(a) === b) { + return a; + } + seen.set(a, b); + const filtered = {}; + const entries = [ + ...Object.getOwnPropertyNames(a), + ...Object.getOwnPropertySymbols(a) + ].filter((key)=>key in b).map((key)=>[ + key, + a[key] + ]); + for (const [key, value] of entries){ + if (Array.isArray(value)) { + const subset = b[key]; + if (Array.isArray(subset)) { + filtered[key] = fn({ + ...value + }, { + ...subset + }); + continue; + } + } else if (value instanceof RegExp) { + filtered[key] = value; + continue; + } else if (typeof value === "object") { + const subset1 = b[key]; + if (typeof subset1 === "object" && subset1) { + if (value instanceof Map && subset1 instanceof Map) { + filtered[key] = new Map([ + ...value + ].filter(([k])=>subset1.has(k)).map(([k, v])=>[ + k, + typeof v === "object" ? fn(v, subset1.get(k)) : v + ])); + continue; + } + if (value instanceof Set && subset1 instanceof Set) { + filtered[key] = new Set([ + ...value + ].filter((v)=>subset1.has(v))); + continue; + } + filtered[key] = fn(value, subset1); + continue; + } + } + filtered[key] = value; + } + return filtered; + } + } + return assertEquals(filter(actual, expected), filter(expected, expected)); +} +function fail(msg) { + assert(false, `Failed assertion${msg ? `: ${msg}` : "."}`); +} +function assertIsError(error, ErrorClass, msgIncludes, msg) { + if (error instanceof Error === false) { + throw new AssertionError(`Expected "error" to be an Error object.`); + } + if (ErrorClass && !(error instanceof ErrorClass)) { + msg = `Expected error to be instance of "${ErrorClass.name}", but was "${typeof error === "object" ? error?.constructor?.name : "[not an object]"}"${msg ? `: ${msg}` : "."}`; + throw new AssertionError(msg); + } + if (msgIncludes && (!(error instanceof Error) || !stripColor(error.message).includes(stripColor(msgIncludes)))) { + msg = `Expected error message to include "${msgIncludes}", but got "${error instanceof Error ? error.message : "[not an Error]"}"${msg ? `: ${msg}` : "."}`; + throw new AssertionError(msg); + } +} +function assertThrows(fn, errorClassOrMsg, msgIncludesOrMsg, msg) { + let ErrorClass = undefined; + let msgIncludes = undefined; + let err; + if (typeof errorClassOrMsg !== "string") { + if (errorClassOrMsg === undefined || errorClassOrMsg.prototype instanceof Error || errorClassOrMsg.prototype === Error.prototype) { + ErrorClass = errorClassOrMsg; + msgIncludes = msgIncludesOrMsg; + } else { + msg = msgIncludesOrMsg; + } + } else { + msg = errorClassOrMsg; + } + let doesThrow = false; + const msgToAppendToError = msg ? `: ${msg}` : "."; + try { + fn(); + } catch (error) { + if (ErrorClass) { + if (error instanceof Error === false) { + throw new AssertionError("A non-Error object was thrown."); + } + assertIsError(error, ErrorClass, msgIncludes, msg); + } + err = error; + doesThrow = true; + } + if (!doesThrow) { + msg = `Expected function to throw${msgToAppendToError}`; + throw new AssertionError(msg); + } + return err; +} +async function assertRejects(fn, errorClassOrMsg, msgIncludesOrMsg, msg) { + let ErrorClass = undefined; + let msgIncludes = undefined; + let err; + if (typeof errorClassOrMsg !== "string") { + if (errorClassOrMsg === undefined || errorClassOrMsg.prototype instanceof Error || errorClassOrMsg.prototype === Error.prototype) { + ErrorClass = errorClassOrMsg; + msgIncludes = msgIncludesOrMsg; + } + } else { + msg = errorClassOrMsg; + } + let doesThrow = false; + let isPromiseReturned = false; + const msgToAppendToError = msg ? `: ${msg}` : "."; + try { + const possiblePromise = fn(); + if (possiblePromise && typeof possiblePromise === "object" && typeof possiblePromise.then === "function") { + isPromiseReturned = true; + await possiblePromise; + } + } catch (error) { + if (!isPromiseReturned) { + throw new AssertionError(`Function throws when expected to reject${msgToAppendToError}`); + } + if (ErrorClass) { + if (error instanceof Error === false) { + throw new AssertionError("A non-Error object was rejected."); + } + assertIsError(error, ErrorClass, msgIncludes, msg); + } + err = error; + doesThrow = true; + } + if (!doesThrow) { + throw new AssertionError(`Expected function to reject${msgToAppendToError}`); + } + return err; +} +function unimplemented(msg) { + throw new AssertionError(msg || "unimplemented"); +} +function unreachable() { + throw new AssertionError("unreachable"); +} +export { AssertionError as AssertionError }; +export { equal as equal }; +export { assert as assert }; +export { assertFalse as assertFalse }; +export { assertEquals as assertEquals }; +export { assertNotEquals as assertNotEquals }; +export { assertStrictEquals as assertStrictEquals }; +export { assertNotStrictEquals as assertNotStrictEquals }; +export { assertAlmostEquals as assertAlmostEquals }; +export { assertInstanceOf as assertInstanceOf }; +export { assertNotInstanceOf as assertNotInstanceOf }; +export { assertExists as assertExists }; +export { assertStringIncludes as assertStringIncludes }; +export { assertArrayIncludes as assertArrayIncludes }; +export { assertMatch as assertMatch }; +export { assertNotMatch as assertNotMatch }; +export { assertObjectMatch as assertObjectMatch }; +export { fail as fail }; +export { assertIsError as assertIsError }; +export { assertThrows as assertThrows }; +export { assertRejects as assertRejects }; +export { unimplemented as unimplemented }; +export { unreachable as unreachable }; + diff --git a/node_modules/tinycolor2/esm/package.json b/node_modules/tinycolor2/esm/package.json new file mode 100644 index 00000000..3dbc1ca5 --- /dev/null +++ b/node_modules/tinycolor2/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/tinycolor2/esm/test.js b/node_modules/tinycolor2/esm/test.js new file mode 100644 index 00000000..4f02b0ce --- /dev/null +++ b/node_modules/tinycolor2/esm/test.js @@ -0,0 +1,2189 @@ +// This file is autogenerated. +// Ideally it wouldn't exist, but it's here to test cjs in node +// Changes should go into ./test.js, and if new assertions are needed +// they'll need to be shimmed here as well +import tinycolor from "./tinycolor.js"; +import { Deno, testDefinitions } from "@deno/shim-deno-test"; +const { assertEquals, assert, assertThrows } = await import( + "../deno_asserts@0.168.0.mjs" +); +async function runDenoTests() { + for (const test of testDefinitions) { + if (test.ignore) { + console.log(`Ignoring ${test.name}`); + continue; + } + console.log(`Running ${test.name}`); + await test.fn(); + console.log(`> Passed ${test.name}`); + } +} + +// TEST_BEGINS_HERE + +Deno.test("TinyColor initialization", function () { + assert( + typeof tinycolor != "undefined", + "tinycolor is initialized on the page" + ); + assert( + typeof tinycolor("red") == "object", + "tinycolor is able to be instantiated" + ); + + var r = tinycolor("red"); + assert( + tinycolor(r) === r, + "when given a tinycolor instance, tinycolor() returns it" + ); + assert( + new tinycolor(r) === r, + "when given a tinycolor instance, new tinycolor() returns it" + ); + assertEquals( + tinycolor("red", { format: "hex" }).toString(), + "#ff0000", + "tinycolor options are being parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0 }, { format: "hex" }).toString(), + "#ff0000", + "tinycolor options are being parsed" + ); + + var obj = { h: 180, s: 0.5, l: 0.5 }; + var color = tinycolor(obj); + assert( + obj.s === 0.5, + "when given an object, the original object is not modified" + ); +}); + +Deno.test("Original input", function () { + var colorRgbUp = "RGB(39, 39, 39)"; + var colorRgbLow = "rgb(39, 39, 39)"; + var colorRgbMix = "RgB(39, 39, 39)"; + var tinycolorObj = tinycolor(colorRgbMix); + var inputObj = { r: 100, g: 100, b: 100 }; + var r = tinycolor("red"); + + assert( + tinycolor(colorRgbLow).getOriginalInput() === colorRgbLow, + "original lowercase input is returned" + ); + assert( + tinycolor(colorRgbUp).getOriginalInput() === colorRgbUp, + "original uppercase input is returned" + ); + assert( + tinycolor(colorRgbMix).getOriginalInput() === colorRgbMix, + "original mixed input is returned" + ); + assert( + tinycolor(tinycolorObj).getOriginalInput() === colorRgbMix, + "when given a tinycolor instance, the color string is returned" + ); + assert( + tinycolor(inputObj).getOriginalInput() === inputObj, + "when given an object, the object is returned" + ); + assert( + new tinycolor("").getOriginalInput() === "", + "when given an empty string, an empty string is returned" + ); + assert( + new tinycolor(null).getOriginalInput() === "", + "when given a null value, an empty string is returned" + ); +}); + +Deno.test("Cloning color", function () { + var originalColor = tinycolor("red"); + var originalColorRgbString = originalColor.toRgbString(); + + var clonedColor = originalColor.clone(); + assert( + clonedColor.toRgbString() === originalColor.toRgbString(), + "cloned color is identical" + ); + + clonedColor.setAlpha(0.5); + assert( + clonedColor.toRgbString() !== originalColor.toRgbString(), + "cloned color is changing independently from original color" + ); + assert( + originalColorRgbString === originalColor.toRgbString(), + "original color was not changed by cloned color change" + ); +}); +Deno.test("Random color", function () { + var randomColor = tinycolor.random(); + assertEquals(randomColor.getAlpha(), 1); + assertEquals(randomColor.getFormat(), "prgb"); + + randomColor.setAlpha(0.5); + assertEquals(randomColor.toHex8String().slice(-2), "80"); +}); + +// Taken from convertWikipediaColors.html +var conversions = [ + { + hex: "#FFFFFF", + hex8: "#FFFFFFFF", + rgb: { r: "100.0%", g: "100.0%", b: "100.0%" }, + hsv: { h: "0", s: "0.000", v: "1.000" }, + hsl: { h: "0", s: "0.000", l: "1.000" }, + }, + { + hex: "#808080", + hex8: "#808080FF", + rgb: { r: "050.0%", g: "050.0%", b: "050.0%" }, + hsv: { h: "0", s: "0.000", v: "0.500" }, + hsl: { h: "0", s: "0.000", l: "0.500" }, + }, + { + hex: "#000000", + hex8: "#000000FF", + rgb: { r: "000.0%", g: "000.0%", b: "000.0%" }, + hsv: { h: "0", s: "0.000", v: "0.000" }, + hsl: { h: "0", s: "0.000", l: "0.000" }, + }, + { + hex: "#FF0000", + hex8: "#FF0000FF", + rgb: { r: "100.0%", g: "000.0%", b: "000.0%" }, + hsv: { h: "0.0", s: "1.000", v: "1.000" }, + hsl: { h: "0.0", s: "1.000", l: "0.500" }, + }, + { + hex: "#BFBF00", + hex8: "#BFBF00FF", + rgb: { r: "075.0%", g: "075.0%", b: "000.0%" }, + hsv: { h: "60.0", s: "1.000", v: "0.750" }, + hsl: { h: "60.0", s: "1.000", l: "0.375" }, + }, + { + hex: "#008000", + hex8: "#008000FF", + rgb: { r: "000.0%", g: "050.0%", b: "000.0%" }, + hsv: { h: "120.0", s: "1.000", v: "0.500" }, + hsl: { h: "120.0", s: "1.000", l: "0.250" }, + }, + { + hex: "#80FFFF", + hex8: "#80FFFFFF", + rgb: { r: "050.0%", g: "100.0%", b: "100.0%" }, + hsv: { h: "180.0", s: "0.500", v: "1.000" }, + hsl: { h: "180.0", s: "1.000", l: "0.750" }, + }, + { + hex: "#8080FF", + hex8: "#8080FFFF", + rgb: { r: "050.0%", g: "050.0%", b: "100.0%" }, + hsv: { h: "240.0", s: "0.500", v: "1.000" }, + hsl: { h: "240.0", s: "1.000", l: "0.750" }, + }, + { + hex: "#BF40BF", + hex8: "#BF40BFFF", + rgb: { r: "075.0%", g: "025.0%", b: "075.0%" }, + hsv: { h: "300.0", s: "0.667", v: "0.750" }, + hsl: { h: "300.0", s: "0.500", l: "0.500" }, + }, + { + hex: "#A0A424", + hex8: "#A0A424FF", + rgb: { r: "062.8%", g: "064.3%", b: "014.2%" }, + hsv: { h: "61.8", s: "0.779", v: "0.643" }, + hsl: { h: "61.8", s: "0.638", l: "0.393" }, + }, + { + hex: "#1EAC41", + hex8: "#1EAC41FF", + rgb: { r: "011.6%", g: "067.5%", b: "025.5%" }, + hsv: { h: "134.9", s: "0.828", v: "0.675" }, + hsl: { h: "134.9", s: "0.707", l: "0.396" }, + }, + { + hex: "#B430E5", + hex8: "#B430E5FF", + rgb: { r: "070.4%", g: "018.7%", b: "089.7%" }, + hsv: { h: "283.7", s: "0.792", v: "0.897" }, + hsl: { h: "283.7", s: "0.775", l: "0.542" }, + }, + { + hex: "#FEF888", + hex8: "#FEF888FF", + rgb: { r: "099.8%", g: "097.4%", b: "053.2%" }, + hsv: { h: "56.9", s: "0.467", v: "0.998" }, + hsl: { h: "56.9", s: "0.991", l: "0.765" }, + }, + { + hex: "#19CB97", + hex8: "#19CB97FF", + rgb: { r: "009.9%", g: "079.5%", b: "059.1%" }, + hsv: { h: "162.4", s: "0.875", v: "0.795" }, + hsl: { h: "162.4", s: "0.779", l: "0.447" }, + }, + { + hex: "#362698", + hex8: "#362698FF", + rgb: { r: "021.1%", g: "014.9%", b: "059.7%" }, + hsv: { h: "248.3", s: "0.750", v: "0.597" }, + hsl: { h: "248.3", s: "0.601", l: "0.373" }, + }, + { + hex: "#7E7EB8", + hex8: "#7E7EB8FF", + rgb: { r: "049.5%", g: "049.3%", b: "072.1%" }, + hsv: { h: "240.5", s: "0.316", v: "0.721" }, + hsl: { h: "240.5", s: "0.290", l: "0.607" }, + }, +]; + +Deno.test("Color Equality", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + + assert(true, tiny.isValid()); + assert( + true, + "Testing " + + c.hex + + ": " + + tiny.toRgbString() + + " " + + tiny.toPercentageRgbString() + + " " + + tiny.toHsvString() + + " " + + tiny.toHslString() + + " " + + tiny.toHexString() + + "Original: " + + JSON.stringify(c.rgb) + + " " + + JSON.stringify(c.hsv) + + " " + + JSON.stringify(c.hsl) + ); + assert(tinycolor.equals(c.rgb, c.hex), "RGB equals hex " + c.hex); + assert(tinycolor.equals(c.rgb, c.hex8), "RGB equals hex " + c.hex); + assert(tinycolor.equals(c.rgb, c.hsl), "RGB equals HSL " + c.hex); + assert(tinycolor.equals(c.rgb, c.hsv), "RGB equals HSV " + c.hex); + assert(tinycolor.equals(c.rgb, c.rgb), "RGB equals RGB " + c.hex); + + assert(tinycolor.equals(c.hex, c.hex), "hex equals hex " + c.hex); + assert(tinycolor.equals(c.hex, c.hex8), "hex equals hex8 " + c.hex); + assert(tinycolor.equals(c.hex, c.hsl), "hex equals HSL " + c.hex); + assert(tinycolor.equals(c.hex, c.hsv), "hex equals HSV " + c.hex); + + assert(tinycolor.equals(c.hsl, c.hsv), "HSL equals HSV " + c.hex); + } +}); + +Deno.test("With Ratio", function () { + assertEquals( + tinycolor.fromRatio({ r: 1, g: 1, b: 1 }).toHexString(), + "#ffffff", + "white" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 0.5 }).toRgbString(), + "rgba(255, 0, 0, 0.5)", + "alpha works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 1 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha = 1 works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 10 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha > 1 works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: -1 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha < 1 works when ratio is parsed" + ); +}); + +Deno.test("Without Ratio", function () { + assertEquals( + tinycolor({ r: 1, g: 1, b: 1 }).toHexString(), + "#010101", + "010101" + ); + assertEquals( + tinycolor({ r: 0.1, g: 0.1, b: 0.1 }).toHexString(), + "#000000", + "000000" + ); + assertEquals(tinycolor("rgb .1 .1 .1").toHexString(), "#000000", "000000"); +}); + +Deno.test("RGB Text Parsing", function () { + assertEquals( + tinycolor("rgb 255 0 0").toHexString(), + "#ff0000", + "spaced input" + ); + assertEquals( + tinycolor("rgb(255, 0, 0)").toHexString(), + "#ff0000", + "parenthesized input" + ); + assertEquals( + tinycolor("rgb (255, 0, 0)").toHexString(), + "#ff0000", + "parenthesized spaced input" + ); + assertEquals( + tinycolor({ r: 255, g: 0, b: 0 }).toHexString(), + "#ff0000", + "object input" + ); + assertEquals( + tinycolor({ r: 255, g: 0, b: 0 }).toRgb(), + { + r: 255, + g: 0, + b: 0, + a: 1, + }, + "object input and compare" + ); + + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb(200, 100, 0)")); + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); + assert( + tinycolor.equals({ r: 200, g: 100, b: 0, a: 0.4 }, "rgba 200 100 0 .4") + ); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgba 200 100 0 1")); + + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb(200, 100, 0)")); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); + + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb(200, 100, 0)") + ); + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") + ); + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") + ); +}); + +Deno.test("Percentage RGB Text Parsing", function () { + assertEquals( + tinycolor("rgb 100% 0% 0%").toHexString(), + "#ff0000", + "spaced input" + ); + assertEquals( + tinycolor("rgb(100%, 0%, 0%)").toHexString(), + "#ff0000", + "parenthesized input" + ); + assertEquals( + tinycolor("rgb (100%, 0%, 0%)").toHexString(), + "#ff0000", + "parenthesized spaced input" + ); + assertEquals( + tinycolor({ r: "100%", g: "0%", b: "0%" }).toHexString(), + "#ff0000", + "object input" + ); + assertEquals( + tinycolor({ r: "100%", g: "0%", b: "0%" }).toRgb(), + { + r: 255, + g: 0, + b: 0, + a: 1, + }, + "object input and compare" + ); + + assert( + tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") + ); + assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert( + tinycolor.equals( + { r: "90%", g: "45%", b: "0%", a: 0.4 }, + "rgba 90% 45% 0% .4" + ) + ); + assert( + !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgba 90% 45% 0% 1") + ); + + assert( + !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") + ); + assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb(90%, 45%, 0%)" + ) + ); + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb 90% 45% 0%" + ) + ); + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb 90% 45% 0%" + ) + ); +}); + +Deno.test("HSL parsing", function () { + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toHexString(), + "#2400c2", + "to hex" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toRgbString(), + "rgb(36, 0, 194)", + "to rgb" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toHslString(), + "hsl(251, 100%, 38%)", + "to hsl" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38, a: 0.5 }).toHslString(), + "hsla(251, 100%, 38%, 0.5)", + "to hsla" + ); + assertEquals( + tinycolor("hsl(251, 100, 38)").toHexString(), + "#2400c2", + "to hex" + ); + assertEquals( + tinycolor("hsl(251, 100%, 38%)").toRgbString(), + "rgb(36, 0, 194)", + "to rgb" + ); + assertEquals( + tinycolor("hsl(251, 100%, 38%)").toHslString(), + "hsl(251, 100%, 38%)", + "to hsl" + ); + assertEquals( + tinycolor("hsl 100 20 10").toHslString(), + "hsl(100, 20%, 10%)", + "problematic hsl" + ); +}); + +Deno.test("Hex Parsing", function () { + assertEquals(tinycolor("rgb 255 0 0").toHexString(), "#ff0000"); + assertEquals(tinycolor("rgb 255 0 0").toHexString(true), "#f00"); + + assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8String(), "#ff000080"); + assertEquals(tinycolor("rgba 255 0 0 0").toHex8String(), "#ff000000"); + assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(), "#ff0000ff"); + assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(true), "#f00f"); + + assertEquals(tinycolor("rgb 255 0 0").toHex(), "ff0000"); + assertEquals(tinycolor("rgb 255 0 0").toHex(true), "f00"); + assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8(), "ff000080"); +}); + +Deno.test("HSV Parsing", function () { + assertEquals( + tinycolor("hsv 251.1 0.887 .918").toHsvString(), + "hsv(251, 89%, 92%)" + ); + assertEquals( + tinycolor("hsv 251.1 0.887 0.918").toHsvString(), + "hsv(251, 89%, 92%)" + ); + assertEquals( + tinycolor("hsva 251.1 0.887 0.918 0.5").toHsvString(), + "hsva(251, 89%, 92%, 0.5)" + ); +}); + +Deno.test("Invalid Parsing", function () { + var invalidColor = tinycolor("this is not a color"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor("#red"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor(" #red"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor("##123456"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor(" ##123456"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ r: "invalid", g: "invalid", b: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ h: "invalid", s: "invalid", l: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ h: "invalid", s: "invalid", v: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); +}); + +Deno.test("Named colors", function () { + assertEquals(tinycolor("aliceblue").toHex(), "f0f8ff"); + assertEquals(tinycolor("antiquewhite").toHex(), "faebd7"); + assertEquals(tinycolor("aqua").toHex(), "00ffff"); + assertEquals(tinycolor("aquamarine").toHex(), "7fffd4"); + assertEquals(tinycolor("azure").toHex(), "f0ffff"); + assertEquals(tinycolor("beige").toHex(), "f5f5dc"); + assertEquals(tinycolor("bisque").toHex(), "ffe4c4"); + assertEquals(tinycolor("black").toHex(), "000000"); + assertEquals(tinycolor("blanchedalmond").toHex(), "ffebcd"); + assertEquals(tinycolor("blue").toHex(), "0000ff"); + assertEquals(tinycolor("blueviolet").toHex(), "8a2be2"); + assertEquals(tinycolor("brown").toHex(), "a52a2a"); + assertEquals(tinycolor("burlywood").toHex(), "deb887"); + assertEquals(tinycolor("cadetblue").toHex(), "5f9ea0"); + assertEquals(tinycolor("chartreuse").toHex(), "7fff00"); + assertEquals(tinycolor("chocolate").toHex(), "d2691e"); + assertEquals(tinycolor("coral").toHex(), "ff7f50"); + assertEquals(tinycolor("cornflowerblue").toHex(), "6495ed"); + assertEquals(tinycolor("cornsilk").toHex(), "fff8dc"); + assertEquals(tinycolor("crimson").toHex(), "dc143c"); + assertEquals(tinycolor("cyan").toHex(), "00ffff"); + assertEquals(tinycolor("darkblue").toHex(), "00008b"); + assertEquals(tinycolor("darkcyan").toHex(), "008b8b"); + assertEquals(tinycolor("darkgoldenrod").toHex(), "b8860b"); + assertEquals(tinycolor("darkgray").toHex(), "a9a9a9"); + assertEquals(tinycolor("darkgreen").toHex(), "006400"); + assertEquals(tinycolor("darkkhaki").toHex(), "bdb76b"); + assertEquals(tinycolor("darkmagenta").toHex(), "8b008b"); + assertEquals(tinycolor("darkolivegreen").toHex(), "556b2f"); + assertEquals(tinycolor("darkorange").toHex(), "ff8c00"); + assertEquals(tinycolor("darkorchid").toHex(), "9932cc"); + assertEquals(tinycolor("darkred").toHex(), "8b0000"); + assertEquals(tinycolor("darksalmon").toHex(), "e9967a"); + assertEquals(tinycolor("darkseagreen").toHex(), "8fbc8f"); + assertEquals(tinycolor("darkslateblue").toHex(), "483d8b"); + assertEquals(tinycolor("darkslategray").toHex(), "2f4f4f"); + assertEquals(tinycolor("darkturquoise").toHex(), "00ced1"); + assertEquals(tinycolor("darkviolet").toHex(), "9400d3"); + assertEquals(tinycolor("deeppink").toHex(), "ff1493"); + assertEquals(tinycolor("deepskyblue").toHex(), "00bfff"); + assertEquals(tinycolor("dimgray").toHex(), "696969"); + assertEquals(tinycolor("dodgerblue").toHex(), "1e90ff"); + assertEquals(tinycolor("firebrick").toHex(), "b22222"); + assertEquals(tinycolor("floralwhite").toHex(), "fffaf0"); + assertEquals(tinycolor("forestgreen").toHex(), "228b22"); + assertEquals(tinycolor("fuchsia").toHex(), "ff00ff"); + assertEquals(tinycolor("gainsboro").toHex(), "dcdcdc"); + assertEquals(tinycolor("ghostwhite").toHex(), "f8f8ff"); + assertEquals(tinycolor("gold").toHex(), "ffd700"); + assertEquals(tinycolor("goldenrod").toHex(), "daa520"); + assertEquals(tinycolor("gray").toHex(), "808080"); + assertEquals(tinycolor("grey").toHex(), "808080"); + assertEquals(tinycolor("green").toHex(), "008000"); + assertEquals(tinycolor("greenyellow").toHex(), "adff2f"); + assertEquals(tinycolor("honeydew").toHex(), "f0fff0"); + assertEquals(tinycolor("hotpink").toHex(), "ff69b4"); + assertEquals(tinycolor("indianred ").toHex(), "cd5c5c"); + assertEquals(tinycolor("indigo ").toHex(), "4b0082"); + assertEquals(tinycolor("ivory").toHex(), "fffff0"); + assertEquals(tinycolor("khaki").toHex(), "f0e68c"); + assertEquals(tinycolor("lavender").toHex(), "e6e6fa"); + assertEquals(tinycolor("lavenderblush").toHex(), "fff0f5"); + assertEquals(tinycolor("lawngreen").toHex(), "7cfc00"); + assertEquals(tinycolor("lemonchiffon").toHex(), "fffacd"); + assertEquals(tinycolor("lightblue").toHex(), "add8e6"); + assertEquals(tinycolor("lightcoral").toHex(), "f08080"); + assertEquals(tinycolor("lightcyan").toHex(), "e0ffff"); + assertEquals(tinycolor("lightgoldenrodyellow").toHex(), "fafad2"); + assertEquals(tinycolor("lightgrey").toHex(), "d3d3d3"); + assertEquals(tinycolor("lightgreen").toHex(), "90ee90"); + assertEquals(tinycolor("lightpink").toHex(), "ffb6c1"); + assertEquals(tinycolor("lightsalmon").toHex(), "ffa07a"); + assertEquals(tinycolor("lightseagreen").toHex(), "20b2aa"); + assertEquals(tinycolor("lightskyblue").toHex(), "87cefa"); + assertEquals(tinycolor("lightslategray").toHex(), "778899"); + assertEquals(tinycolor("lightsteelblue").toHex(), "b0c4de"); + assertEquals(tinycolor("lightyellow").toHex(), "ffffe0"); + assertEquals(tinycolor("lime").toHex(), "00ff00"); + assertEquals(tinycolor("limegreen").toHex(), "32cd32"); + assertEquals(tinycolor("linen").toHex(), "faf0e6"); + assertEquals(tinycolor("magenta").toHex(), "ff00ff"); + assertEquals(tinycolor("maroon").toHex(), "800000"); + assertEquals(tinycolor("mediumaquamarine").toHex(), "66cdaa"); + assertEquals(tinycolor("mediumblue").toHex(), "0000cd"); + assertEquals(tinycolor("mediumorchid").toHex(), "ba55d3"); + assertEquals(tinycolor("mediumpurple").toHex(), "9370db"); + assertEquals(tinycolor("mediumseagreen").toHex(), "3cb371"); + assertEquals(tinycolor("mediumslateblue").toHex(), "7b68ee"); + assertEquals(tinycolor("mediumspringgreen").toHex(), "00fa9a"); + assertEquals(tinycolor("mediumturquoise").toHex(), "48d1cc"); + assertEquals(tinycolor("mediumvioletred").toHex(), "c71585"); + assertEquals(tinycolor("midnightblue").toHex(), "191970"); + assertEquals(tinycolor("mintcream").toHex(), "f5fffa"); + assertEquals(tinycolor("mistyrose").toHex(), "ffe4e1"); + assertEquals(tinycolor("moccasin").toHex(), "ffe4b5"); + assertEquals(tinycolor("navajowhite").toHex(), "ffdead"); + assertEquals(tinycolor("navy").toHex(), "000080"); + assertEquals(tinycolor("oldlace").toHex(), "fdf5e6"); + assertEquals(tinycolor("olive").toHex(), "808000"); + assertEquals(tinycolor("olivedrab").toHex(), "6b8e23"); + assertEquals(tinycolor("orange").toHex(), "ffa500"); + assertEquals(tinycolor("orangered").toHex(), "ff4500"); + assertEquals(tinycolor("orchid").toHex(), "da70d6"); + assertEquals(tinycolor("palegoldenrod").toHex(), "eee8aa"); + assertEquals(tinycolor("palegreen").toHex(), "98fb98"); + assertEquals(tinycolor("paleturquoise").toHex(), "afeeee"); + assertEquals(tinycolor("palevioletred").toHex(), "db7093"); + assertEquals(tinycolor("papayawhip").toHex(), "ffefd5"); + assertEquals(tinycolor("peachpuff").toHex(), "ffdab9"); + assertEquals(tinycolor("peru").toHex(), "cd853f"); + assertEquals(tinycolor("pink").toHex(), "ffc0cb"); + assertEquals(tinycolor("plum").toHex(), "dda0dd"); + assertEquals(tinycolor("powderblue").toHex(), "b0e0e6"); + assertEquals(tinycolor("purple").toHex(), "800080"); + assertEquals(tinycolor("rebeccapurple").toHex(), "663399"); + assertEquals(tinycolor("red").toHex(), "ff0000"); + assertEquals(tinycolor("rosybrown").toHex(), "bc8f8f"); + assertEquals(tinycolor("royalblue").toHex(), "4169e1"); + assertEquals(tinycolor("saddlebrown").toHex(), "8b4513"); + assertEquals(tinycolor("salmon").toHex(), "fa8072"); + assertEquals(tinycolor("sandybrown").toHex(), "f4a460"); + assertEquals(tinycolor("seagreen").toHex(), "2e8b57"); + assertEquals(tinycolor("seashell").toHex(), "fff5ee"); + assertEquals(tinycolor("sienna").toHex(), "a0522d"); + assertEquals(tinycolor("silver").toHex(), "c0c0c0"); + assertEquals(tinycolor("skyblue").toHex(), "87ceeb"); + assertEquals(tinycolor("slateblue").toHex(), "6a5acd"); + assertEquals(tinycolor("slategray").toHex(), "708090"); + assertEquals(tinycolor("snow").toHex(), "fffafa"); + assertEquals(tinycolor("springgreen").toHex(), "00ff7f"); + assertEquals(tinycolor("steelblue").toHex(), "4682b4"); + assertEquals(tinycolor("tan").toHex(), "d2b48c"); + assertEquals(tinycolor("teal").toHex(), "008080"); + assertEquals(tinycolor("thistle").toHex(), "d8bfd8"); + assertEquals(tinycolor("tomato").toHex(), "ff6347"); + assertEquals(tinycolor("turquoise").toHex(), "40e0d0"); + assertEquals(tinycolor("violet").toHex(), "ee82ee"); + assertEquals(tinycolor("wheat").toHex(), "f5deb3"); + assertEquals(tinycolor("white").toHex(), "ffffff"); + assertEquals(tinycolor("whitesmoke").toHex(), "f5f5f5"); + assertEquals(tinycolor("yellow").toHex(), "ffff00"); + assertEquals(tinycolor("yellowgreen").toHex(), "9acd32"); + + assertEquals(tinycolor("#f00").toName(), "red"); + assertEquals(tinycolor("#fa0a0a").toName(), false); +}); + +Deno.test("Invalid alpha should normalize to 1", function () { + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: -1 }).toRgbString(), + "rgb(255, 20, 10)", + "Negative value" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: -0 }).toRgbString(), + "rgba(255, 20, 10, 0)", + "Negative 0" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toRgbString(), + "rgba(255, 20, 10, 0)", + "0" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0.5 }).toRgbString(), + "rgba(255, 20, 10, 0.5)", + ".5" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 1 }).toRgbString(), + "rgb(255, 20, 10)", + "1" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 100 }).toRgbString(), + "rgb(255, 20, 10)", + "Greater than 1" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: "asdfasd" }).toRgbString(), + "rgb(255, 20, 10)", + "Non Numeric" + ); + + assertEquals( + tinycolor("#fff").toRgbString(), + "rgb(255, 255, 255)", + "Hex should be 1" + ); + assertEquals( + tinycolor("rgba 255 0 0 100").toRgbString(), + "rgb(255, 0, 0)", + "Greater than 1 in string parsing" + ); +}); + +Deno.test("toString() with alpha set", function () { + var redNamed = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0.6 }, + { + format: "name", + } + ); + var transparentNamed = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0 }, + { + format: "name", + } + ); + var redHex = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0.4 }, + { + format: "hex", + } + ); + + assertEquals(redNamed.getFormat(), "name", "getFormat() is correct"); + assertEquals(redHex.getFormat(), "hex", "getFormat() is correct"); + + assertEquals( + redNamed.toString(), + "rgba(255, 0, 0, 0.6)", + "Names should default to rgba if alpha is < 1" + ); + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0.4)", + "Hex should default to rgba if alpha is < 1" + ); + + assertEquals( + redNamed.toString("hex"), + "#ff0000", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex6"), + "#ff0000", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex3"), + "#f00", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex8"), + "#ff000099", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex4"), + "#f009", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("name"), + "#ff0000", + "Semi transparent names should return hex in toString() if name format is specified" + ); + + assertEquals( + redNamed.toName(), + false, + "Semi transparent names should be false in toName()" + ); + + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0.4)", + "Hex should default to rgba if alpha is < 1" + ); + assertEquals( + transparentNamed.toString(), + "transparent", + "Named color should equal transparent if alpha == 0" + ); + + redHex.setAlpha(0); + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0)", + "Hex should default to rgba if alpha is = 0" + ); +}); + +Deno.test("setting alpha", function () { + var hexSetter = tinycolor("rgba(255, 0, 0, 1)"); + assertEquals(hexSetter.getAlpha(), 1, "Alpha should start as 1"); + var returnedFromSetAlpha = hexSetter.setAlpha(0.9); + assertEquals( + returnedFromSetAlpha, + hexSetter, + "setAlpha return value should be the color." + ); + assertEquals(hexSetter.getAlpha(), 0.9, "setAlpha should change alpha value"); + hexSetter.setAlpha(0.5); + assertEquals(hexSetter.getAlpha(), 0.5, "setAlpha should change alpha value"); + hexSetter.setAlpha(0); + assertEquals(hexSetter.getAlpha(), 0, "setAlpha should change alpha value"); + hexSetter.setAlpha(-1); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with value < 0 should be bound to 1" + ); + hexSetter.setAlpha(2); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with value > 1 should be bound to 1" + ); + hexSetter.setAlpha(); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); + hexSetter.setAlpha(null); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); + hexSetter.setAlpha("test"); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); +}); + +Deno.test("Alpha = 0 should act differently on toName()", function () { + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toName(), + "transparent", + "0" + ); + assertEquals( + tinycolor("transparent").toString(), + "transparent", + "toString when passed" + ); + assertEquals(tinycolor("transparent").toHex(), "000000", "toHex"); +}); + +Deno.test("getBrightness", function () { + assertEquals(tinycolor("#000").getBrightness(), 0, "returns 0 for #000"); + assertEquals(tinycolor("#fff").getBrightness(), 255, "returns 255 for #fff"); +}); + +Deno.test("getLuminance", function () { + assertEquals(tinycolor("#000").getLuminance(), 0, "returns 0 for #000"); + assertEquals(tinycolor("#fff").getLuminance(), 1, "returns 1 for #fff"); +}); + +Deno.test("isDark returns true/false for dark/light colors", function () { + assertEquals(tinycolor("#000").isDark(), true, "#000 is dark"); + assertEquals(tinycolor("#111").isDark(), true, "#111 is dark"); + assertEquals(tinycolor("#222").isDark(), true, "#222 is dark"); + assertEquals(tinycolor("#333").isDark(), true, "#333 is dark"); + assertEquals(tinycolor("#444").isDark(), true, "#444 is dark"); + assertEquals(tinycolor("#555").isDark(), true, "#555 is dark"); + assertEquals(tinycolor("#666").isDark(), true, "#666 is dark"); + assertEquals(tinycolor("#777").isDark(), true, "#777 is dark"); + assertEquals(tinycolor("#888").isDark(), false, "#888 is not dark"); + assertEquals(tinycolor("#999").isDark(), false, "#999 is not dark"); + assertEquals(tinycolor("#aaa").isDark(), false, "#aaa is not dark"); + assertEquals(tinycolor("#bbb").isDark(), false, "#bbb is not dark"); + assertEquals(tinycolor("#ccc").isDark(), false, "#ccc is not dark"); + assertEquals(tinycolor("#ddd").isDark(), false, "#ddd is not dark"); + assertEquals(tinycolor("#eee").isDark(), false, "#eee is not dark"); + assertEquals(tinycolor("#fff").isDark(), false, "#fff is not dark"); +}); + +Deno.test("isLight returns true/false for light/dark colors", function () { + assertEquals(tinycolor("#000").isLight(), false, "#000 is not light"); + assertEquals(tinycolor("#111").isLight(), false, "#111 is not light"); + assertEquals(tinycolor("#222").isLight(), false, "#222 is not light"); + assertEquals(tinycolor("#333").isLight(), false, "#333 is not light"); + assertEquals(tinycolor("#444").isLight(), false, "#444 is not light"); + assertEquals(tinycolor("#555").isLight(), false, "#555 is not light"); + assertEquals(tinycolor("#666").isLight(), false, "#666 is not light"); + assertEquals(tinycolor("#777").isLight(), false, "#777 is not light"); + assertEquals(tinycolor("#888").isLight(), true, "#888 is light"); + assertEquals(tinycolor("#999").isLight(), true, "#999 is light"); + assertEquals(tinycolor("#aaa").isLight(), true, "#aaa is light"); + assertEquals(tinycolor("#bbb").isLight(), true, "#bbb is light"); + assertEquals(tinycolor("#ccc").isLight(), true, "#ccc is light"); + assertEquals(tinycolor("#ddd").isLight(), true, "#ddd is light"); + assertEquals(tinycolor("#eee").isLight(), true, "#eee is light"); + assertEquals(tinycolor("#fff").isLight(), true, "#fff is light"); +}); + +Deno.test("HSL Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toHsl()).toHexString(), + "HSL Object" + ); + } +}); + +Deno.test("HSL String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toHslString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "toHslString red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "toHslString green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "toHslString blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("HSV String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toHsvString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "toHsvString red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "toHsvString green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "toHsvString blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("HSV Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toHsv()).toHexString(), + "HSV Object" + ); + } +}); + +Deno.test("RGB Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toRgb()).toHexString(), + "RGB Object" + ); + } +}); + +Deno.test("RGB String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toRgbString()).toHexString(), + "RGB String" + ); + } +}); + +Deno.test("PRGB Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toPercentageRgb()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "Red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "Green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "Blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("PRGB String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toPercentageRgbString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "Red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "Green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "Blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals(tiny.toHexString(), tinycolor(tiny).toHexString(), "Object"); + } +}); + +Deno.test("Color equality", function () { + assert(tinycolor.equals("#ff0000", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#ff0000", "rgb(255, 0, 0)"), "Same alphas"); + assert( + !tinycolor.equals("#ff0000", "rgba(255, 0, 0, .1)"), + "Different alphas" + ); + assert(tinycolor.equals("#ff000066", "rgba(255, 0, 0, .4)"), "Same alphas"); + assert(tinycolor.equals("#f009", "rgba(255, 0, 0, .6)"), "Same alphas"); + assert(tinycolor.equals("#336699CC", "369C"), "Same hex"); + assert(tinycolor.equals("ff0000", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); + assert(tinycolor.equals("f00", "#ff0000"), "Same hex"); + assertEquals(tinycolor("010101").toHexString(), "#010101"); + assert(!tinycolor.equals("#ff0000", "#00ff00"), "Different hex"); + assert( + tinycolor.equals("#ff8000", "rgb(100%, 50%, 0%)"), + "Percentage bounds checking" + ); +}); + +Deno.test("isReadable", function () { + // "#ff0088", "#8822aa" (values used in old WCAG1 tests) + assert( + tinycolor.isReadable("#000000", "#ffffff", { level: "AA", size: "small" }), + "white/black is readable" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", {}), + "not readable - empty wcag2 object" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "small" }), + "not readable - AA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "large" }), + "not readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { + level: "AAA", + size: "large", + }), + "not readable - AAA large" + ); + + // values derived from and validated using the calculators at http://www.dasplankton.de/ContrastA/ + // and http://webaim.org/resources/contrastchecker/ + + // "#ff0088", "#5c1a72": contrast ratio 3.04 + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "small" }), + "not readable - AA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { + level: "AAA", + size: "large", + }), + "not readable - AAA large" + ); + + // "#ff0088", "#2e0c3a": contrast ratio 4.56 + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "small" }), + "readable - AA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#2e0c3a", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AAA", size: "large" }), + "readable - AAA large" + ); + + // "#db91b8", "#2e0c3a": contrast ratio 7.12 + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "small" }), + "readable - AA small" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "small" }), + "readable - AAA small" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "large" }), + "readable - AAA large" + ); +}); + +Deno.test("readability", function () { + // check return values from readability function. See isReadable above for standards tests. + assertEquals( + tinycolor.readability("#000", "#000"), + 1, + "Readability function test 0" + ); + assertEquals( + tinycolor.readability("#000", "#111"), + 1.1121078324840545, + "Readability function test 1" + ); + assertEquals( + tinycolor.readability("#000", "#fff"), + 21, + "Readability function test 2" + ); +}); + +Deno.test("mostReadable", function () { + assertEquals( + tinycolor + .mostReadable("#000", ["#111", "#222", { wcag2: {} }]) + .toHexString(), + "#222222", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#f00", ["#d00", "#0d0"], { wcag2: {} }) + .toHexString(), + "#00dd00", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#fff", ["#fff", "#fff"], { wcag2: {} }) + .toHexString(), + "#ffffff", + "no different color in list" + ); + //includeFallbackColors + assertEquals( + tinycolor + .mostReadable("#fff", ["#fff", "#fff"], { + includeFallbackColors: true, + }) + .toHexString(), + "#000000", + "no different color in list" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#124", "#125"], { + includeFallbackColors: false, + }) + .toHexString(), + "#112255", + "no readable color in list" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#ffffff", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#124", "#125"], { + includeFallbackColors: true, + }) + .toHexString(), + "#ffffff", + "no readable color in list" + ); + + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#000000", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#2e0c3a"], { + includeFallbackColors: true, + level: "AAA", + size: "large", + }) + .toHexString(), + "#2e0c3a", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#2e0c3a"], { + includeFallbackColors: true, + level: "AAA", + size: "small", + }) + .toHexString(), + "#000000", + "no readable color in list" + ); + + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#ffffff", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#a9acb6"], { + includeFallbackColors: true, + level: "AAA", + size: "large", + }) + .toHexString(), + "#a9acb6", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#a9acb6"], { + includeFallbackColors: true, + level: "AAA", + size: "small", + }) + .toHexString(), + "#ffffff", + "no readable color in list" + ); +}); + +Deno.test("Filters", function () { + assertEquals( + tinycolor("red").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" + ); + assertEquals( + tinycolor("red").toFilter("blue"), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ff0000ff)" + ); + + assertEquals( + tinycolor("transparent").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#00000000)" + ); + assertEquals( + tinycolor("transparent").toFilter("red"), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#ffff0000)" + ); + + assertEquals( + tinycolor("#f0f0f0dd").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ddf0f0f0,endColorstr=#ddf0f0f0)" + ); + assertEquals( + tinycolor("rgba(0, 0, 255, .5").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#800000ff,endColorstr=#800000ff)" + ); +}); + +/* Originally generated with: +var results = []; +for (var i = 0; i <= 100; i++) results.push( tinycolor.saturate("red", i).toHex() ) +console.log(JSON.stringify(results)) +*/ +var DESATURATIONS = [ + "ff0000", + "fe0101", + "fc0303", + "fb0404", + "fa0505", + "f90606", + "f70808", + "f60909", + "f50a0a", + "f40b0b", + "f20d0d", + "f10e0e", + "f00f0f", + "ee1111", + "ed1212", + "ec1313", + "eb1414", + "e91616", + "e81717", + "e71818", + "e61919", + "e41b1b", + "e31c1c", + "e21d1d", + "e01f1f", + "df2020", + "de2121", + "dd2222", + "db2424", + "da2525", + "d92626", + "d72828", + "d62929", + "d52a2a", + "d42b2b", + "d22d2d", + "d12e2e", + "d02f2f", + "cf3030", + "cd3232", + "cc3333", + "cb3434", + "c93636", + "c83737", + "c73838", + "c63939", + "c43b3b", + "c33c3c", + "c23d3d", + "c13e3e", + "bf4040", + "be4141", + "bd4242", + "bb4444", + "ba4545", + "b94646", + "b84747", + "b64949", + "b54a4a", + "b44b4b", + "b34d4d", + "b14e4e", + "b04f4f", + "af5050", + "ad5252", + "ac5353", + "ab5454", + "aa5555", + "a85757", + "a75858", + "a65959", + "a45b5b", + "a35c5c", + "a25d5d", + "a15e5e", + "9f6060", + "9e6161", + "9d6262", + "9c6363", + "9a6565", + "996666", + "986767", + "966969", + "956a6a", + "946b6b", + "936c6c", + "916e6e", + "906f6f", + "8f7070", + "8e7171", + "8c7373", + "8b7474", + "8a7575", + "887777", + "877878", + "867979", + "857a7a", + "837c7c", + "827d7d", + "817e7e", + "808080", +]; +var SATURATIONS = [ + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", +]; +var LIGHTENS = [ + "ff0000", + "ff0505", + "ff0a0a", + "ff0f0f", + "ff1414", + "ff1a1a", + "ff1f1f", + "ff2424", + "ff2929", + "ff2e2e", + "ff3333", + "ff3838", + "ff3d3d", + "ff4242", + "ff4747", + "ff4d4d", + "ff5252", + "ff5757", + "ff5c5c", + "ff6161", + "ff6666", + "ff6b6b", + "ff7070", + "ff7575", + "ff7a7a", + "ff8080", + "ff8585", + "ff8a8a", + "ff8f8f", + "ff9494", + "ff9999", + "ff9e9e", + "ffa3a3", + "ffa8a8", + "ffadad", + "ffb3b3", + "ffb8b8", + "ffbdbd", + "ffc2c2", + "ffc7c7", + "ffcccc", + "ffd1d1", + "ffd6d6", + "ffdbdb", + "ffe0e0", + "ffe5e5", + "ffebeb", + "fff0f0", + "fff5f5", + "fffafa", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", +]; +var BRIGHTENS = [ + "ff0000", + "ff0303", + "ff0505", + "ff0808", + "ff0a0a", + "ff0d0d", + "ff0f0f", + "ff1212", + "ff1414", + "ff1717", + "ff1919", + "ff1c1c", + "ff1f1f", + "ff2121", + "ff2424", + "ff2626", + "ff2929", + "ff2b2b", + "ff2e2e", + "ff3030", + "ff3333", + "ff3636", + "ff3838", + "ff3b3b", + "ff3d3d", + "ff4040", + "ff4242", + "ff4545", + "ff4747", + "ff4a4a", + "ff4c4c", + "ff4f4f", + "ff5252", + "ff5454", + "ff5757", + "ff5959", + "ff5c5c", + "ff5e5e", + "ff6161", + "ff6363", + "ff6666", + "ff6969", + "ff6b6b", + "ff6e6e", + "ff7070", + "ff7373", + "ff7575", + "ff7878", + "ff7a7a", + "ff7d7d", + "ff7f7f", + "ff8282", + "ff8585", + "ff8787", + "ff8a8a", + "ff8c8c", + "ff8f8f", + "ff9191", + "ff9494", + "ff9696", + "ff9999", + "ff9c9c", + "ff9e9e", + "ffa1a1", + "ffa3a3", + "ffa6a6", + "ffa8a8", + "ffabab", + "ffadad", + "ffb0b0", + "ffb2b2", + "ffb5b5", + "ffb8b8", + "ffbaba", + "ffbdbd", + "ffbfbf", + "ffc2c2", + "ffc4c4", + "ffc7c7", + "ffc9c9", + "ffcccc", + "ffcfcf", + "ffd1d1", + "ffd4d4", + "ffd6d6", + "ffd9d9", + "ffdbdb", + "ffdede", + "ffe0e0", + "ffe3e3", + "ffe5e5", + "ffe8e8", + "ffebeb", + "ffeded", + "fff0f0", + "fff2f2", + "fff5f5", + "fff7f7", + "fffafa", + "fffcfc", + "ffffff", +]; +var DARKENS = [ + "ff0000", + "fa0000", + "f50000", + "f00000", + "eb0000", + "e60000", + "e00000", + "db0000", + "d60000", + "d10000", + "cc0000", + "c70000", + "c20000", + "bd0000", + "b80000", + "b30000", + "ad0000", + "a80000", + "a30000", + "9e0000", + "990000", + "940000", + "8f0000", + "8a0000", + "850000", + "800000", + "7a0000", + "750000", + "700000", + "6b0000", + "660000", + "610000", + "5c0000", + "570000", + "520000", + "4d0000", + "470000", + "420000", + "3d0000", + "380000", + "330000", + "2e0000", + "290000", + "240000", + "1f0000", + "190000", + "140000", + "0f0000", + "0a0000", + "050000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", +]; + +Deno.test("Modifications", function () { + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").desaturate(i).toHex(), + DESATURATIONS[i], + "Desaturation " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").saturate(i).toHex(), + SATURATIONS[i], + "Saturation " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").lighten(i).toHex(), + LIGHTENS[i], + "Lighten " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").brighten(i).toHex(), + BRIGHTENS[i], + "Brighter " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").darken(i).toHex(), + DARKENS[i], + "Darken " + i + " works" + ); + } + + assertEquals( + tinycolor("red").greyscale().toHex(), + "808080", + "Greyscale works" + ); +}); + +Deno.test("Spin", function () { + assertEquals( + Math.round(tinycolor("#f00").spin(-1234).toHsl().h), + 206, + "Spinning -1234 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(-360).toHsl().h), + 0, + "Spinning -360 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(-120).toHsl().h), + 240, + "Spinning -120 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(0).toHsl().h), + 0, + "Spinning 0 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(10).toHsl().h), + 10, + "Spinning 10 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(360).toHsl().h), + 0, + "Spinning 360 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(2345).toHsl().h), + 185, + "Spinning 2345 works" + ); + + [-360, 0, 360].forEach(function (delta) { + Object.keys(tinycolor.names).forEach(function (name) { + assertEquals( + tinycolor(name).toHex(), + tinycolor(name).spin(delta).toHex(), + "Spinning " + delta.toString() + " has no effect" + ); + }); + }); +}); + +Deno.test("Mix", function () { + // amount 0 or none + assertEquals( + tinycolor.mix("#000", "#fff").toHsl().l, + 0.5, + "Mixing without amount works" + ); + assertEquals( + tinycolor.mix("#f00", "#000", 0).toHex(), + "ff0000", + "Mixing with 0 amount works" + ); + // This case checks the the problem with floating point numbers (eg 255/90) + assertEquals( + tinycolor.mix("#fff", "#000", 90).toHex(), + "1a1a1a", + "Mixing with 90 amount works correctly" + ); + + // black and white + for (var i = 0; i < 100; i++) { + assertEquals( + Math.round(tinycolor.mix("#000", "#fff", i).toHsl().l * 100) / 100, + i / 100, + "Mixing black and white with " + i + " amount works" + ); + } + + // with colors + for (var i = 0; i < 100; i++) { + var new_hex = Math.round((255 * (100 - i)) / 100).toString(16); + + if (new_hex.length === 1) { + new_hex = "0" + new_hex; + } + + assertEquals( + tinycolor.mix("#f00", "#000", i).toHex(), + new_hex + "0000", + "Mixing " + i + " (red channel)" + ); + assertEquals( + tinycolor.mix("#0f0", "#000", i).toHex(), + "00" + new_hex + "00", + "Mixing " + i + " (green channel)" + ); + assertEquals( + tinycolor.mix("#00f", "#000", i).toHex(), + "0000" + new_hex, + "Mixing " + i + " (blue channel)" + ); + assertEquals( + tinycolor.mix(tinycolor("transparent"), "#000", i).toRgb().a, + i / 100, + "Mixing " + i + " (alpha channel)" + ); + } +}); + +// The combination tests need to be expanded furthe + +function colorsToHexString(colors) { + return colors + .map(function (c) { + return c.toHex(); + }) + .join(","); +} + +Deno.test("complement", function () { + var complementDoesntModifyInstance = tinycolor("red"); + assertEquals( + complementDoesntModifyInstance.complement().toHex(), + "00ffff", + "Complement works" + ); + assertEquals( + complementDoesntModifyInstance.toHex(), + "ff0000", + "Complement did not modify this color" + ); +}); + +Deno.test("analogous", function () { + var combination = tinycolor("red").analogous(); + assertEquals( + colorsToHexString(combination), + "ff0000,ff0066,ff0033,ff0000,ff3300,ff6600", + "Correct Combination" + ); +}); + +Deno.test("monochromatic", function () { + var combination = tinycolor("red").monochromatic(); + assertEquals( + colorsToHexString(combination), + "ff0000,2a0000,550000,800000,aa0000,d40000", + "Correct Combination" + ); +}); + +Deno.test("splitcomplement", function () { + var combination = tinycolor("red").splitcomplement(); + assertEquals( + colorsToHexString(combination), + "ff0000,ccff00,0066ff", + "Correct Combination" + ); +}); + +Deno.test("triad", function () { + var combination = tinycolor("red").triad(); + assertEquals( + colorsToHexString(combination), + "ff0000,00ff00,0000ff", + "Correct Combination" + ); +}); + +Deno.test("tetrad", function () { + var combination = tinycolor("red").tetrad(); + assertEquals( + colorsToHexString(combination), + "ff0000,80ff00,00ffff,7f00ff", + "Correct Combination" + ); +}); + +Deno.test({ + name: "polyad", + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + ignore: true, + fn: function () { + assertThrows(() => { + tinycolor("red").polyad(); + }); + assertThrows(() => { + tinycolor("red").polyad(-1); + }); + assertThrows(() => { + tinycolor("red").polyad("invalid"); + }); + assertEquals(colorsToHexString(tinycolor("red").polyad(1)), "ff0000"); + assertEquals(colorsToHexString(tinycolor("red").polyad("1")), "ff0000"); + assertEquals( + colorsToHexString(tinycolor("red").polyad(2)), + "ff0000,00ffff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(3)), + "ff0000,00ff00,0000ff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(4)), + "ff0000,80ff00,00ffff,7f00ff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(5)), + "ff0000,ccff00,00ff66,0066ff,cc00ff" + ); + }, +}); + +runDenoTests(); diff --git a/node_modules/tinycolor2/esm/test_template.js b/node_modules/tinycolor2/esm/test_template.js new file mode 100644 index 00000000..84914f76 --- /dev/null +++ b/node_modules/tinycolor2/esm/test_template.js @@ -0,0 +1,24 @@ +// This file is autogenerated. +// Ideally it wouldn't exist, but it's here to test cjs in node +// Changes should go into ./test.js, and if new assertions are needed +// they'll need to be shimmed here as well +import tinycolor from "./tinycolor.js"; +import { Deno, testDefinitions } from "@deno/shim-deno-test"; +const { assertEquals, assert, assertThrows } = await import( + "../deno_asserts@0.168.0.mjs" +); +async function runDenoTests() { + for (const test of testDefinitions) { + if (test.ignore) { + console.log(`Ignoring ${test.name}`); + continue; + } + console.log(`Running ${test.name}`); + await test.fn(); + console.log(`> Passed ${test.name}`); + } +} + +// CONTENT_GOES_HERE + +runDenoTests(); diff --git a/node_modules/tinycolor2/esm/tinycolor.js b/node_modules/tinycolor2/esm/tinycolor.js new file mode 100644 index 00000000..374f5ea9 --- /dev/null +++ b/node_modules/tinycolor2/esm/tinycolor.js @@ -0,0 +1,1180 @@ +// This file is autogenerated. It's used to publish ESM to npm. +function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); +} + +// https://github.com/bgrins/TinyColor +// Brian Grinstead, MIT License + +var trimLeft = /^\s+/; +var trimRight = /\s+$/; +function tinycolor(color, opts) { + color = color ? color : ""; + opts = opts || {}; + + // If input is already a tinycolor, return itself + if (color instanceof tinycolor) { + return color; + } + // If we are called as a function, call using new instead + if (!(this instanceof tinycolor)) { + return new tinycolor(color, opts); + } + var rgb = inputToRGB(color); + this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; + this._gradientType = opts.gradientType; + + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (this._r < 1) this._r = Math.round(this._r); + if (this._g < 1) this._g = Math.round(this._g); + if (this._b < 1) this._b = Math.round(this._b); + this._ok = rgb.ok; +} +tinycolor.prototype = { + isDark: function isDark() { + return this.getBrightness() < 128; + }, + isLight: function isLight() { + return !this.isDark(); + }, + isValid: function isValid() { + return this._ok; + }, + getOriginalInput: function getOriginalInput() { + return this._originalInput; + }, + getFormat: function getFormat() { + return this._format; + }, + getAlpha: function getAlpha() { + return this._a; + }, + getBrightness: function getBrightness() { + //http://www.w3.org/TR/AERT#color-contrast + var rgb = this.toRgb(); + return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; + }, + getLuminance: function getLuminance() { + //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + var rgb = this.toRgb(); + var RsRGB, GsRGB, BsRGB, R, G, B; + RsRGB = rgb.r / 255; + GsRGB = rgb.g / 255; + BsRGB = rgb.b / 255; + if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); + if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); + if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; + }, + setAlpha: function setAlpha(value) { + this._a = boundAlpha(value); + this._roundA = Math.round(100 * this._a) / 100; + return this; + }, + toHsv: function toHsv() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { + h: hsv.h * 360, + s: hsv.s, + v: hsv.v, + a: this._a + }; + }, + toHsvString: function toHsvString() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = Math.round(hsv.h * 360), + s = Math.round(hsv.s * 100), + v = Math.round(hsv.v * 100); + return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; + }, + toHsl: function toHsl() { + var hsl = rgbToHsl(this._r, this._g, this._b); + return { + h: hsl.h * 360, + s: hsl.s, + l: hsl.l, + a: this._a + }; + }, + toHslString: function toHslString() { + var hsl = rgbToHsl(this._r, this._g, this._b); + var h = Math.round(hsl.h * 360), + s = Math.round(hsl.s * 100), + l = Math.round(hsl.l * 100); + return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; + }, + toHex: function toHex(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function toHexString(allow3Char) { + return "#" + this.toHex(allow3Char); + }, + toHex8: function toHex8(allow4Char) { + return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); + }, + toHex8String: function toHex8String(allow4Char) { + return "#" + this.toHex8(allow4Char); + }, + toRgb: function toRgb() { + return { + r: Math.round(this._r), + g: Math.round(this._g), + b: Math.round(this._b), + a: this._a + }; + }, + toRgbString: function toRgbString() { + return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; + }, + toPercentageRgb: function toPercentageRgb() { + return { + r: Math.round(bound01(this._r, 255) * 100) + "%", + g: Math.round(bound01(this._g, 255) * 100) + "%", + b: Math.round(bound01(this._b, 255) * 100) + "%", + a: this._a + }; + }, + toPercentageRgbString: function toPercentageRgbString() { + return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; + }, + toName: function toName() { + if (this._a === 0) { + return "transparent"; + } + if (this._a < 1) { + return false; + } + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function toFilter(secondColor) { + var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? "GradientType = 1, " : ""; + if (secondColor) { + var s = tinycolor(secondColor); + secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); + } + return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; + }, + toString: function toString(format) { + var formatSet = !!format; + format = format || this._format; + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex4") { + formattedString = this.toHex8String(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } + return formattedString || this.toHexString(); + }, + clone: function clone() { + return tinycolor(this.toString()); + }, + _applyModification: function _applyModification(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function lighten() { + return this._applyModification(_lighten, arguments); + }, + brighten: function brighten() { + return this._applyModification(_brighten, arguments); + }, + darken: function darken() { + return this._applyModification(_darken, arguments); + }, + desaturate: function desaturate() { + return this._applyModification(_desaturate, arguments); + }, + saturate: function saturate() { + return this._applyModification(_saturate, arguments); + }, + greyscale: function greyscale() { + return this._applyModification(_greyscale, arguments); + }, + spin: function spin() { + return this._applyModification(_spin, arguments); + }, + _applyCombination: function _applyCombination(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function analogous() { + return this._applyCombination(_analogous, arguments); + }, + complement: function complement() { + return this._applyCombination(_complement, arguments); + }, + monochromatic: function monochromatic() { + return this._applyCombination(_monochromatic, arguments); + }, + splitcomplement: function splitcomplement() { + return this._applyCombination(_splitcomplement, arguments); + }, + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + // polyad: function (number) { + // return this._applyCombination(polyad, [number]); + // }, + triad: function triad() { + return this._applyCombination(polyad, [3]); + }, + tetrad: function tetrad() { + return this._applyCombination(polyad, [4]); + } +}; + +// If input is an object, force 1 into "1.0" to handle ratios properly +// String input requires "1.0" as input, so 1 will be treated as 1 +tinycolor.fromRatio = function (color, opts) { + if (_typeof(color) == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; + } + return tinycolor(color, opts); +}; + +// Given a string or object, convert that input to RGB +// Possible string inputs: +// +// "red" +// "#f00" or "f00" +// "#ff0000" or "ff0000" +// "#ff000000" or "ff000000" +// "rgb 255 0 0" or "rgb (255, 0, 0)" +// "rgb 1.0 0 0" or "rgb (1, 0, 0)" +// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" +// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" +// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" +// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" +// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" +// +function inputToRGB(color) { + var rgb = { + r: 0, + g: 0, + b: 0 + }; + var a = 1; + var s = null; + var v = null; + var l = null; + var ok = false; + var format = false; + if (typeof color == "string") { + color = stringInputToObject(color); + } + if (_typeof(color) == "object") { + if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { + s = convertToPercentage(color.s); + v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, s, v); + ok = true; + format = "hsv"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { + s = convertToPercentage(color.s); + l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, s, l); + ok = true; + format = "hsl"; + } + if (color.hasOwnProperty("a")) { + a = color.a; + } + } + a = boundAlpha(a); + return { + ok: ok, + format: color.format || format, + r: Math.min(255, Math.max(rgb.r, 0)), + g: Math.min(255, Math.max(rgb.g, 0)), + b: Math.min(255, Math.max(rgb.b, 0)), + a: a + }; +} + +// Conversion Functions +// -------------------- + +// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: +// + +// `rgbToRgb` +// Handle bounds / percentage checking to conform to CSS color spec +// +// *Assumes:* r, g, b in [0, 255] or [0, 1] +// *Returns:* { r, g, b } in [0, 255] +function rgbToRgb(r, g, b) { + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; +} + +// `rgbToHsl` +// Converts an RGB color value to HSL. +// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] +// *Returns:* { h, s, l } in [0,1] +function rgbToHsl(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + l = (max + min) / 2; + if (max == min) { + h = s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + l: l + }; +} + +// `hslToRgb` +// Converts an HSL color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] +function hslToRgb(h, s, l) { + var r, g, b; + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; +} + +// `rgbToHsv` +// Converts an RGB color value to HSV +// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] +// *Returns:* { h, s, v } in [0,1] +function rgbToHsv(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + v = max; + var d = max - min; + s = max === 0 ? 0 : d / max; + if (max == min) { + h = 0; // achromatic + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + v: v + }; +} + +// `hsvToRgb` +// Converts an HSV color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] +function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + var i = Math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; +} + +// `rgbToHex` +// Converts an RGB color to hex +// Assumes r, g, and b are contained in the set [0, 255] +// Returns a 3 or 6 character hex +function rgbToHex(r, g, b, allow3Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + } + return hex.join(""); +} + +// `rgbaToHex` +// Converts an RGBA color plus alpha transparency to hex +// Assumes r, g, b are contained in the set [0, 255] and +// a in [0, 1]. Returns a 4 or 8 character rgba hex +function rgbaToHex(r, g, b, a, allow4Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; + + // Return a 4 character hex if possible + if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); + } + return hex.join(""); +} + +// `rgbaToArgbHex` +// Converts an RGBA color to an ARGB Hex8 string +// Rarely used, but required for "toFilter()" +function rgbaToArgbHex(r, g, b, a) { + var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + return hex.join(""); +} + +// `equals` +// Can be called with any tinycolor input +tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) return false; + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); +}; +tinycolor.random = function () { + return tinycolor.fromRatio({ + r: Math.random(), + g: Math.random(), + b: Math.random() + }); +}; + +// Modification Functions +// ---------------------- +// Thanks to less.js for some of the basics here +// + +function _desaturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); +} +function _saturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); +} +function _greyscale(color) { + return tinycolor(color).desaturate(100); +} +function _lighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} +function _brighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var rgb = tinycolor(color).toRgb(); + rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); + rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); + rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); + return tinycolor(rgb); +} +function _darken(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} + +// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. +// Values outside of this range will be wrapped into this range. +function _spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (hsl.h + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); +} + +// Combination Functions +// --------------------- +// Thanks to jQuery xColor for some of the ideas behind these +// + +function _complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); +} +function polyad(color, number) { + if (isNaN(number) || number <= 0) { + throw new Error("Argument to polyad must be a positive number"); + } + var hsl = tinycolor(color).toHsl(); + var result = [tinycolor(color)]; + var step = 360 / number; + for (var i = 1; i < number; i++) { + result.push(tinycolor({ + h: (hsl.h + i * step) % 360, + s: hsl.s, + l: hsl.l + })); + } + return result; +} +function _splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [tinycolor(color), tinycolor({ + h: (h + 72) % 360, + s: hsl.s, + l: hsl.l + }), tinycolor({ + h: (h + 216) % 360, + s: hsl.s, + l: hsl.l + })]; +} +function _analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; + for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; +} +function _monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, + s = hsv.s, + v = hsv.v; + var ret = []; + var modification = 1 / results; + while (results--) { + ret.push(tinycolor({ + h: h, + s: s, + v: v + })); + v = (v + modification) % 1; + } + return ret; +} + +// Utility Functions +// --------------------- + +tinycolor.mix = function (color1, color2, amount) { + amount = amount === 0 ? 0 : amount || 50; + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); + var p = amount / 100; + var rgba = { + r: (rgb2.r - rgb1.r) * p + rgb1.r, + g: (rgb2.g - rgb1.g) * p + rgb1.g, + b: (rgb2.b - rgb1.b) * p + rgb1.b, + a: (rgb2.a - rgb1.a) * p + rgb1.a + }; + return tinycolor(rgba); +}; + +// Readability Functions +// --------------------- +// false +// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false +tinycolor.isReadable = function (color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; + out = false; + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; + } + return out; +}; + +// `mostReadable` +// Given a base color and a list of possible foreground or background +// colors for that base, returns the most readable color. +// Optionally returns Black or White if the most readable color is unreadable. +// *Example* +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" +tinycolor.mostReadable = function (baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size; + args = args || {}; + includeFallbackColors = args.includeFallbackColors; + level = args.level; + size = args.size; + for (var i = 0; i < colorList.length; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); + } + } + if (tinycolor.isReadable(baseColor, bestColor, { + level: level, + size: size + }) || !includeFallbackColors) { + return bestColor; + } else { + args.includeFallbackColors = false; + return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); + } +}; + +// Big List of Colors +// ------------------ +// +var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" +}; + +// Make it easy to access colors via `hexNames[hex]` +var hexNames = tinycolor.hexNames = flip(names); + +// Utilities +// --------- + +// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` +function flip(o) { + var flipped = {}; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; +} + +// Return a valid alpha value [0,1] with all invalid values being set to 1 +function boundAlpha(a) { + a = parseFloat(a); + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } + return a; +} + +// Take input from [0, n] and return it as [0, 1] +function bound01(n, max) { + if (isOnePointZero(n)) n = "100%"; + var processPercent = isPercentage(n); + n = Math.min(max, Math.max(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; + } + + // Handle floating point rounding errors + if (Math.abs(n - max) < 0.000001) { + return 1; + } + + // Convert into [0, 1] range if it isn't already + return n % max / parseFloat(max); +} + +// Force a number between 0 and 1 +function clamp01(val) { + return Math.min(1, Math.max(0, val)); +} + +// Parse a base-16 hex value into a base-10 integer +function parseIntFromHex(val) { + return parseInt(val, 16); +} + +// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 +// +function isOnePointZero(n) { + return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; +} + +// Check to see if string passed in is a percentage +function isPercentage(n) { + return typeof n === "string" && n.indexOf("%") != -1; +} + +// Force a hex value to have 2 characters +function pad2(c) { + return c.length == 1 ? "0" + c : "" + c; +} + +// Replace a decimal with it's percentage value +function convertToPercentage(n) { + if (n <= 1) { + n = n * 100 + "%"; + } + return n; +} + +// Converts a decimal to a hex value +function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); +} +// Converts a hex value to a decimal +function convertHexToDecimal(h) { + return parseIntFromHex(h) / 255; +} +var matchers = function () { + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + return { + CSS_UNIT: new RegExp(CSS_UNIT), + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; +}(); + +// `isValidCSSUnit` +// Take in a single string / number and check to see if it looks like a CSS unit +// (see `matchers` above for definition). +function isValidCSSUnit(color) { + return !!matchers.CSS_UNIT.exec(color); +} + +// `stringInputToObject` +// Permissive string parsing. Take in a number of formats, and output an object +// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` +function stringInputToObject(color) { + color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } else if (color == "transparent") { + return { + r: 0, + g: 0, + b: 0, + a: 0, + format: "name" + }; + } + + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if (match = matchers.rgb.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3] + }; + } + if (match = matchers.rgba.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3], + a: match[4] + }; + } + if (match = matchers.hsl.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3] + }; + } + if (match = matchers.hsla.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3], + a: match[4] + }; + } + if (match = matchers.hsv.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3] + }; + } + if (match = matchers.hsva.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3], + a: match[4] + }; + } + if (match = matchers.hex8.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + a: convertHexToDecimal(match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex6.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if (match = matchers.hex4.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + a: convertHexToDecimal(match[4] + "" + match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex3.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + format: named ? "name" : "hex" + }; + } + return false; +} +function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || { + level: "AA", + size: "small" + }; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return { + level: level, + size: size + }; +} + +export { tinycolor as default }; diff --git a/node_modules/tinycolor2/package.json b/node_modules/tinycolor2/package.json new file mode 100644 index 00000000..5eb8c35d --- /dev/null +++ b/node_modules/tinycolor2/package.json @@ -0,0 +1,35 @@ +{ + "version": "1.6.0", + "name": "tinycolor2", + "description": "Fast Color Parsing and Manipulation", + "url": "http://bgrins.github.com/TinyColor", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/bgrins/TinyColor.git" + }, + "keywords": [ + "color", + "parser", + "tinycolor" + ], + "author": "Brian Grinstead (http://briangrinstead.com)", + "bugs": { + "url": "https://github.com/bgrins/TinyColor/issues" + }, + "module": "./esm/tinycolor.js", + "main": "./cjs/tinycolor.js", + "browser": "./cjs/tinycolor.js", + "exports": { + ".": { + "import": "./esm/tinycolor.js", + "require": "./cjs/tinycolor.js" + } + }, + "scripts": { + "test": "node cjs/test.js && node esm/test.js" + }, + "devDependencies": { + "@deno/shim-deno-test": "^0.4.0" + } +} diff --git a/node_modules/tinycolor2/tinycolor.js b/node_modules/tinycolor2/tinycolor.js new file mode 100644 index 00000000..52601dfe --- /dev/null +++ b/node_modules/tinycolor2/tinycolor.js @@ -0,0 +1,1191 @@ +// This file is autogenerated. +// It's here at this path for backwards compatibility for links to it +// but the npm package now exports both CJS and ESM. +// See https://github.com/bgrins/TinyColor/ for instructions. + (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.tinycolor = factory()); +})(this, (function () { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); + } + + // https://github.com/bgrins/TinyColor + // Brian Grinstead, MIT License + + var trimLeft = /^\s+/; + var trimRight = /\s+$/; + function tinycolor(color, opts) { + color = color ? color : ""; + opts = opts || {}; + + // If input is already a tinycolor, return itself + if (color instanceof tinycolor) { + return color; + } + // If we are called as a function, call using new instead + if (!(this instanceof tinycolor)) { + return new tinycolor(color, opts); + } + var rgb = inputToRGB(color); + this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; + this._gradientType = opts.gradientType; + + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (this._r < 1) this._r = Math.round(this._r); + if (this._g < 1) this._g = Math.round(this._g); + if (this._b < 1) this._b = Math.round(this._b); + this._ok = rgb.ok; + } + tinycolor.prototype = { + isDark: function isDark() { + return this.getBrightness() < 128; + }, + isLight: function isLight() { + return !this.isDark(); + }, + isValid: function isValid() { + return this._ok; + }, + getOriginalInput: function getOriginalInput() { + return this._originalInput; + }, + getFormat: function getFormat() { + return this._format; + }, + getAlpha: function getAlpha() { + return this._a; + }, + getBrightness: function getBrightness() { + //http://www.w3.org/TR/AERT#color-contrast + var rgb = this.toRgb(); + return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; + }, + getLuminance: function getLuminance() { + //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + var rgb = this.toRgb(); + var RsRGB, GsRGB, BsRGB, R, G, B; + RsRGB = rgb.r / 255; + GsRGB = rgb.g / 255; + BsRGB = rgb.b / 255; + if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); + if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); + if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; + }, + setAlpha: function setAlpha(value) { + this._a = boundAlpha(value); + this._roundA = Math.round(100 * this._a) / 100; + return this; + }, + toHsv: function toHsv() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { + h: hsv.h * 360, + s: hsv.s, + v: hsv.v, + a: this._a + }; + }, + toHsvString: function toHsvString() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = Math.round(hsv.h * 360), + s = Math.round(hsv.s * 100), + v = Math.round(hsv.v * 100); + return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; + }, + toHsl: function toHsl() { + var hsl = rgbToHsl(this._r, this._g, this._b); + return { + h: hsl.h * 360, + s: hsl.s, + l: hsl.l, + a: this._a + }; + }, + toHslString: function toHslString() { + var hsl = rgbToHsl(this._r, this._g, this._b); + var h = Math.round(hsl.h * 360), + s = Math.round(hsl.s * 100), + l = Math.round(hsl.l * 100); + return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; + }, + toHex: function toHex(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function toHexString(allow3Char) { + return "#" + this.toHex(allow3Char); + }, + toHex8: function toHex8(allow4Char) { + return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); + }, + toHex8String: function toHex8String(allow4Char) { + return "#" + this.toHex8(allow4Char); + }, + toRgb: function toRgb() { + return { + r: Math.round(this._r), + g: Math.round(this._g), + b: Math.round(this._b), + a: this._a + }; + }, + toRgbString: function toRgbString() { + return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; + }, + toPercentageRgb: function toPercentageRgb() { + return { + r: Math.round(bound01(this._r, 255) * 100) + "%", + g: Math.round(bound01(this._g, 255) * 100) + "%", + b: Math.round(bound01(this._b, 255) * 100) + "%", + a: this._a + }; + }, + toPercentageRgbString: function toPercentageRgbString() { + return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; + }, + toName: function toName() { + if (this._a === 0) { + return "transparent"; + } + if (this._a < 1) { + return false; + } + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function toFilter(secondColor) { + var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? "GradientType = 1, " : ""; + if (secondColor) { + var s = tinycolor(secondColor); + secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); + } + return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; + }, + toString: function toString(format) { + var formatSet = !!format; + format = format || this._format; + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex4") { + formattedString = this.toHex8String(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } + return formattedString || this.toHexString(); + }, + clone: function clone() { + return tinycolor(this.toString()); + }, + _applyModification: function _applyModification(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function lighten() { + return this._applyModification(_lighten, arguments); + }, + brighten: function brighten() { + return this._applyModification(_brighten, arguments); + }, + darken: function darken() { + return this._applyModification(_darken, arguments); + }, + desaturate: function desaturate() { + return this._applyModification(_desaturate, arguments); + }, + saturate: function saturate() { + return this._applyModification(_saturate, arguments); + }, + greyscale: function greyscale() { + return this._applyModification(_greyscale, arguments); + }, + spin: function spin() { + return this._applyModification(_spin, arguments); + }, + _applyCombination: function _applyCombination(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function analogous() { + return this._applyCombination(_analogous, arguments); + }, + complement: function complement() { + return this._applyCombination(_complement, arguments); + }, + monochromatic: function monochromatic() { + return this._applyCombination(_monochromatic, arguments); + }, + splitcomplement: function splitcomplement() { + return this._applyCombination(_splitcomplement, arguments); + }, + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + // polyad: function (number) { + // return this._applyCombination(polyad, [number]); + // }, + triad: function triad() { + return this._applyCombination(polyad, [3]); + }, + tetrad: function tetrad() { + return this._applyCombination(polyad, [4]); + } + }; + + // If input is an object, force 1 into "1.0" to handle ratios properly + // String input requires "1.0" as input, so 1 will be treated as 1 + tinycolor.fromRatio = function (color, opts) { + if (_typeof(color) == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; + } + return tinycolor(color, opts); + }; + + // Given a string or object, convert that input to RGB + // Possible string inputs: + // + // "red" + // "#f00" or "f00" + // "#ff0000" or "ff0000" + // "#ff000000" or "ff000000" + // "rgb 255 0 0" or "rgb (255, 0, 0)" + // "rgb 1.0 0 0" or "rgb (1, 0, 0)" + // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" + // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" + // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" + // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" + // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" + // + function inputToRGB(color) { + var rgb = { + r: 0, + g: 0, + b: 0 + }; + var a = 1; + var s = null; + var v = null; + var l = null; + var ok = false; + var format = false; + if (typeof color == "string") { + color = stringInputToObject(color); + } + if (_typeof(color) == "object") { + if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { + s = convertToPercentage(color.s); + v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, s, v); + ok = true; + format = "hsv"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { + s = convertToPercentage(color.s); + l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, s, l); + ok = true; + format = "hsl"; + } + if (color.hasOwnProperty("a")) { + a = color.a; + } + } + a = boundAlpha(a); + return { + ok: ok, + format: color.format || format, + r: Math.min(255, Math.max(rgb.r, 0)), + g: Math.min(255, Math.max(rgb.g, 0)), + b: Math.min(255, Math.max(rgb.b, 0)), + a: a + }; + } + + // Conversion Functions + // -------------------- + + // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: + // + + // `rgbToRgb` + // Handle bounds / percentage checking to conform to CSS color spec + // + // *Assumes:* r, g, b in [0, 255] or [0, 1] + // *Returns:* { r, g, b } in [0, 255] + function rgbToRgb(r, g, b) { + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; + } + + // `rgbToHsl` + // Converts an RGB color value to HSL. + // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] + // *Returns:* { h, s, l } in [0,1] + function rgbToHsl(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + l = (max + min) / 2; + if (max == min) { + h = s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + l: l + }; + } + + // `hslToRgb` + // Converts an HSL color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hslToRgb(h, s, l) { + var r, g, b; + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + + // `rgbToHsv` + // Converts an RGB color value to HSV + // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] + // *Returns:* { h, s, v } in [0,1] + function rgbToHsv(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + v = max; + var d = max - min; + s = max === 0 ? 0 : d / max; + if (max == min) { + h = 0; // achromatic + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + v: v + }; + } + + // `hsvToRgb` + // Converts an HSV color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + var i = Math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + + // `rgbToHex` + // Converts an RGB color to hex + // Assumes r, g, and b are contained in the set [0, 255] + // Returns a 3 or 6 character hex + function rgbToHex(r, g, b, allow3Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + } + return hex.join(""); + } + + // `rgbaToHex` + // Converts an RGBA color plus alpha transparency to hex + // Assumes r, g, b are contained in the set [0, 255] and + // a in [0, 1]. Returns a 4 or 8 character rgba hex + function rgbaToHex(r, g, b, a, allow4Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; + + // Return a 4 character hex if possible + if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); + } + return hex.join(""); + } + + // `rgbaToArgbHex` + // Converts an RGBA color to an ARGB Hex8 string + // Rarely used, but required for "toFilter()" + function rgbaToArgbHex(r, g, b, a) { + var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + return hex.join(""); + } + + // `equals` + // Can be called with any tinycolor input + tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) return false; + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); + }; + tinycolor.random = function () { + return tinycolor.fromRatio({ + r: Math.random(), + g: Math.random(), + b: Math.random() + }); + }; + + // Modification Functions + // ---------------------- + // Thanks to less.js for some of the basics here + // + + function _desaturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + function _saturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + function _greyscale(color) { + return tinycolor(color).desaturate(100); + } + function _lighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + function _brighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var rgb = tinycolor(color).toRgb(); + rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); + rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); + rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); + return tinycolor(rgb); + } + function _darken(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + + // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. + // Values outside of this range will be wrapped into this range. + function _spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (hsl.h + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); + } + + // Combination Functions + // --------------------- + // Thanks to jQuery xColor for some of the ideas behind these + // + + function _complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); + } + function polyad(color, number) { + if (isNaN(number) || number <= 0) { + throw new Error("Argument to polyad must be a positive number"); + } + var hsl = tinycolor(color).toHsl(); + var result = [tinycolor(color)]; + var step = 360 / number; + for (var i = 1; i < number; i++) { + result.push(tinycolor({ + h: (hsl.h + i * step) % 360, + s: hsl.s, + l: hsl.l + })); + } + return result; + } + function _splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [tinycolor(color), tinycolor({ + h: (h + 72) % 360, + s: hsl.s, + l: hsl.l + }), tinycolor({ + h: (h + 216) % 360, + s: hsl.s, + l: hsl.l + })]; + } + function _analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; + for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; + } + function _monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, + s = hsv.s, + v = hsv.v; + var ret = []; + var modification = 1 / results; + while (results--) { + ret.push(tinycolor({ + h: h, + s: s, + v: v + })); + v = (v + modification) % 1; + } + return ret; + } + + // Utility Functions + // --------------------- + + tinycolor.mix = function (color1, color2, amount) { + amount = amount === 0 ? 0 : amount || 50; + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); + var p = amount / 100; + var rgba = { + r: (rgb2.r - rgb1.r) * p + rgb1.r, + g: (rgb2.g - rgb1.g) * p + rgb1.g, + b: (rgb2.b - rgb1.b) * p + rgb1.b, + a: (rgb2.a - rgb1.a) * p + rgb1.a + }; + return tinycolor(rgba); + }; + + // Readability Functions + // --------------------- + // false + // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false + tinycolor.isReadable = function (color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; + out = false; + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; + } + return out; + }; + + // `mostReadable` + // Given a base color and a list of possible foreground or background + // colors for that base, returns the most readable color. + // Optionally returns Black or White if the most readable color is unreadable. + // *Example* + // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" + // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" + // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" + // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" + tinycolor.mostReadable = function (baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size; + args = args || {}; + includeFallbackColors = args.includeFallbackColors; + level = args.level; + size = args.size; + for (var i = 0; i < colorList.length; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); + } + } + if (tinycolor.isReadable(baseColor, bestColor, { + level: level, + size: size + }) || !includeFallbackColors) { + return bestColor; + } else { + args.includeFallbackColors = false; + return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); + } + }; + + // Big List of Colors + // ------------------ + // + var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" + }; + + // Make it easy to access colors via `hexNames[hex]` + var hexNames = tinycolor.hexNames = flip(names); + + // Utilities + // --------- + + // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` + function flip(o) { + var flipped = {}; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; + } + + // Return a valid alpha value [0,1] with all invalid values being set to 1 + function boundAlpha(a) { + a = parseFloat(a); + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } + return a; + } + + // Take input from [0, n] and return it as [0, 1] + function bound01(n, max) { + if (isOnePointZero(n)) n = "100%"; + var processPercent = isPercentage(n); + n = Math.min(max, Math.max(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; + } + + // Handle floating point rounding errors + if (Math.abs(n - max) < 0.000001) { + return 1; + } + + // Convert into [0, 1] range if it isn't already + return n % max / parseFloat(max); + } + + // Force a number between 0 and 1 + function clamp01(val) { + return Math.min(1, Math.max(0, val)); + } + + // Parse a base-16 hex value into a base-10 integer + function parseIntFromHex(val) { + return parseInt(val, 16); + } + + // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 + // + function isOnePointZero(n) { + return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; + } + + // Check to see if string passed in is a percentage + function isPercentage(n) { + return typeof n === "string" && n.indexOf("%") != -1; + } + + // Force a hex value to have 2 characters + function pad2(c) { + return c.length == 1 ? "0" + c : "" + c; + } + + // Replace a decimal with it's percentage value + function convertToPercentage(n) { + if (n <= 1) { + n = n * 100 + "%"; + } + return n; + } + + // Converts a decimal to a hex value + function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); + } + // Converts a hex value to a decimal + function convertHexToDecimal(h) { + return parseIntFromHex(h) / 255; + } + var matchers = function () { + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + return { + CSS_UNIT: new RegExp(CSS_UNIT), + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; + }(); + + // `isValidCSSUnit` + // Take in a single string / number and check to see if it looks like a CSS unit + // (see `matchers` above for definition). + function isValidCSSUnit(color) { + return !!matchers.CSS_UNIT.exec(color); + } + + // `stringInputToObject` + // Permissive string parsing. Take in a number of formats, and output an object + // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` + function stringInputToObject(color) { + color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } else if (color == "transparent") { + return { + r: 0, + g: 0, + b: 0, + a: 0, + format: "name" + }; + } + + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if (match = matchers.rgb.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3] + }; + } + if (match = matchers.rgba.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3], + a: match[4] + }; + } + if (match = matchers.hsl.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3] + }; + } + if (match = matchers.hsla.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3], + a: match[4] + }; + } + if (match = matchers.hsv.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3] + }; + } + if (match = matchers.hsva.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3], + a: match[4] + }; + } + if (match = matchers.hex8.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + a: convertHexToDecimal(match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex6.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if (match = matchers.hex4.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + a: convertHexToDecimal(match[4] + "" + match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex3.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + format: named ? "name" : "hex" + }; + } + return false; + } + function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || { + level: "AA", + size: "small" + }; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return { + level: level, + size: size + }; + } + + return tinycolor; + +})); diff --git a/node_modules/token-types/LICENSE b/node_modules/token-types/LICENSE new file mode 100644 index 00000000..ffcebb7b --- /dev/null +++ b/node_modules/token-types/LICENSE @@ -0,0 +1,7 @@ +Copyright 2017 Borewit + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/token-types/README.md b/node_modules/token-types/README.md new file mode 100644 index 00000000..8391ac6f --- /dev/null +++ b/node_modules/token-types/README.md @@ -0,0 +1,115 @@ +![Node.js CI](https://github.com/Borewit/token-types/workflows/Node.js%20CI/badge.svg) +[![NPM version](https://badge.fury.io/js/token-types.svg)](https://npmjs.org/package/token-types) +[![npm downloads](http://img.shields.io/npm/dm/token-types.svg)](https://npmcharts.com/compare/token-types,strtok3?start=1200&interval=30) +[![coveralls](https://coveralls.io/repos/github/Borewit/token-types/badge.svg?branch=master)](https://coveralls.io/github/Borewit/token-types?branch=master) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/4723ce4613fc49cda8db5eed29f18834)](https://www.codacy.com/app/Borewit/token-types?utm_source=github.com&utm_medium=referral&utm_content=Borewit/token-types&utm_campaign=Badge_Grade) +[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Borewit/token-types.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/token-types/context:javascript) +[![Total alerts](https://img.shields.io/lgtm/alerts/g/Borewit/token-types.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/token-types/alerts/) +[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/6940/branches/61852/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=6940&bid=61852) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/token-types/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/token-types?targetFile=package.json) + +# token-types + +A primitive token library used to read and write from a node `Buffer`. +Although it is possible to use this module directly, it is primary designed to be used with [strtok3 tokenizer](https://github.com/Borewit/strtok3). + +## Installation + +```sh +npm install --save token-types +``` +Usually in combination with [strtok3](https://github.com/Borewit/strtok3): +```sh +npm install --save strtok3 +``` + +Using TypeScript you should also install [@tokenizer/token](https://github.com/Borewit/tokenizer-token) as a development +dependency: + +```shell +npm install --save-dev @tokenizer/token +``` + + +## Example + +```js +const strtok3 = require('strtok3'); +const token = require('token-types'); + +(async () => { + + const tokenizer = await strtok3.fromFile("somefile.bin"); + try { + const myNumber = await tokenizer.readToken(token.Float32_BE); + console.log(`My number: ${myNumber}`); + } finally { + tokenizer.close(); // Close the file + } +})(); +``` + +## Tokens + +### Numeric tokens + +`node-strtok` supports a wide variety of numerical tokens out of the box: + +| Token | Number | Bits | Endianness | +|---------------|------------------|------|----------------| +| `UINT8` | Unsigned integer | 8 | n/a | +| `UINT16_BE` | Unsigned integer | 16 | big endian | +| `UINT16_LE` | Unsigned integer | 16 | little endian | +| `UINT24_BE` | Unsigned integer | 24 | big endian | +| `UINT24_LE` | Unsigned integer | 24 | little endian | +| `UINT32_BE` | Unsigned integer | 32 | big endian | +| `UINT32_LE` | Unsigned integer | 32 | little endian | +| `UINT64_BE` | Unsigned integer | 64 | big endian | +| `UINT64_LE`* | Unsigned integer | 64 | little endian | +| `INT8` | Signed integer | 8 | n/a | +| `INT16_BE` | Signed integer | 16 | big endian | +| `INT16_LE` | Signed integer | 16 | little endian | +| `INT24_BE` | Signed integer | 24 | big endian | +| `INT24_LE` | Signed integer | 24 | little endian | +| `INT32_BE` | Signed integer | 32 | big endian | +| `INT32_LE` | Signed integer | 32 | little endian | +| `INT64_BE` | Signed integer | 64 | big endian | +| `INT64_LE`* | Signed integer | 64 | little endian | +| `Float16_BE` | IEEE 754 float | 16 | big endian | +| `Float16_LE` | IEEE 754 float | 16 | little endian | +| `Float32_BE` | IEEE 754 float | 32 | big endian | +| `Float32_LE` | IEEE 754 float | 32 | little endian | +| `Float64_BE` | IEEE 754 float | 64 | big endian | +| `Float64_LE` | IEEE 754 float | 64 | little endian | +| `Float80_BE`* | IEEE 754 float | 80 | big endian | +| `Float80_LE`* | IEEE 754 float | 80 | little endian | + +### Other tokens + +String types: +* Windows-1252 +* ISO-8859-1 + +*) The tokens exceed the JavaScript IEEE 754 64-bit Floating Point precision, decoding and encoding is best effort based. + +### Custom token + +Complex tokens can be added, which makes very suitable for reading binary files or network messages: +```js + ExtendedHeader = { + len: 10, + + get: (buf, off) => { + return { + // Extended header size + size: Token.UINT32_BE.get(buf, off), + // Extended Flags + extendedFlags: Token.UINT16_BE.get(buf, off + 4), + // Size of padding + sizeOfPadding: Token.UINT32_BE.get(buf, off + 6), + // CRC data present + crcDataPresent: common.strtokBITSET.get(buf, off + 4, 31) + }; + } + }; +``` diff --git a/node_modules/token-types/lib/index.d.ts b/node_modules/token-types/lib/index.d.ts new file mode 100644 index 00000000..bcf41936 --- /dev/null +++ b/node_modules/token-types/lib/index.d.ts @@ -0,0 +1,150 @@ +/// +import { IToken, IGetToken } from '@tokenizer/token'; +/** + * 8-bit unsigned integer + */ +export declare const UINT8: IToken; +/** + * 16-bit unsigned integer, Little Endian byte order + */ +export declare const UINT16_LE: IToken; +/** + * 16-bit unsigned integer, Big Endian byte order + */ +export declare const UINT16_BE: IToken; +/** + * 24-bit unsigned integer, Little Endian byte order + */ +export declare const UINT24_LE: IToken; +/** + * 24-bit unsigned integer, Big Endian byte order + */ +export declare const UINT24_BE: IToken; +/** + * 32-bit unsigned integer, Little Endian byte order + */ +export declare const UINT32_LE: IToken; +/** + * 32-bit unsigned integer, Big Endian byte order + */ +export declare const UINT32_BE: IToken; +/** + * 8-bit signed integer + */ +export declare const INT8: IToken; +/** + * 16-bit signed integer, Big Endian byte order + */ +export declare const INT16_BE: IToken; +/** + * 16-bit signed integer, Little Endian byte order + */ +export declare const INT16_LE: IToken; +/** + * 24-bit signed integer, Little Endian byte order + */ +export declare const INT24_LE: IToken; +/** + * 24-bit signed integer, Big Endian byte order + */ +export declare const INT24_BE: IToken; +/** + * 32-bit signed integer, Big Endian byte order + */ +export declare const INT32_BE: IToken; +/** + * 32-bit signed integer, Big Endian byte order + */ +export declare const INT32_LE: IToken; +/** + * 64-bit unsigned integer, Little Endian byte order + */ +export declare const UINT64_LE: IToken; +/** + * 64-bit signed integer, Little Endian byte order + */ +export declare const INT64_LE: IToken; +/** + * 64-bit unsigned integer, Big Endian byte order + */ +export declare const UINT64_BE: IToken; +/** + * 64-bit signed integer, Big Endian byte order + */ +export declare const INT64_BE: IToken; +/** + * IEEE 754 16-bit (half precision) float, big endian + */ +export declare const Float16_BE: IToken; +/** + * IEEE 754 16-bit (half precision) float, little endian + */ +export declare const Float16_LE: IToken; +/** + * IEEE 754 32-bit (single precision) float, big endian + */ +export declare const Float32_BE: IToken; +/** + * IEEE 754 32-bit (single precision) float, little endian + */ +export declare const Float32_LE: IToken; +/** + * IEEE 754 64-bit (double precision) float, big endian + */ +export declare const Float64_BE: IToken; +/** + * IEEE 754 64-bit (double precision) float, little endian + */ +export declare const Float64_LE: IToken; +/** + * IEEE 754 80-bit (extended precision) float, big endian + */ +export declare const Float80_BE: IToken; +/** + * IEEE 754 80-bit (extended precision) float, little endian + */ +export declare const Float80_LE: IToken; +/** + * Ignore a given number of bytes + */ +export declare class IgnoreType implements IGetToken { + len: number; + /** + * @param len number of bytes to ignore + */ + constructor(len: number); + get(array: Uint8Array, off: number): void; +} +export declare class Uint8ArrayType implements IGetToken { + len: number; + constructor(len: number); + get(array: Uint8Array, offset: number): Uint8Array; +} +export declare class BufferType implements IGetToken { + len: number; + constructor(len: number); + get(uint8Array: Uint8Array, off: number): Buffer; +} +/** + * Consume a fixed number of bytes from the stream and return a string with a specified encoding. + */ +export declare class StringType implements IGetToken { + len: number; + encoding: BufferEncoding; + constructor(len: number, encoding: BufferEncoding); + get(uint8Array: Uint8Array, offset: number): string; +} +/** + * ANSI Latin 1 String + * Using windows-1252 / ISO 8859-1 decoding + */ +export declare class AnsiStringType implements IGetToken { + len: number; + private static windows1252; + private static decode; + private static inRange; + private static codePointToString; + private static singleByteDecoder; + constructor(len: number); + get(buffer: Buffer, offset?: number): string; +} diff --git a/node_modules/token-types/lib/index.js b/node_modules/token-types/lib/index.js new file mode 100644 index 00000000..82d8e0a2 --- /dev/null +++ b/node_modules/token-types/lib/index.js @@ -0,0 +1,455 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AnsiStringType = exports.StringType = exports.BufferType = exports.Uint8ArrayType = exports.IgnoreType = exports.Float80_LE = exports.Float80_BE = exports.Float64_LE = exports.Float64_BE = exports.Float32_LE = exports.Float32_BE = exports.Float16_LE = exports.Float16_BE = exports.INT64_BE = exports.UINT64_BE = exports.INT64_LE = exports.UINT64_LE = exports.INT32_LE = exports.INT32_BE = exports.INT24_BE = exports.INT24_LE = exports.INT16_LE = exports.INT16_BE = exports.INT8 = exports.UINT32_BE = exports.UINT32_LE = exports.UINT24_BE = exports.UINT24_LE = exports.UINT16_BE = exports.UINT16_LE = exports.UINT8 = void 0; +const ieee754 = require("ieee754"); +// Primitive types +function dv(array) { + return new DataView(array.buffer, array.byteOffset); +} +/** + * 8-bit unsigned integer + */ +exports.UINT8 = { + len: 1, + get(array, offset) { + return dv(array).getUint8(offset); + }, + put(array, offset, value) { + dv(array).setUint8(offset, value); + return offset + 1; + } +}; +/** + * 16-bit unsigned integer, Little Endian byte order + */ +exports.UINT16_LE = { + len: 2, + get(array, offset) { + return dv(array).getUint16(offset, true); + }, + put(array, offset, value) { + dv(array).setUint16(offset, value, true); + return offset + 2; + } +}; +/** + * 16-bit unsigned integer, Big Endian byte order + */ +exports.UINT16_BE = { + len: 2, + get(array, offset) { + return dv(array).getUint16(offset); + }, + put(array, offset, value) { + dv(array).setUint16(offset, value); + return offset + 2; + } +}; +/** + * 24-bit unsigned integer, Little Endian byte order + */ +exports.UINT24_LE = { + len: 3, + get(array, offset) { + const dataView = dv(array); + return dataView.getUint8(offset) + (dataView.getUint16(offset + 1, true) << 8); + }, + put(array, offset, value) { + const dataView = dv(array); + dataView.setUint8(offset, value & 0xff); + dataView.setUint16(offset + 1, value >> 8, true); + return offset + 3; + } +}; +/** + * 24-bit unsigned integer, Big Endian byte order + */ +exports.UINT24_BE = { + len: 3, + get(array, offset) { + const dataView = dv(array); + return (dataView.getUint16(offset) << 8) + dataView.getUint8(offset + 2); + }, + put(array, offset, value) { + const dataView = dv(array); + dataView.setUint16(offset, value >> 8); + dataView.setUint8(offset + 2, value & 0xff); + return offset + 3; + } +}; +/** + * 32-bit unsigned integer, Little Endian byte order + */ +exports.UINT32_LE = { + len: 4, + get(array, offset) { + return dv(array).getUint32(offset, true); + }, + put(array, offset, value) { + dv(array).setUint32(offset, value, true); + return offset + 4; + } +}; +/** + * 32-bit unsigned integer, Big Endian byte order + */ +exports.UINT32_BE = { + len: 4, + get(array, offset) { + return dv(array).getUint32(offset); + }, + put(array, offset, value) { + dv(array).setUint32(offset, value); + return offset + 4; + } +}; +/** + * 8-bit signed integer + */ +exports.INT8 = { + len: 1, + get(array, offset) { + return dv(array).getInt8(offset); + }, + put(array, offset, value) { + dv(array).setInt8(offset, value); + return offset + 1; + } +}; +/** + * 16-bit signed integer, Big Endian byte order + */ +exports.INT16_BE = { + len: 2, + get(array, offset) { + return dv(array).getInt16(offset); + }, + put(array, offset, value) { + dv(array).setInt16(offset, value); + return offset + 2; + } +}; +/** + * 16-bit signed integer, Little Endian byte order + */ +exports.INT16_LE = { + len: 2, + get(array, offset) { + return dv(array).getInt16(offset, true); + }, + put(array, offset, value) { + dv(array).setInt16(offset, value, true); + return offset + 2; + } +}; +/** + * 24-bit signed integer, Little Endian byte order + */ +exports.INT24_LE = { + len: 3, + get(array, offset) { + const unsigned = exports.UINT24_LE.get(array, offset); + return unsigned > 0x7fffff ? unsigned - 0x1000000 : unsigned; + }, + put(array, offset, value) { + const dataView = dv(array); + dataView.setUint8(offset, value & 0xff); + dataView.setUint16(offset + 1, value >> 8, true); + return offset + 3; + } +}; +/** + * 24-bit signed integer, Big Endian byte order + */ +exports.INT24_BE = { + len: 3, + get(array, offset) { + const unsigned = exports.UINT24_BE.get(array, offset); + return unsigned > 0x7fffff ? unsigned - 0x1000000 : unsigned; + }, + put(array, offset, value) { + const dataView = dv(array); + dataView.setUint16(offset, value >> 8); + dataView.setUint8(offset + 2, value & 0xff); + return offset + 3; + } +}; +/** + * 32-bit signed integer, Big Endian byte order + */ +exports.INT32_BE = { + len: 4, + get(array, offset) { + return dv(array).getInt32(offset); + }, + put(array, offset, value) { + dv(array).setInt32(offset, value); + return offset + 4; + } +}; +/** + * 32-bit signed integer, Big Endian byte order + */ +exports.INT32_LE = { + len: 4, + get(array, offset) { + return dv(array).getInt32(offset, true); + }, + put(array, offset, value) { + dv(array).setInt32(offset, value, true); + return offset + 4; + } +}; +/** + * 64-bit unsigned integer, Little Endian byte order + */ +exports.UINT64_LE = { + len: 8, + get(array, offset) { + return dv(array).getBigUint64(offset, true); + }, + put(array, offset, value) { + dv(array).setBigUint64(offset, value, true); + return offset + 8; + } +}; +/** + * 64-bit signed integer, Little Endian byte order + */ +exports.INT64_LE = { + len: 8, + get(array, offset) { + return dv(array).getBigInt64(offset, true); + }, + put(array, offset, value) { + dv(array).setBigInt64(offset, value, true); + return offset + 8; + } +}; +/** + * 64-bit unsigned integer, Big Endian byte order + */ +exports.UINT64_BE = { + len: 8, + get(array, offset) { + return dv(array).getBigUint64(offset); + }, + put(array, offset, value) { + dv(array).setBigUint64(offset, value); + return offset + 8; + } +}; +/** + * 64-bit signed integer, Big Endian byte order + */ +exports.INT64_BE = { + len: 8, + get(array, offset) { + return dv(array).getBigInt64(offset); + }, + put(array, offset, value) { + dv(array).setBigInt64(offset, value); + return offset + 8; + } +}; +/** + * IEEE 754 16-bit (half precision) float, big endian + */ +exports.Float16_BE = { + len: 2, + get(dataView, offset) { + return ieee754.read(dataView, offset, false, 10, this.len); + }, + put(dataView, offset, value) { + ieee754.write(dataView, value, offset, false, 10, this.len); + return offset + this.len; + } +}; +/** + * IEEE 754 16-bit (half precision) float, little endian + */ +exports.Float16_LE = { + len: 2, + get(array, offset) { + return ieee754.read(array, offset, true, 10, this.len); + }, + put(array, offset, value) { + ieee754.write(array, value, offset, true, 10, this.len); + return offset + this.len; + } +}; +/** + * IEEE 754 32-bit (single precision) float, big endian + */ +exports.Float32_BE = { + len: 4, + get(array, offset) { + return dv(array).getFloat32(offset); + }, + put(array, offset, value) { + dv(array).setFloat32(offset, value); + return offset + 4; + } +}; +/** + * IEEE 754 32-bit (single precision) float, little endian + */ +exports.Float32_LE = { + len: 4, + get(array, offset) { + return dv(array).getFloat32(offset, true); + }, + put(array, offset, value) { + dv(array).setFloat32(offset, value, true); + return offset + 4; + } +}; +/** + * IEEE 754 64-bit (double precision) float, big endian + */ +exports.Float64_BE = { + len: 8, + get(array, offset) { + return dv(array).getFloat64(offset); + }, + put(array, offset, value) { + dv(array).setFloat64(offset, value); + return offset + 8; + } +}; +/** + * IEEE 754 64-bit (double precision) float, little endian + */ +exports.Float64_LE = { + len: 8, + get(array, offset) { + return dv(array).getFloat64(offset, true); + }, + put(array, offset, value) { + dv(array).setFloat64(offset, value, true); + return offset + 8; + } +}; +/** + * IEEE 754 80-bit (extended precision) float, big endian + */ +exports.Float80_BE = { + len: 10, + get(array, offset) { + return ieee754.read(array, offset, false, 63, this.len); + }, + put(array, offset, value) { + ieee754.write(array, value, offset, false, 63, this.len); + return offset + this.len; + } +}; +/** + * IEEE 754 80-bit (extended precision) float, little endian + */ +exports.Float80_LE = { + len: 10, + get(array, offset) { + return ieee754.read(array, offset, true, 63, this.len); + }, + put(array, offset, value) { + ieee754.write(array, value, offset, true, 63, this.len); + return offset + this.len; + } +}; +/** + * Ignore a given number of bytes + */ +class IgnoreType { + /** + * @param len number of bytes to ignore + */ + constructor(len) { + this.len = len; + } + // ToDo: don't read, but skip data + get(array, off) { + } +} +exports.IgnoreType = IgnoreType; +class Uint8ArrayType { + constructor(len) { + this.len = len; + } + get(array, offset) { + return array.subarray(offset, offset + this.len); + } +} +exports.Uint8ArrayType = Uint8ArrayType; +class BufferType { + constructor(len) { + this.len = len; + } + get(uint8Array, off) { + return Buffer.from(uint8Array.subarray(off, off + this.len)); + } +} +exports.BufferType = BufferType; +/** + * Consume a fixed number of bytes from the stream and return a string with a specified encoding. + */ +class StringType { + constructor(len, encoding) { + this.len = len; + this.encoding = encoding; + } + get(uint8Array, offset) { + return Buffer.from(uint8Array).toString(this.encoding, offset, offset + this.len); + } +} +exports.StringType = StringType; +/** + * ANSI Latin 1 String + * Using windows-1252 / ISO 8859-1 decoding + */ +class AnsiStringType { + constructor(len) { + this.len = len; + } + static decode(buffer, offset, until) { + let str = ''; + for (let i = offset; i < until; ++i) { + str += AnsiStringType.codePointToString(AnsiStringType.singleByteDecoder(buffer[i])); + } + return str; + } + static inRange(a, min, max) { + return min <= a && a <= max; + } + static codePointToString(cp) { + if (cp <= 0xFFFF) { + return String.fromCharCode(cp); + } + else { + cp -= 0x10000; + return String.fromCharCode((cp >> 10) + 0xD800, (cp & 0x3FF) + 0xDC00); + } + } + static singleByteDecoder(bite) { + if (AnsiStringType.inRange(bite, 0x00, 0x7F)) { + return bite; + } + const codePoint = AnsiStringType.windows1252[bite - 0x80]; + if (codePoint === null) { + throw Error('invaliding encoding'); + } + return codePoint; + } + get(buffer, offset = 0) { + return AnsiStringType.decode(buffer, offset, offset + this.len); + } +} +exports.AnsiStringType = AnsiStringType; +AnsiStringType.windows1252 = [8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, + 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, + 8482, 353, 8250, 339, 157, 382, 376, 160, 161, 162, 163, 164, 165, 166, 167, 168, + 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, + 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, + 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, + 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255]; diff --git a/node_modules/token-types/package.json b/node_modules/token-types/package.json new file mode 100644 index 00000000..8882afe2 --- /dev/null +++ b/node_modules/token-types/package.json @@ -0,0 +1,93 @@ +{ + "name": "token-types", + "version": "4.2.1", + "description": "Common token types for decoding and encoding numeric and string values", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "scripts": { + "clean": "del-cli lib/**/*.js lib/***.js.map *.d.ts test/**/*.d.ts test/**/*.js test/**/*.js.map .nyc_output", + "build": "npm run compile", + "compile-src": "tsc --p lib", + "compile-test": "tsc --p test", + "compile": "npm run compile-src && npm run compile-test", + "lint-ts": "tslint lib/index.ts --exclude '*.d.ts' 'test/**/*.ts' --exclude 'test/**/*.d.ts'", + "lint-md": "remark -u preset-lint-recommended .", + "lint": "npm run lint-ts && npm run lint-md", + "test": "mocha --require ts-node/register --require source-map-support/register --full-trace --recursive test/test-*.ts", + "test-coverage": "nyc npm run test" + }, + "engines": { + "node": ">=10" + }, + "repository": { + "type": "git", + "url": "https://github.com/Borewit/token-types" + }, + "files": [ + "lib/index.js", + "lib/index.d.ts" + ], + "license": "MIT", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "bugs": { + "url": "https://github.com/Borewit/token-types/issues" + }, + "devDependencies": { + "@types/chai": "^4.3.1", + "@types/mocha": "^9.1.0", + "@types/node": "^18.6.3", + "chai": "^4.3.6", + "coveralls": "^3.1.1", + "del-cli": "^5.0.0", + "mocha": "^9.2.2", + "nyc": "^15.1.0", + "remark-cli": "^11.0.0", + "remark-preset-lint-recommended": "^6.1.2", + "source-map-support": "^0.5.21", + "ts-node": "^10.9.1", + "tslint": "^6.1.3", + "typescript": "^4.7.4" + }, + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "remarkConfig": { + "plugins": [ + "preset-lint-recommended" + ] + }, + "nyc": { + "exclude": [ + "test/**/*.ts", + "lib/**/*.*.js" + ], + "extension": [ + ".ts" + ], + "sourceMap": true, + "instrument": true, + "reporter": [ + "lcov", + "text" + ], + "report-dir": "coverage" + }, + "keywords": [ + "token", + "integer", + "unsigned", + "numeric", + "float", + "IEEE", + "754", + "strtok3" + ] +} diff --git a/node_modules/tr46/.npmignore b/node_modules/tr46/.npmignore new file mode 100644 index 00000000..96e9161f --- /dev/null +++ b/node_modules/tr46/.npmignore @@ -0,0 +1,4 @@ +scripts/ +test/ + +!lib/mapping_table.json diff --git a/node_modules/tr46/index.js b/node_modules/tr46/index.js new file mode 100644 index 00000000..9ce12ca2 --- /dev/null +++ b/node_modules/tr46/index.js @@ -0,0 +1,193 @@ +"use strict"; + +var punycode = require("punycode"); +var mappingTable = require("./lib/mappingTable.json"); + +var PROCESSING_OPTIONS = { + TRANSITIONAL: 0, + NONTRANSITIONAL: 1 +}; + +function normalize(str) { // fix bug in v8 + return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); +} + +function findStatus(val) { + var start = 0; + var end = mappingTable.length - 1; + + while (start <= end) { + var mid = Math.floor((start + end) / 2); + + var target = mappingTable[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + return target; + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +function countSymbols(string) { + return string + // replace every surrogate pair with a BMP symbol + .replace(regexAstralSymbols, '_') + // then get the length + .length; +} + +function mapChars(domain_name, useSTD3, processing_option) { + var hasError = false; + var processed = ""; + + var len = countSymbols(domain_name); + for (var i = 0; i < len; ++i) { + var codePoint = domain_name.codePointAt(i); + var status = findStatus(codePoint); + + switch (status[1]) { + case "disallowed": + hasError = true; + processed += String.fromCodePoint(codePoint); + break; + case "ignored": + break; + case "mapped": + processed += String.fromCodePoint.apply(String, status[2]); + break; + case "deviation": + if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { + processed += String.fromCodePoint.apply(String, status[2]); + } else { + processed += String.fromCodePoint(codePoint); + } + break; + case "valid": + processed += String.fromCodePoint(codePoint); + break; + case "disallowed_STD3_mapped": + if (useSTD3) { + hasError = true; + processed += String.fromCodePoint(codePoint); + } else { + processed += String.fromCodePoint.apply(String, status[2]); + } + break; + case "disallowed_STD3_valid": + if (useSTD3) { + hasError = true; + } + + processed += String.fromCodePoint(codePoint); + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; + +function validateLabel(label, processing_option) { + if (label.substr(0, 4) === "xn--") { + label = punycode.toUnicode(label); + processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; + } + + var error = false; + + if (normalize(label) !== label || + (label[3] === "-" && label[4] === "-") || + label[0] === "-" || label[label.length - 1] === "-" || + label.indexOf(".") !== -1 || + label.search(combiningMarksRegex) === 0) { + error = true; + } + + var len = countSymbols(label); + for (var i = 0; i < len; ++i) { + var status = findStatus(label.codePointAt(i)); + if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || + (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && + status[1] !== "valid" && status[1] !== "deviation")) { + error = true; + break; + } + } + + return { + label: label, + error: error + }; +} + +function processing(domain_name, useSTD3, processing_option) { + var result = mapChars(domain_name, useSTD3, processing_option); + result.string = normalize(result.string); + + var labels = result.string.split("."); + for (var i = 0; i < labels.length; ++i) { + try { + var validation = validateLabel(labels[i]); + labels[i] = validation.label; + result.error = result.error || validation.error; + } catch(e) { + result.error = true; + } + } + + return { + string: labels.join("."), + error: result.error + }; +} + +module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { + var result = processing(domain_name, useSTD3, processing_option); + var labels = result.string.split("."); + labels = labels.map(function(l) { + try { + return punycode.toASCII(l); + } catch(e) { + result.error = true; + return l; + } + }); + + if (verifyDnsLength) { + var total = labels.slice(0, labels.length - 1).join(".").length; + if (total.length > 253 || total.length === 0) { + result.error = true; + } + + for (var i=0; i < labels.length; ++i) { + if (labels.length > 63 || labels.length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) return null; + return labels.join("."); +}; + +module.exports.toUnicode = function(domain_name, useSTD3) { + var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + + return { + domain: result.string, + error: result.error + }; +}; + +module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; diff --git a/node_modules/tr46/lib/.gitkeep b/node_modules/tr46/lib/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/node_modules/tr46/lib/mappingTable.json b/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 00000000..89cf19a7 --- /dev/null +++ b/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]] \ No newline at end of file diff --git a/node_modules/tr46/package.json b/node_modules/tr46/package.json new file mode 100644 index 00000000..b6826da1 --- /dev/null +++ b/node_modules/tr46/package.json @@ -0,0 +1,31 @@ +{ + "name": "tr46", + "version": "0.0.3", + "description": "An implementation of the Unicode TR46 spec", + "main": "index.js", + "scripts": { + "test": "mocha", + "pretest": "node scripts/getLatestUnicodeTests.js", + "prepublish": "node scripts/generateMappingTable.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Sebmaster/tr46.js.git" + }, + "keywords": [ + "unicode", + "tr46", + "url", + "whatwg" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "bugs": { + "url": "https://github.com/Sebmaster/tr46.js/issues" + }, + "homepage": "https://github.com/Sebmaster/tr46.js#readme", + "devDependencies": { + "mocha": "^2.2.5", + "request": "^2.57.0" + } +} diff --git a/node_modules/utif2/LICENSE b/node_modules/utif2/LICENSE new file mode 100644 index 00000000..491e2390 --- /dev/null +++ b/node_modules/utif2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Photopea + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/utif2/README.md b/node_modules/utif2/README.md new file mode 100644 index 00000000..2ea2e125 --- /dev/null +++ b/node_modules/utif2/README.md @@ -0,0 +1,86 @@ + +# UTIF2 +## This is newer version of [UTIF](https://www.npmjs.com/package/utif) + +Since last update of UTIF was 18/6/2019 and [Photopea does not touch npm](https://github.com/photopea/UTIF.js/issues/106) at all and neither 3rd party developer is keeping package up to date with GitHub repo... this package is just updated version of utif (from npm) but with many improvements. + +## About + +A small, fast and advanced TIFF / EXIF (+ DNG, CR2, NEF and other TIFF-ish files) decoder and encoder. It is the main TIFF library for [Photopea image editor](https://www.photopea.com). Try to open your TIFF file with Photopea to see, if UTIF.js can parse it. + +* Supports Black & White, Grayscale, RGB and Paletted images +* Supports Fax 3 and Fax 4 (CCITT), JPEG, LZW, PackBits and other compressions (1,3,4,5,6,7,8,32773,32809) +* E.g. [this 8 MPix image](//www.photopea.com/api/img/G4.TIF) with Fax 4 compression is just 56 kB ( [Open in Photopea](https://www.photopea.com?p=%7B%22files%22:%5B%22//www.photopea.com/api/img/G4.TIF%22%5D%7D) ) + +For RAW files, UTIF.js only decodes raw sensor data (and JPG previews, if there are any). It does not convert the raw data into a displayable image (RGBA). Such conversion is complex and out of scope of this library. + +## Installation + +Download and include the `UTIF.js` file in your code. If you're in NodeJS or otherwise using NPM, run: + +```sh +npm install utif +``` + +#### `UTIF.decode(buffer)` +* `buffer`: ArrayBuffer containing TIFF or EXIF data +* returns an array of "IFDs" (image file directories). Each IFD is an object, keys are "tXYZ" (XYZ is a TIFF tag number), values are values of these tags. You can get the the dimension (and other properties, "metadata") of the image without decompressing pixel data. + +#### `UTIF.decodeImage(buffer, ifd)` +* `buffer`: ArrayBuffer containing TIFF or EXIF data +* `ifd`: the element of the output of UTIF.decode() +* If there is an image inside the IFD, it is decoded and three new properties are added to the IFD: +* * `width`: the width of the image +* * `height`: the height of the image +* * `data`: decompressed pixel data of the image + +TIFF files may have various number of channels and various color depth. The interpretation of `data` depends on many tags (see the [TIFF 6 specification](http://www.npes.org/pdf/TIFF-v6.pdf)). The following function converts any TIFF image into a 8-bit RGBA image. + +#### `UTIF.toRGBA8(ifd)` +* `ifd`: image file directory (element of "ifds" returned by UTIF.decode(), processed by UTIF.decodeImage()) +* returns Uint8Array of the image in RGBA format, 8 bits per channel (ready to use in context2d.putImageData() etc.) + +### Example + +```javascript +function imgLoaded(e) { + var ifds = UTIF.decode(e.target.response); + UTIF.decodeImage(e.target.response, ifds[0]) + var rgba = UTIF.toRGBA8(ifds[0]); // Uint8Array with RGBA pixels + console.log(ifds[0].width, ifds[0].height, ifds[0]); +} + +var xhr = new XMLHttpRequest(); +xhr.open("GET", "my_image.tif"); +xhr.responseType = "arraybuffer"; +xhr.onload = imgLoaded; xhr.send(); +``` +## Use TIFF images in HTML + +If you are not a programmer, you can use TIFF images directly inside the `` element of HTML. Then, it is enough to call `UTIF.replaceIMG()` once at some point. + +#### `UTIF.replaceIMG()` +```html + +... + ... +``` +And UTIF.js will do the rest. Internally, the "src" attribute of the image will be replaced with a new URI of the image (base64-encoded PNG). Note, that you can also insert DNG, CR2, NEF and other raw images into HTML this way. + +## Encoding TIFF images + +You should not save images into TIFF format in the 21st century. Save them as PNG instead (e.g. using [UPNG.js](https://github.com/photopea/UPNG.js)). If you still want to use TIFF format for some reason, here it is. + +#### `UTIF.encodeImage(rgba, w, h, metadata)` +* `rgba`: ArrayBuffer containing RGBA pixel data +* `w`: image width +* `h`: image height +* `metadata` [optional]: IFD object (see below) +* returns ArrayBuffer of the binary TIFF file. No compression right now. + +#### `UTIF.encode(ifds)` +* `ifds`: array of IFDs (image file directories). An IFD is a JS object with properties "tXYZ" (where XYZ are TIFF tags) +* returns ArrayBuffer of binary data. You can use it to encode EXIF data. + +## Dependencies +TIFF format sometimes uses Inflate algorithm for compression (but it is quite rare). Right now, UTIF.js calls [Pako.js](https://github.com/nodeca/pako) for the Inflate method. diff --git a/node_modules/utif2/UTIF.d.ts b/node_modules/utif2/UTIF.d.ts new file mode 100644 index 00000000..aac72733 --- /dev/null +++ b/node_modules/utif2/UTIF.d.ts @@ -0,0 +1,72 @@ +// Type definitions for utif 4.0.1 +// Project: https://github.com/photopea/UTIF.js +// Definitions by: Jan Pesa +// Naveen Kumar Sangi +// Massimiliano Caniparoli +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import 'node'; + +export as namespace UTIF; + +export type TiffTag = string[] | number[]; + +/** + * Each IFD is an object, keys are "tXYZ" (XYZ is a TIFF tag number), values are values of these tags. + * You can get the the dimension (and other properties, "metadata") of the image without decompressing pixel data. + * For more information on what each tag means, refer https://github.com/photopea/UTIF.js/blob/master/UTIF.js#L742 or TIFF 6 specification. + */ +// tslint:disable-next-line:interface-name +export interface IFD { + [property: string]: TiffTag | number | Uint8Array; + data: Uint8Array; + width: number; + height: number; +} + +/** + * Returns an array of "IFDs" (image file directories). + * + * @param buffer A Buffer or ArrayBuffer containing TIFF or EXIF data. + */ +export function decode(buffer: Buffer | ArrayBuffer): IFD[]; + +/** + * If there is an image inside the IFD, it is decoded and three new properties are added to the IFD: width, height and data. + * Note: TIFF files may have various number of channels and various color depth. The interpretation of data depends on many tags (see the TIFF 6 specification). + * + * @param buffer A Buffer or ArrayBuffer containing TIFF or EXIF data + * @param ifd The element of the output of UTIF.decode() + */ +export function decodeImage(buffer: Buffer | ArrayBuffer, ifd: IFD): void; + +/** + * Returns Uint8Array of the image in RGBA format, 8 bits per channel (ready to use in context2d.putImageData() etc.) + * + * @param ifd An image file directory + */ +export function toRGBA8(ifd: IFD): Uint8Array; + +/** + * Returns an ArrayBuffer of the binary TIFF file. + * Note: No compression available right now. + * + * @param rgba A Uint8Array containing RGBA pixel data. + * @param w Width of the image. + * @param h Height of the image. + * @param metadata [optional] The image file directory which should be encoded. + */ +export function encodeImage(rgba: Uint8Array, w: number, h: number, metadata?: IFD): ArrayBuffer; + +/** + * Returns ArrayBuffer of binary data which can be used to encode EXIF data. + * + * @param ifds The array of IFDs (image file directories) to be encoded. + */ +export function encode(ifds: IFD[]): ArrayBuffer; + +/** + * Replaces all Image elements in the document with Canvas elements. + * The attributes "id", "class" and "style" will be copied from the original Image to the new Canvas. + */ +export function replaceIMG(): void; \ No newline at end of file diff --git a/node_modules/utif2/UTIF.js b/node_modules/utif2/UTIF.js new file mode 100644 index 00000000..2836c86d --- /dev/null +++ b/node_modules/utif2/UTIF.js @@ -0,0 +1,1649 @@ + + + + +;(function(){ + var UTIF = {}; + + // Make available for import by `require()` + if (typeof module == "object") {module.exports = UTIF;} + else {self.UTIF = UTIF;} + + var pako = (typeof require === "function") ? require("pako") : self.pako; + + function log() { if (typeof process=="undefined" || process.env.NODE_ENV=="development") console.log.apply(console, arguments); } + + (function(UTIF, pako){ + + // Following lines add a JPEG decoder to UTIF.JpegDecoder + (function(){"use strict";var W=function a1(){function W(p){this.message="JPEG error: "+p}W.prototype=new Error;W.prototype.name="JpegError";W.constructor=W;return W}(),ak=function ag(){var p=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,ac=799,ah=3406,ao=2276,ar=1567,ai=3784,s=5793,ad=2896;function ak(Q){if(Q==null)Q={};if(Q.w==null)Q.w=-1;this.V=Q.n;this.N=Q.w}function a5(Q,h){var f=0,G=[],n,E,a=16,F;while(a>0&&!Q[a-1]){a--}G.push({children:[],index:0});var C=G[0];for(n=0;n0){C=G.pop()}C.index++;G.push(C);while(G.length<=n){G.push(F={children:[],index:0});C.children[C.index]=F.children;C=F}f++}if(n+10){V--;return J>>V&1}J=Q[h++];if(J===255){var I=Q[h++];if(I){if(I===220&&d){h+=2;var l=Z(Q,h);h+=2;if(l>0&&l!==f.s){throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",l)}}else if(I===217){if(d){var M=q*8; + if(M>0&&M>>7}function u(I){var l=I;while(!0){l=l[Y()];switch(typeof l){case"number":return l;case"object":continue}throw new W("invalid huffman sequence")}}function m(I){var e=0;while(I>0){e=e<<1|Y();I--}return e}function j(I){if(I===1){return Y()===1?1:-1}var e=m(I);if(e>=1<>4;if(i===0){if(A<15){break}N+=16;continue}N+=A;var o=p[N];X.D[I+o]=j(i);N++}}function $(X,I){var l=u(X.J),M=l===0?0:j(l)<0){r--;return}var N=E,l=a;while(N<=l){var M=u(X.i),S=M&15,i=M>>4;if(S===0){if(i<15){r=m(i)+(1<>4;if(S===0){if(M<15){r=m(M)+(1<0){for(O=0;O0?"unexpected":"excessive";h=k.offset}if(k.M>=65488&&k.M<=65495){h+=2}else{break}}return h-z}function al(Q,h,f){var G=Q.$,n=Q.D,E,a,C,F,d,T,U,z,J,V,Y,u,m,j,v,$,b;if(!G){throw new W("missing required Quantization Table.")}for(var r=0;r<64;r+=8){J=n[h+r];V=n[h+r+1];Y=n[h+r+2];u=n[h+r+3];m=n[h+r+4];j=n[h+r+5];v=n[h+r+6];$=n[h+r+7];J*=G[r];if((V|Y|u|m|j|v|$)===0){b=s*J+512>>10;f[r]=b;f[r+1]=b;f[r+2]=b;f[r+3]=b;f[r+4]=b;f[r+5]=b;f[r+6]=b;f[r+7]=b;continue}V*=G[r+1];Y*=G[r+2];u*=G[r+3];m*=G[r+4];j*=G[r+5];v*=G[r+6];$*=G[r+7];E=s*J+128>>8;a=s*m+128>>8;C=Y;F=v;d=ad*(V-$)+128>>8;z=ad*(V+$)+128>>8; + T=u<<4;U=j<<4;E=E+a+1>>1;a=E-a;b=C*ai+F*ar+128>>8;C=C*ar-F*ai+128>>8;F=b;d=d+U+1>>1;U=d-U;z=z+T+1>>1;T=z-T;E=E+F+1>>1;F=E-F;a=a+C+1>>1;C=a-C;b=d*ao+z*ah+2048>>12;d=d*ah-z*ao+2048>>12;z=b;b=T*ac+U*t+2048>>12;T=T*t-U*ac+2048>>12;U=b;f[r]=E+z;f[r+7]=E-z;f[r+1]=a+U;f[r+6]=a-U;f[r+2]=C+T;f[r+5]=C-T;f[r+3]=F+d;f[r+4]=F-d}for(var P=0;P<8;++P){J=f[P];V=f[P+8];Y=f[P+16];u=f[P+24];m=f[P+32];j=f[P+40];v=f[P+48];$=f[P+56];if((V|Y|u|m|j|v|$)===0){b=s*J+8192>>14;if(b<-2040){b=0}else if(b>=2024){b=255}else{b=b+2056>>4}n[h+P]=b;n[h+P+8]=b;n[h+P+16]=b;n[h+P+24]=b;n[h+P+32]=b;n[h+P+40]=b;n[h+P+48]=b;n[h+P+56]=b;continue}E=s*J+2048>>12;a=s*m+2048>>12;C=Y;F=v;d=ad*(V-$)+2048>>12;z=ad*(V+$)+2048>>12;T=u;U=j;E=(E+a+1>>1)+4112;a=E-a;b=C*ai+F*ar+2048>>12;C=C*ar-F*ai+2048>>12;F=b;d=d+U+1>>1;U=d-U;z=z+T+1>>1;T=z-T;E=E+F+1>>1;F=E-F;a=a+C+1>>1;C=a-C;b=d*ao+z*ah+2048>>12;d=d*ah-z*ao+2048>>12;z=b; + b=T*ac+U*t+2048>>12;T=T*t-U*ac+2048>>12;U=b;J=E+z;$=E-z;V=a+U;v=a-U;Y=C+T;j=C-T;u=F+d;m=F-d;if(J<16){J=0}else if(J>=4080){J=255}else{J>>=4}if(V<16){V=0}else if(V>=4080){V=255}else{V>>=4}if(Y<16){Y=0}else if(Y>=4080){Y=255}else{Y>>=4}if(u<16){u=0}else if(u>=4080){u=255}else{u>>=4}if(m<16){m=0}else if(m>=4080){m=255}else{m>>=4}if(j<16){j=0}else if(j>=4080){j=255}else{j>>=4}if(v<16){v=0}else if(v>=4080){v=255}else{v>>=4}if($<16){$=0}else if($>=4080){$=255}else{$>>=4}n[h+P]=J; + n[h+P+8]=V;n[h+P+16]=Y;n[h+P+24]=u;n[h+P+32]=m;n[h+P+40]=j;n[h+P+48]=v;n[h+P+56]=$}}function a0(Q,h){var f=h.P,G=h.c,n=new Int16Array(64);for(var E=0;E=G){return null}var E=Z(Q,h);if(E>=65472&&E<=65534){return{u:null,M:E,offset:h}}var a=Z(Q,n);while(!(a>=65472&&a<=65534)){if(++n>=G){return null}a=Z(Q,n)}return{u:E.toString(16),M:a,offset:n}}ak.prototype={parse(Q,h){if(h==null)h={}; + var f=h.F,E=0,a=null,C=null,F,d,T=0;function G(){var o=Z(Q,E);E+=2;var B=E+o-2,V=an(Q,B,E);if(V&&V.u){B=V.offset}var ab=Q.subarray(E,B);E+=ab.length;return ab}function n(F){var o=Math.ceil(F.o/8/F.X),B=Math.ceil(F.s/8/F.B);for(var Y=0;Y>4===0){for(u=0;u<64;u++){b=p[u];P[b]=Q[E++]}}else if(r>>4===1){for(u=0;u<64;u++){b=p[u];P[b]=Z(Q,E);E+=2}}else{throw new W("DQT - invalid table spec")}U[r&15]=P}break;case 65472:case 65473:case 65474:if(F){throw new W("Only single frame JPEGs supported")}E+=2;F={};F.G=V===65473;F.Z=V===65474;F.precision=Q[E++];var D=Z(Q,E),a4,q=0,H=0;E+=2;F.s=f||D;F.o=Z(Q,E);E+=2;F.W=[];F._={};var a8=Q[E++];for(Y=0;Y>4,y=Q[E+1]&15;if(q>4===0?J:z)[_&15]=a5(N,K)}break;case 65501:E+=2;d=Z(Q,E);E+=2;break;case 65498:var x=++T===1&&!f,R;E+=2;var k=Q[E++],g=[];for(Y=0;Y>4];R.i=z[a6&15];g.push(R)}var I=Q[E++],l=Q[E++],M=Q[E++];try{var S=a7(Q,E,F,g,d,I,l,M>>4,M&15,x);E+=S}catch(ex){if(ex instanceof DNLMarkerError){return this.parse(Q,{F:ex.s})}else if(ex instanceof EOIMarkerError){break markerLoop}throw ex}break;case 65500:E+=4;break;case 65535:if(Q[E]!==255){E--}break;default:var i=an(Q,E-2,E-3);if(i&&i.u){E=i.offset;break}if(E>=Q.length-1){break markerLoop}throw new W("JpegImage.parse - unknown marker: "+V.toString(16))}V=Z(Q,E);E+=2}this.width=F.o;this.height=F.s;this.g=a;this.b=C;this.W=[];for(Y=0;Y>8)+P[J+1]}}}return v},get f(){if(this.b){return!!this.b.a}if(this.p===3){if(this.N===0){return!1}else if(this.W[0].index===82&&this.W[1].index===71&&this.W[2].index===66){return!1}return!0}if(this.N===1){return!0}return!1},z:function aj(Q){var h,f,G; + for(var n=0,E=Q.length;n4){throw new W("Unsupported color mode")}var E=this.Y(h,f,n);if(this.p===1&&G){var a=E.length,C=new Uint8ClampedArray(a*3),F=0;for(var d=0;d>24}function Z(p,t){return p[t]<<8|p[t+1]}function am(p,t){return(p[t]<<24|p[t+1]<<16|p[t+2]<<8|p[t+3])>>>0}UTIF.JpegDecoder=ak}()); + + //UTIF.JpegDecoder = PDFJS.JpegImage; + + + UTIF.encodeImage = function(rgba, w, h, metadata) + { + var idf = { "t256":[w], "t257":[h], "t258":[8,8,8,8], "t259":[1], "t262":[2], "t273":[1000], // strips offset + "t277":[4], "t278":[h], /* rows per strip */ "t279":[w*h*4], // strip byte counts + "t282":[[72,1]], "t283":[[72,1]], "t284":[1], "t286":[[0,1]], "t287":[[0,1]], "t296":[1], "t305": ["Photopea (UTIF.js)"], "t338":[1] + }; + if (metadata) for (var i in metadata) idf[i] = metadata[i]; + + var prfx = new Uint8Array(UTIF.encode([idf])); + var img = new Uint8Array(rgba); + var data = new Uint8Array(1000+w*h*4); + for(var i=0; i probably not an image + img.isLE = id=="II"; + img.width = img["t256"][0]; //delete img["t256"]; + img.height = img["t257"][0]; //delete img["t257"]; + + var cmpr = img["t259"] ? img["t259"][0] : 1; //delete img["t259"]; + var fo = img["t266"] ? img["t266"][0] : 1; //delete img["t266"]; + if(img["t284"] && img["t284"][0]==2) log("PlanarConfiguration 2 should not be used!"); + if(cmpr==7 && img["t258"] && img["t258"].length>3) img["t258"]=img["t258"].slice(0,3); + + var spp = img["t277"]?img["t277"][0]:1; + var bps = img["t258"]?img["t258"][0]:1; + var bipp = bps*spp; // bits per pixel + /* + var bipp; // bits per pixel + if(img["t258"]) bipp = Math.min(32,img["t258"][0])*img["t258"].length; + else bipp = (img["t277"]?img["t277"][0]:1); + */ + // Some .NEF files have t258==14, even though they use 16 bits per pixel + if(cmpr==1 && img["t279"]!=null && img["t278"] && img["t262"][0]==32803) { + bipp = Math.round((img["t279"][0]*8)/(img.width*img["t278"][0])); + } + if(img["t50885"] && img["t50885"][0]==4) bipp = img["t258"][0]*3; // RAW_CANON_40D_SRAW_V103.CR2 + var bipl = Math.ceil(img.width*bipp/8)*8; + var soff = img["t273"]; if(soff==null || img["t322"]) soff = img["t324"]; + var bcnt = img["t279"]; if(cmpr==1 && soff.length==1) bcnt = [img.height*(bipl>>>3)]; if(bcnt==null || img["t322"]) bcnt = img["t325"]; + //bcnt[0] = Math.min(bcnt[0], data.length); // Hasselblad, "RAW_HASSELBLAD_H3D39II.3FR" + var bytes = new Uint8Array(img.height*(bipl>>>3)), bilen = 0; + + if(img["t322"]!=null) // tiled + { + var tw = img["t322"][0], th = img["t323"][0]; + var tx = Math.floor((img.width + tw - 1) / tw); + var ty = Math.floor((img.height + th - 1) / th); + var tbuff = new Uint8Array(Math.ceil(tw*th*bipp/8)|0); + console.log("====", tx,ty); + for(var y=0; y>>3, bpl = Math.ceil(bps*noc*w/8); + + // convert to Little Endian /* + if(bps==16 && !img.isLE && img["t33422"]==null) // not DNG + for(var y=0; y>>8)&255; + } + else if(noc==3) for(var j= 3; j> 3 ^ 0x3ff0; + return (buffer[byte] | buffer[byte + 1] << 8) >> (vpos & 7) & ~((-1) << bits); + } + } + // Raw Format 6 + function getBufferDataRW6(i) { + return buffer[vpos + 15 - i]; + } + function readPageRW6() { + bytes[0] = (getBufferDataRW6(0) << 6) | (getBufferDataRW6(1) >> 2); // 14 bit + bytes[1] = (((getBufferDataRW6(1) & 0x3) << 12) | (getBufferDataRW6(2) << 4) | (getBufferDataRW6(3) >> 4)) & 0x3fff; + bytes[2] = (getBufferDataRW6(3) >> 2) & 0x3; + bytes[3] = ((getBufferDataRW6(3) & 0x3) << 8) | getBufferDataRW6(4); + bytes[4] = (getBufferDataRW6(5) << 2) | (getBufferDataRW6(6) >> 6); + bytes[5] = ((getBufferDataRW6(6) & 0x3f) << 4) | (getBufferDataRW6(7) >> 4); + bytes[6] = (getBufferDataRW6(7) >> 2) & 0x3; + bytes[7] = ((getBufferDataRW6(7) & 0x3) << 8) | getBufferDataRW6(8); + bytes[8] = ((getBufferDataRW6(9) << 2) & 0x3fc) | (getBufferDataRW6(10) >> 6); + bytes[9] = ((getBufferDataRW6(10) << 4) | (getBufferDataRW6(11) >> 4)) & 0x3ff; + bytes[10] = (getBufferDataRW6(11) >> 2) & 0x3; + bytes[11] = ((getBufferDataRW6(11) & 0x3) << 8) | getBufferDataRW6(12); + bytes[12] = (((getBufferDataRW6(13) << 2) & 0x3fc) | getBufferDataRW6(14) >> 6) & 0x3ff; + bytes[13] = ((getBufferDataRW6(14) << 4) | (getBufferDataRW6(15) >> 4)) & 0x3ff; + vpos += 16; + byte = 0; + } + function readPageRw6_bps12() { + bytes[0] = (getBufferDataRW6(0) << 4) | (getBufferDataRW6(1) >> 4); + bytes[1] = (((getBufferDataRW6(1) & 0xf) << 8) | (getBufferDataRW6(2))) & 0xfff; + bytes[2] = (getBufferDataRW6(3) >> 6) & 0x3; + bytes[3] = ((getBufferDataRW6(3) & 0x3f) << 2) | (getBufferDataRW6(4) >> 6); + bytes[4] = ((getBufferDataRW6(4) & 0x3f) << 2) | (getBufferDataRW6(5) >> 6); + bytes[5] = ((getBufferDataRW6(5) & 0x3f) << 2) | (getBufferDataRW6(6) >> 6); + bytes[6] = (getBufferDataRW6(6) >> 4) & 0x3; + bytes[7] = ((getBufferDataRW6(6) & 0xf) << 4) | (getBufferDataRW6(7) >> 4); + bytes[8] = ((getBufferDataRW6(7) & 0xf) << 4) | (getBufferDataRW6(8) >> 4); + bytes[9] = ((getBufferDataRW6(8) & 0xf) << 4) | (getBufferDataRW6(9) >> 4); + bytes[10] = (getBufferDataRW6(9) >> 2) & 0x3; + bytes[11] = ((getBufferDataRW6(9) & 0x3) << 6) | (getBufferDataRW6(10) >> 2); + bytes[12] = ((getBufferDataRW6(10) & 0x3) << 6) | (getBufferDataRW6(11) >> 2); + bytes[13] = ((getBufferDataRW6(11) & 0x3) << 6) | (getBufferDataRW6(12) >> 2); + bytes[14] = getBufferDataRW6(12) & 0x3; + bytes[15] = getBufferDataRW6(13); + bytes[16] = getBufferDataRW6(14); + bytes[17] = getBufferDataRW6(15); + + vpos += 16; + byte = 0; + } + // Main loop + function resetPredNonzeros(){ + pred[0]=0; pred[1]=0; + nonz[0]=0; nonz[1]=0; + } + if (RW2_Format == 7) { + throw RW2_Format; + + // Skatch of version 7 + /* + var pixels_per_block = bitsPerSample == 14 ? 9 : 10; + rowbytes = 0|(rawWidth / pixels_per_block * 16); + for (row = 0; row < rawHeight - 15; row += 16) { + var rowstoread = Math.min(16, rawHeight - row); + var readlen = rowbytes*rowstoread; + buffer = new Uint8Array(image.slice(bidx, bidx+readlen)); + vpos = 0; + bidx += readlen; + i = 0; + for (crow = 0; crow < rowstoread; crow++) { + idx = (row + crow) * rawWidth; + for (col = 0; col <= rawWidth - pixels_per_block; col += pixels_per_block) { + for(j=0; j < pixels_per_block; j++) bytes[j] = buffer[i++]; + if (bitsPerSample == 12) { + result[idx ] = ((bytes[1] & 0xF) << 8) + bytes[0]; + result[idx + 1] = 16 * bytes[2] + (bytes[1] >> 4); + result[idx + 2] = ((bytes[4] & 0xF) << 8) + bytes[3]; + result[idx + 3] = 16 * bytes[5] + (bytes[4] >> 4); + result[idx + 4] = ((bytes[7] & 0xF) << 8) + bytes[6]; + result[idx + 5] = 16 * bytes[8] + (bytes[7] >> 4); + result[idx + 6] = ((bytes[10] & 0xF) << 8) + bytes[9]; + result[idx + 7] = 16 * bytes[11] + (bytes[10] >> 4); + result[idx + 8] = ((bytes[13] & 0xF) << 8) + bytes[12]; + result[idx + 9] = 16 * bytes[14] + (bytes[13] >> 4); + } else if (bitsPerSample == 14) { + result[idx] = bytes[0] + ((bytes[1] & 0x3F) << 8); + result[idx + 1] = (bytes[1] >> 6) + 4 * (bytes[2]) + ((bytes[3] & 0xF) << 10); + result[idx + 2] = (bytes[3] >> 4) + 16 * (bytes[4]) + ((bytes[5] & 3) << 12); + result[idx + 3] = ((bytes[5] & 0xFC) >> 2) + (bytes[6] << 6); + result[idx + 4] = bytes[7] + ((bytes[8] & 0x3F) << 8); + result[idx + 5] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 0xF) << 10); + result[idx + 6] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12); + result[idx + 7] = ((bytes[12] & 0xFC) >> 2) + (bytes[13] << 6); + result[idx + 8] = bytes[14] + ((bytes[15] & 0x3F) << 8); + } + } + } + } + */ + } + else if(RW2_Format == 6) { + var is12bit = bitsPerSample == 12, + readPageRw6Fn = is12bit ? readPageRw6_bps12 : readPageRW6, + pixelsPerBlock = is12bit ? 14 : 11, + pixelbase0 = is12bit ? 0x80 : 0x200, + pixelbase_compare = is12bit ? 0x800 : 0x2000, + spix_compare = is12bit ? 0x3fff : 0xffff, + pixel_mask = is12bit ? 0xfff : 0x3fff, + blocksperrow = rawWidth / pixelsPerBlock, + rowbytes = blocksperrow * 16, + bufferSize = is12bit ? 18 : 14; + + for (row = 0; row < rawHeight - 15; row += 16) { + var rowstoread = Math.min(16, rawHeight - row); + var readlen = rowbytes*rowstoread; + buffer = new Uint8Array(img_buffer, off+bidx, readlen);//new Uint8Array(image.slice(bidx, bidx+readlen)); + vpos = 0; + bidx += readlen; + for (crow = 0, col = 0; crow < rowstoread; crow++, col = 0) { + idx = (row + crow) * rawWidth; + for (var rblock = 0; rblock < blocksperrow; rblock++) { + readPageRw6Fn(); + resetPredNonzeros(); + sh=0; pixel_base=0; + for (i = 0; i < pixelsPerBlock; i++){ + isOdd = i & 1; + if (i % 3 == 2) { + var base = byte < bufferSize ? bytes[byte++] : 0; + if (base == 3) base = 4; + pixel_base = pixelbase0 << base; + sh = 1 << base; + } + var epixel = byte < bufferSize ? bytes[byte++] : 0; + if (pred[isOdd]) { + epixel *= sh; + if (pixel_base < pixelbase_compare && nonz[isOdd] > pixel_base) + epixel += nonz[isOdd] - pixel_base; + nonz[isOdd] = epixel; + } else { + pred[isOdd] = epixel; + if (epixel) + nonz[isOdd] = epixel; + else + epixel = nonz[isOdd]; + } + result[idx + col++] = (epixel - 0xf) <= spix_compare ? (epixel - 0xf) & spix_compare : ((epixel + 0x7ffffff1) >> 0x1f) & pixel_mask; + } + } + } + } + } + else if (RW2_Format == 5) { + var blockSize = bitsPerSample == 12 ? 10 : 9; + for (row = 0; row < rawHeight; row++) { + for (col = 0; col < rawWidth; col+=blockSize) { + getDataRaw(0); + // Tuhle podminku pouziva i RW2_Format 7 + if (bitsPerSample == 12) { + result[idx++] = ((bytes[1] & 0xF) << 8) + bytes[0]; + result[idx++] = 16 * bytes[2] + (bytes[1] >> 4); + result[idx++] = ((bytes[4] & 0xF) << 8) + bytes[3]; + result[idx++] = 16 * bytes[5] + (bytes[4] >> 4); + result[idx++] = ((bytes[7] & 0xF) << 8) + bytes[6]; + result[idx++] = 16 * bytes[8] + (bytes[7] >> 4); + result[idx++] = ((bytes[10] & 0xF) << 8) + bytes[9]; + result[idx++] = 16 * bytes[11] + (bytes[10] >> 4); + result[idx++] = ((bytes[13] & 0xF) << 8) + bytes[12]; + result[idx++] = 16 * bytes[14] + (bytes[13] >> 4); + } else if (bitsPerSample == 14) { + result[idx++] = bytes[0] + ((bytes[1] & 0x3F) << 8); + result[idx++] = (bytes[1] >> 6) + 4 * (bytes[2]) + ((bytes[3] & 0xF) << 10); + result[idx++] = (bytes[3] >> 4) + 16 * (bytes[4]) + ((bytes[5] & 3) << 12); + result[idx++] = ((bytes[5] & 0xFC) >> 2) + (bytes[6] << 6); + result[idx++] = bytes[7] + ((bytes[8] & 0x3F) << 8); + result[idx++] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 0xF) << 10); + result[idx++] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12); + result[idx++] = ((bytes[12] & 0xFC) >> 2) + (bytes[13] << 6); + result[idx++] = bytes[14] + ((bytes[15] & 0x3F) << 8); + } + } + } + //console.log(result[1000000 - 1]) + } else if(RW2_Format == 4) { + for (row = 0; row < rawHeight; row++){ + for(col = 0; col < rawWidth; col++){ + i = col % 14; + isOdd = i & 1; + if (i==0) resetPredNonzeros(); + if (i%3 == 2) + sh = 4 >> (3 - getDataRaw(2)); + if (nonz[isOdd]) { + j = getDataRaw(8); + if(j != 0){ + pred[isOdd] -= 0x80 << sh; + if (pred[isOdd] < 0 || sh == 4) + pred[isOdd] &= ~((-1) << sh); + pred[isOdd] += j << sh; + } + } else { + nonz[isOdd] = getDataRaw(8); + if(nonz[isOdd] || i > 11) + pred[isOdd] = nonz[isOdd] << 4 | getDataRaw(4); + } + result[idx++] = pred[col & 1]; + } + } + } + else throw RW2_Format; + } + + + UTIF.decode._decodeVC5 = function(){var x=[1,0,1,0,2,2,1,1,3,7,1,2,5,25,1,3,6,48,1,4,6,54,1,5,7,111,1,8,7,99,1,6,7,105,12,0,7,107,1,7,8,209,20,0,8,212,1,9,8,220,1,10,9,393,1,11,9,394,32,0,9,416,1,12,9,427,1,13,10,887,1,18,10,784,1,14,10,790,1,15,10,835,60,0,10,852,1,16,10,885,1,17,11,1571,1,19,11,1668,1,20,11,1669,100,0,11,1707,1,21,11,1772,1,22,12,3547,1,29,12,3164,1,24,12,3166,1,25,12,3140,1,23,12,3413,1,26,12,3537,1,27,12,3539,1,28,13,7093,1,35,13,6283,1,30,13,6331,1,31,13,6335,180,0,13,6824,1,32,13,7072,1,33,13,7077,320,0,13,7076,1,34,14,12565,1,36,14,12661,1,37,14,12669,1,38,14,13651,1,39,14,14184,1,40,15,28295,1,46,15,28371,1,47,15,25320,1,42,15,25336,1,43,15,25128,1,41,15,27300,1,44,15,28293,1,45,16,50259,1,48,16,50643,1,49,16,50675,1,50,16,56740,1,53,16,56584,1,51,16,56588,1,52,17,113483,1,61,17,113482,1,60,17,101285,1,55,17,101349,1,56,17,109205,1,57,17,109207,1,58,17,100516,1,54,17,113171,1,59,18,202568,1,62,18,202696,1,63,18,218408,1,64,18,218412,1,65,18,226340,1,66,18,226356,1,67,18,226358,1,68,19,402068,1,69,19,405138,1,70,19,405394,1,71,19,436818,1,72,19,436826,1,73,19,452714,1,75,19,452718,1,76,19,452682,1,74,20,804138,1,77,20,810279,1,78,20,810790,1,79,20,873638,1,80,20,873654,1,81,20,905366,1,82,20,905430,1,83,20,905438,1,84,21,1608278,1,85,21,1620557,1,86,21,1621582,1,87,21,1621583,1,88,21,1747310,1,89,21,1810734,1,90,21,1810735,1,91,21,1810863,1,92,21,1810879,1,93,22,3621725,1,99,22,3621757,1,100,22,3241112,1,94,22,3494556,1,95,22,3494557,1,96,22,3494622,1,97,22,3494623,1,98,23,6482227,1,102,23,6433117,1,101,23,6989117,1,103,23,6989119,1,105,23,6989118,1,104,23,7243449,1,106,23,7243512,1,107,24,13978233,1,111,24,12964453,1,109,24,12866232,1,108,24,14486897,1,113,24,13978232,1,110,24,14486896,1,112,24,14487026,1,114,24,14487027,1,115,25,25732598,1,225,25,25732597,1,189,25,25732596,1,188,25,25732595,1,203,25,25732594,1,202,25,25732593,1,197,25,25732592,1,207,25,25732591,1,169,25,25732590,1,223,25,25732589,1,159,25,25732522,1,235,25,25732579,1,152,25,25732575,1,192,25,25732489,1,179,25,25732573,1,201,25,25732472,1,172,25,25732576,1,149,25,25732488,1,178,25,25732566,1,120,25,25732571,1,219,25,25732577,1,150,25,25732487,1,127,25,25732506,1,211,25,25732548,1,125,25,25732588,1,158,25,25732486,1,247,25,25732467,1,238,25,25732508,1,163,25,25732552,1,228,25,25732603,1,183,25,25732513,1,217,25,25732587,1,168,25,25732520,1,122,25,25732484,1,128,25,25732562,1,249,25,25732505,1,187,25,25732504,1,186,25,25732483,1,136,25,25928905,1,181,25,25732560,1,255,25,25732500,1,230,25,25732482,1,135,25,25732555,1,233,25,25732568,1,222,25,25732583,1,145,25,25732481,1,134,25,25732586,1,167,25,25732521,1,248,25,25732518,1,209,25,25732480,1,243,25,25732512,1,216,25,25732509,1,164,25,25732547,1,140,25,25732479,1,157,25,25732544,1,239,25,25732574,1,191,25,25732564,1,251,25,25732478,1,156,25,25732546,1,139,25,25732498,1,242,25,25732557,1,133,25,25732477,1,162,25,25732515,1,213,25,25732584,1,165,25,25732514,1,212,25,25732476,1,227,25,25732494,1,198,25,25732531,1,236,25,25732530,1,234,25,25732529,1,117,25,25732528,1,215,25,25732527,1,124,25,25732526,1,123,25,25732525,1,254,25,25732524,1,253,25,25732523,1,148,25,25732570,1,218,25,25732580,1,146,25,25732581,1,147,25,25732569,1,224,25,25732533,1,143,25,25732540,1,184,25,25732541,1,185,25,25732585,1,166,25,25732556,1,132,25,25732485,1,129,25,25732563,1,250,25,25732578,1,151,25,25732501,1,119,25,25732502,1,193,25,25732536,1,176,25,25732496,1,245,25,25732553,1,229,25,25732516,1,206,25,25732582,1,144,25,25732517,1,208,25,25732558,1,137,25,25732543,1,241,25,25732466,1,237,25,25732507,1,190,25,25732542,1,240,25,25732551,1,131,25,25732554,1,232,25,25732565,1,252,25,25732475,1,171,25,25732493,1,205,25,25732492,1,204,25,25732491,1,118,25,25732490,1,214,25,25928904,1,180,25,25732549,1,126,25,25732602,1,182,25,25732539,1,175,25,25732545,1,141,25,25732559,1,138,25,25732537,1,177,25,25732534,1,153,25,25732503,1,194,25,25732606,1,160,25,25732567,1,121,25,25732538,1,174,25,25732497,1,246,25,25732550,1,130,25,25732572,1,200,25,25732474,1,170,25,25732511,1,221,25,25732601,1,196,25,25732532,1,142,25,25732519,1,210,25,25732495,1,199,25,25732605,1,155,25,25732535,1,154,25,25732499,1,244,25,25732510,1,220,25,25732600,1,195,25,25732607,1,161,25,25732604,1,231,25,25732473,1,173,25,25732599,1,226,26,51465122,1,116,26,51465123,0,1],o,C,k,P=[3,3,3,3,2,2,2,1,1,1],V=24576,ar=16384,H=8192,az=ar|H; + function d(t){var E=t[1],h=t[0][E>>>3]>>>7-(E&7)&1;t[1]++;return h}function ag(t,E){if(o==null){o={}; + for(var h=0;h>>1}return t}function A(t,E){return t>>E}function O(t,E,h,L,g,n){E[h]=A(A(11*t[g]-4*t[g+n]+t[g+n+n]+4,3)+t[L],1); + E[h+n]=A(A(5*t[g]+4*t[g+n]-t[g+n+n]+4,3)-t[L],1)}function J(t,E,h,L,g,n){var W=t[g-n]-t[g+n],j=t[g],$=t[L]; + E[h]=A(A(W+4,3)+j+$,1);E[h+n]=A(A(-W+4,3)+j-$,1)}function y(t,E,h,L,g,n){E[h]=A(A(5*t[g]+4*t[g-n]-t[g-n-n]+4,3)+t[L],1); + E[h+n]=A(A(11*t[g]-4*t[g-n]+t[g-n-n]+4,3)-t[L],1)}function q(t){t=t<0?0:t>4095?4095:t;t=k[t]>>>2;return t}function av(t,E,h,L,g,n){L=new Uint16Array(L.buffer); + var W=Date.now(),j=UTIF._binBE,$=E+h,r,u,X,I,ax,a3,R,ai,aa,ap,ah,ae,aD,al,i,aE,T,B;E+=4;var a5=n[0]==1; + while(E<$){var S=j.readShort(t,E),s=j.readUshort(t,E+2);E+=4;if(S==12)r=s;else if(S==20)u=s;else if(S==21)X=s; + else if(S==48)I=s;else if(S==53)ax=s;else if(S==35)a3=s;else if(S==62)R=s;else if(S==101)ai=s;else if(S==109)aa=s; + else if(S==84)ap=s;else if(S==106)ah=s;else if(S==107)ae=s;else if(S==108)aD=s;else if(S==102)al=s;else if(S==104)i=s; + else if(S==105)aE=s;else{var F=S<0?-S:S,D=F&65280,_=0;if(F&az){if(F&H){_=s&65535;_+=(F&255)<<16}else{_=s&65535}}if((F&V)==V){if(T==null){T=[]; + for(var M=0;M<4;M++)T[M]=new Int16Array((u>>>1)*(X>>>1));B=new Int16Array((u>>>1)*(X>>>1));C=new Int16Array(1024); + for(var M=0;M<1024;M++){var aG=M-512,p=Math.abs(aG),r=Math.floor(768*p*p*p/(255*255*255))+p;C[M]=Math.sign(aG)*r}k=new Uint16Array(4096); + var aA=(1<<16)-1;for(var M=0;M<4096;M++){var at=M,a1=aA*(Math.pow(113,at/4095)-1)/112;k[M]=Math.min(a1,aA)}}var w=T[R],v=m(u,1+P[I]),N=m(X,1+P[I]); + if(I==0){for(var b=0;b>>1)+G]=t[c]<<8|t[c+1]}}else{var a7=[t,E*8],a4=[],ay=0,aw=v*N,f=[0,0],Q=0,s=0; + while(ay0){a4[ay++]=s;Q--}}var l=(I-1)%3,aF=l!=1?v:0,a2=l!=0?N:0; + for(var b=0;b>>1)+aF,au=b*v;for(var G=0;G>>1,an=v*2,a9=N*2; + for(var b=0;b>14-K*2&3;var a6=aC[aB];if(a6!=0)for(var b=0;b>>1)*(u>>>1)+(G>>>1),z=a8[c],ao=ab[c]-2048,ak=aq[c]-2048,ad=as[c]-2048,aj=(ao<<1)+z,a0=(ak<<1)+z,aH=z+ad,am=z-ad; + if(a5){L[U]=q(aH);L[U+1]=q(a0);L[U+u]=q(aj);L[U+u+1]=q(am)}else{L[U]=q(aj);L[U+1]=q(aH);L[U+u]=q(am); + L[U+u+1]=q(a0)}}}E+=_*4}else if(F==16388){E+=_*4}else if(D==8192||D==8448||D==9216){}else throw F.toString(16)}}console.log(Date.now()-W)}return av}() + + + + UTIF.decode._decodeLogLuv32 = function(img, data, off, len, tgt, toff) { + var w = img.width, qw=w*4; + var io = 0, out = new Uint8Array(qw); + + while(io>> (tab[i] >>> 8); + for(var c=0; c>>4); tgt[toff+i+1]=(b0<<4)|(b2>>>4); tgt[toff+i+2]=(b2<<4)|(b1>>>4); } + return; + } + + var pix = new Uint16Array(16); + var row, col, val, max, min, imax, imin, sh, bit, i, dp; + + var data = new Uint8Array(raw_width+1); + for (row=0; row < height; row++) { + //fread (data, 1, raw_width, ifp); + for(var j=0; j>> 11); + imax = 0x0f & (val >>> 22); + imin = 0x0f & (val >>> 26); + for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); + for (bit=30, i=0; i < 16; i++) + if (i == imax) pix[i] = max; + else if (i == imin) pix[i] = min; + else { + pix[i] = ((bin.readUshort(data, dp+(bit >> 3)) >>> (bit & 7) & 0x7f) << sh) + min; + if (pix[i] > 0x7ff) pix[i] = 0x7ff; + bit += 7; + } + for (i=0; i < 16; i++, col+=2) { + //RAW(row,col) = curve[pix[i] << 1] >> 2; + var clr = pix[i]<<1; //clr = 0xffff; + UTIF.decode._putsF(tgt, (row*raw_width+col)*tiff_bps, clr<<(16-tiff_bps)); + } + col -= col & 1 ? 1:31; + } + } + } + + UTIF.decode._decodeNikon = function(img,imgs, data, off, src_length, tgt, toff) + { + var nikon_tree = [ + [ 0, 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ + 5,4,3,6,2,7,1,0,8,9,11,10,12 ], + [ 0, 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ + 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 ], + [ 0, 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ + 5,4,6,3,7,2,8,1,9,0,10,11,12 ], + [ 0, 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ + 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 ], + [ 0, 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ + 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 ], + [ 0, 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ + 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 ] ]; + + var raw_width = img["t256"][0], height=img["t257"][0], tiff_bps=img["t258"][0]; + + var tree = 0, split = 0; + var make_decoder = UTIF.decode._make_decoder; + var getbithuff = UTIF.decode._getbithuff; + + var mn = imgs[0].exifIFD.makerNote, md = mn["t150"]?mn["t150"]:mn["t140"], mdo=0; //console.log(mn,md); + //console.log(md[0].toString(16), md[1].toString(16), tiff_bps); + var ver0 = md[mdo++], ver1 = md[mdo++]; + if (ver0 == 0x49 || ver1 == 0x58) mdo+=2110; + if (ver0 == 0x46) tree = 2; + if (tiff_bps == 14) tree += 3; + + var vpred = [[0,0],[0,0]], bin=(img.isLE ? UTIF._binLE : UTIF._binBE); + for(var i=0; i<2; i++) for(var j=0; j<2; j++) { vpred[i][j] = bin.readShort(md,mdo); mdo+=2; } // not sure here ... [i][j] or [j][i] + //console.log(vpred); + + + var max = 1 << tiff_bps & 0x7fff, step=0; + var csize = bin.readShort(md,mdo); mdo+=2; + if (csize > 1) step = Math.floor(max / (csize-1)); + if (ver0 == 0x44 && ver1 == 0x20 && step > 0) split = bin.readShort(md,562); + + + var i; + var row, col; + var len, shl, diff; + var min_v = 0; + var hpred = [0,0]; + var huff = make_decoder(nikon_tree[tree]); + + //var g_input_offset=0, bitbuf=0, vbits=0, reset=0; + var prm = [off,0,0,0]; + //console.log(split); split = 170; + + for (min_v=row=0; row < height; row++) { + if (split && row == split) { + //free (huff); + huff = make_decoder (nikon_tree[tree+1]); + //max_v += (min_v = 16) << 1; + } + for (col=0; col < raw_width; col++) { + i = getbithuff(data,prm,huff[0],huff); + len = i & 15; + shl = i >>> 4; + diff = (((getbithuff(data,prm,len-shl,0) << 1) + 1) << shl) >>> 1; + if ((diff & (1 << (len-1))) == 0) + diff -= (1 << len) - (shl==0?1:0); + if (col < 2) hpred[col] = vpred[row & 1][col] += diff; + else hpred[col & 1] += diff; + + var clr = Math.min(Math.max(hpred[col & 1],0),(1<>>3); dt[o]|=val>>>16; dt[o+1]|=val>>>8; dt[o+2]|=val; } + + + UTIF.decode._getbithuff = function(data,prm,nbits, huff) { + var zero_after_ff = 0; + var get_byte = UTIF.decode._get_byte; + var c; + + var off=prm[0], bitbuf=prm[1], vbits=prm[2], reset=prm[3]; + + //if (nbits > 25) return 0; + //if (nbits < 0) return bitbuf = vbits = reset = 0; + if (nbits == 0 || vbits < 0) return 0; + while (!reset && vbits < nbits && (c = data[off++]) != -1 && + !(reset = zero_after_ff && c == 0xff && data[off++])) { + //console.log("byte read into c"); + bitbuf = (bitbuf << 8) + c; + vbits += 8; + } + c = (bitbuf << (32-vbits)) >>> (32-nbits); + if (huff) { + vbits -= huff[c+1] >>> 8; //console.log(c, huff[c]>>8); + c = huff[c+1]&255; + } else + vbits -= nbits; + if (vbits < 0) throw "e"; + + prm[0]=off; prm[1]=bitbuf; prm[2]=vbits; prm[3]=reset; + + return c; + } + + UTIF.decode._make_decoder = function(source) { + var max, len, h, i, j; + var huff = []; + + for (max=16; max!=0 && !source[max]; max--); + var si=17; + + huff[0] = max; + for (h=len=1; len <= max; len++) + for (i=0; i < source[len]; i++, ++si) + for (j=0; j < 1 << (max-len); j++) + if (h <= 1 << max) + huff[h++] = (len << 8) | source[si]; + return huff; + } + + UTIF.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff) + { + len = Math.min(len, data.length-off); + var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len); + + if (tables) { + var SOI = 216, EOI = 217, boff = 0; + for (var i=0; i<(tlen-1); i++) + { + // Skip EOI marker from JPEGTables + if (tables[i]==255 && tables[i+1]==EOI) break; + buff[boff++] = tables[i]; + } + + // Skip SOI marker from data + var byte1 = data[off], byte2 = data[off + 1]; + if (byte1!=255 || byte2!=SOI) + { + buff[boff++] = byte1; + buff[boff++] = byte2; + } + for (var i=2; i>>8); } + else for(var i=0; i>>8); tgt[toff+(i<<1)+1] = (out[i]&255); } + } + else if(bps==14 || bps==12 || bps==10) { // 4 * 14 == 56 == 7 * 8 + var rst = 16-bps; + for(var i=0; i 1); + } + + if(!isTiled) + { + if(data[off]==255 && data[off+1]==SOI) return { jpegOffset: off }; + if(jpgIchgFmt!=null) + { + if(data[off+jifoff]==255 && data[off+jifoff+1]==SOI) joff = off+jifoff; + else log("JPEGInterchangeFormat does not point to SOI"); + + if(jpgIchgFmtLen==null) log("JPEGInterchangeFormatLength field is missing"); + else if(jifoff >= soff || (jifoff+jiflen) <= soff) log("JPEGInterchangeFormatLength field value is invalid"); + + if(joff != null) return { jpegOffset: joff }; + } + } + + if(ycbcrss!=null) { ssx = ycbcrss[0]; ssy = ycbcrss[1]; } + + if(jpgIchgFmt!=null) + if(jpgIchgFmtLen!=null) + if(jiflen >= 2 && (jifoff+jiflen) <= soff) + { + if(data[off+jifoff+jiflen-2]==255 && data[off+jifoff+jiflen-1]==SOI) tables = new Uint8Array(jiflen-2); + else tables = new Uint8Array(jiflen); + + for(i=0; i offset to first strip or tile"); + + if(tables == null) + { + var ooff = 0, out = []; + out[ooff++] = 255; out[ooff++] = SOI; + + var qtables = img["t519"]; + if(qtables==null) throw new Error("JPEGQTables tag is missing"); + for(i=0; i>> 8); out[ooff++] = nc & 255; + out[ooff++] = (i | (k << 4)); + for(j=0; j<16; j++) out[ooff++] = data[off+htables[i]+j]; + for(j=0; j>> 8) & 255; out[ooff++] = img.height & 255; + out[ooff++] = (img.width >>> 8) & 255; out[ooff++] = img.width & 255; + out[ooff++] = spp; + if(spp==1) { out[ooff++] = 1; out[ooff++] = 17; out[ooff++] = 0; } + else for(i=0; i<3; i++) + { + out[ooff++] = i + 1; + out[ooff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15)); + out[ooff++] = i; + } + + if(jpgresint!=null && jpgresint[0]!=0) + { + out[ooff++] = 255; out[ooff++] = DRI; out[ooff++] = 0; out[ooff++] = 4; + out[ooff++] = (jpgresint[0] >>> 8) & 255; + out[ooff++] = jpgresint[0] & 255; + } + + tables = new Uint8Array(out); + } + + var sofpos = -1; + i = 0; + while(i < (tables.length - 1)) { + if(tables[i]==255 && tables[i+1]==SOF0) { sofpos = i; break; } + i++; + } + + if(sofpos == -1) + { + var tmptab = new Uint8Array(tables.length + 10 + 3*spp); + tmptab.set(tables); + var tmpoff = tables.length; + sofpos = tables.length; + tables = tmptab; + + tables[tmpoff++] = 255; tables[tmpoff++] = SOF0; + tables[tmpoff++] = 0; tables[tmpoff++] = 8 + 3*spp; tables[tmpoff++] = 8; + tables[tmpoff++] = (img.height >>> 8) & 255; tables[tmpoff++] = img.height & 255; + tables[tmpoff++] = (img.width >>> 8) & 255; tables[tmpoff++] = img.width & 255; + tables[tmpoff++] = spp; + if(spp==1) { tables[tmpoff++] = 1; tables[tmpoff++] = 17; tables[tmpoff++] = 0; } + else for(i=0; i<3; i++) + { + tables[tmpoff++] = i + 1; + tables[tmpoff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15)); + tables[tmpoff++] = i; + } + } + + if(data[soff]==255 && data[soff+1]==SOS) + { + var soslen = (data[soff+2]<<8) | data[soff+3]; + sosMarker = new Uint8Array(soslen+2); + sosMarker[0] = data[soff]; sosMarker[1] = data[soff+1]; sosMarker[2] = data[soff+2]; sosMarker[3] = data[soff+3]; + for(i=0; i<(soslen-2); i++) sosMarker[i+4] = data[soff+i+4]; + } + else + { + sosMarker = new Uint8Array(2 + 6 + 2*spp); + var sosoff = 0; + sosMarker[sosoff++] = 255; sosMarker[sosoff++] = SOS; + sosMarker[sosoff++] = 0; sosMarker[sosoff++] = 6 + 2*spp; sosMarker[sosoff++] = spp; + if(spp==1) { sosMarker[sosoff++] = 1; sosMarker[sosoff++] = 0; } + else for(i=0; i<3; i++) + { + sosMarker[sosoff++] = i+1; sosMarker[sosoff++] = (i << 4) | i; + } + sosMarker[sosoff++] = 0; sosMarker[sosoff++] = 63; sosMarker[sosoff++] = 0; + } + + return { jpegOffset: off, tables: tables, sosMarker: sosMarker, sofPosition: sofpos }; + } + + UTIF.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff) + { + var i, dlen, tlen, buff, buffoff; + var jpegData = UTIF.decode._decodeOldJPEGInit(img, data, off, len); + + if(jpegData.jpegOffset!=null) + { + dlen = off+len-jpegData.jpegOffset; + buff = new Uint8Array(dlen); + for(i=0; i>> 8) & 255; buff[jpegData.sofPosition+6] = img.height & 255; + buff[jpegData.sofPosition+7] = (img.width >>> 8) & 255; buff[jpegData.sofPosition+8] = img.width & 255; + + if(data[off]!=255 || data[off+1]!=SOS) + { + buff.set(jpegData.sosMarker, buffoff); + buffoff += sosMarker.length; + } + for(i=0; i=0 && n<128) for(var i=0; i< n+1; i++) { ta[toff]=sa[off]; toff++; off++; } + if(n>=-127 && n<0) { for(var i=0; i<-n+1; i++) { ta[toff]=sa[off]; toff++; } off++; } + } + return toff; + } + + UTIF.decode._decodeThunder = function(data, off, len, tgt, toff) + { + var d2 = [ 0, 1, 0, -1 ], d3 = [ 0, 1, 2, 3, 0, -3, -2, -1 ]; + var lim = off+len, qoff = toff*2, px = 0; + while(off>>6), n = (b&63); off++; + if(msk==3) { px=(n&15); tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } + if(msk==0) for(var i=0; i>>1] |= (px<<(4*(1-qoff&1))); qoff++; } + if(msk==2) for(var i=0; i<2; i++) { var d=(n>>>(3*(1-i)))&7; if(d!=4) { px+=d3[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } } + if(msk==1) for(var i=0; i<3; i++) { var d=(n>>>(2*(2-i)))&3; if(d!=2) { px+=d2[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } } + } + } + + UTIF.decode._dmap = { "1":0,"011":1,"000011":2,"0000011":3, "010":-1,"000010":-2,"0000010":-3 }; + UTIF.decode._lens = ( function() + { + var addKeys = function(lens, arr, i0, inc) { for(var i=0; i>>3)>>3]>>>(7-(boff&7)))&1; + if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1; + boff++; wrd+=bit; + if(mode=="H") + { + if(U._lens[clr][wrd]!=null) + { + var dl=U._lens[clr][wrd]; wrd=""; len+=dl; + if(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=""; } + } + } + else + { + if(wrd=="0001") { wrd=""; U._addNtimes(line,b2-a0,clr); a0=b2; } + if(wrd=="001" ) { wrd=""; mode="H"; toRead=2; } + if(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=""; clr=1-clr; } + } + if(line.length==w && mode=="") + { + U._writeBits(line, tgt, toff*8+y*bipl); + clr=0; y++; a0=0; + pline=U._makeDiff(line); line=[]; + } + //if(wrd.length>150) { log(wrd); break; throw "e"; } + } + } + + UTIF.decode._findDiff = function(line, x, clr) { for(var i=0; i=x && line[i+1]==clr) return line[i]; } + + UTIF.decode._makeDiff = function(line) + { + var out = []; if(line[0]==1) out.push(0,1); + for(var i=1; i>>3)>>3]>>>(7-(boff&7)))&1; + if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1; + boff++; wrd+=bit; + + len = U._lens[clr][wrd]; + if(len!=null) { + U._addNtimes(line,len,clr); wrd=""; + if(len<64) clr = 1-clr; + if(line.length==w) { U._writeBits(line, tgt, toff*8+y*bipl); line=[]; y++; clr=0; if((boff&7)!=0) boff+=8-(boff&7); if(len>=64) boff+=8; } + } + } + } + + UTIF.decode._decodeG3 = function(data, off, slen, tgt, toff, w, fo, twoDim) + { + var U = UTIF.decode, boff=off<<3, len=0, wrd=""; + var line=[], pline=[]; for(var i=0; i>>3)>>3]>>>(7-(boff&7)))&1; + if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1; + boff++; wrd+=bit; + + if(is1D) + { + if(U._lens[clr][wrd]!=null) + { + var dl=U._lens[clr][wrd]; wrd=""; len+=dl; + if(dl<64) { U._addNtimes(line,len,clr); clr=1-clr; len=0; } + } + } + else + { + if(mode=="H") + { + if(U._lens[clr][wrd]!=null) + { + var dl=U._lens[clr][wrd]; wrd=""; len+=dl; + if(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=""; } + } + } + else + { + if(wrd=="0001") { wrd=""; U._addNtimes(line,b2-a0,clr); a0=b2; } + if(wrd=="001" ) { wrd=""; mode="H"; toRead=2; } + if(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=""; clr=1-clr; } + } + } + if(wrd.endsWith("000000000001")) // needed for some files + { + if(y>=0) U._writeBits(line, tgt, toff*8+y*bipl); + if(twoDim) { + if(fo==1) is1D = ((data[boff>>>3]>>>(7-(boff&7)))&1)==1; + if(fo==2) is1D = ((data[boff>>>3]>>>( (boff&7)))&1)==1; + boff++; + } + //log("EOL",y, "next 1D:", is1D); + wrd=""; clr=0; y++; a0=0; + pline=U._makeDiff(line); line=[]; + } + } + if(line.length==w) U._writeBits(line, tgt, toff*8+y*bipl); + } + + UTIF.decode._addNtimes = function(arr, n, val) { for(var i=0; i>>3] |= (bits[i]<<(7-((boff+i)&7))); + } + + UTIF.decode._decodeLZW=UTIF.decode._decodeLZW=function(){var e,U,Z,u,K=0,V=0,g=0,N=0,O=function(){var S=e>>>3,A=U[S]<<16|U[S+1]<<8|U[S+2],j=A>>>24-(e&7)-V&(1<>>----------------"); + for(var i=0; idata.buffer.byteLength) num=data.buffer.byteLength-no; arr = new Uint8Array(data.buffer, no, num); } + if(type== 2) { var o0 = (num<5 ? offset-4 : voff), c=data[o0], len=Math.max(0, Math.min(num-1,data.length-o0)); + if(c<128 || len==0) arr.push( bin.readASCII(data, o0, len) ); + else arr = new Uint8Array(data.buffer, o0, len); } + if(type== 3) { for(var j=0; j4) { bin.writeUint(data, offset, eoff); toff=eoff; } + + if (type== 1 || type==7) { for(var i=0; i4) { dlen += (dlen&1); eoff += dlen; } + offset += 4; + } + return [offset, eoff]; + } + + UTIF.toRGBA8 = function(out, scl) + { + function gamma(x) { return x < 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1.0 / 2.4) - 0.055; } + + + var w = out.width, h = out.height, area = w*h, qarea = area*4, data = out.data; + var img = new Uint8Array(area*4); + //console.log(out); + // 0: WhiteIsZero, 1: BlackIsZero, 2: RGB, 3: Palette color, 4: Transparency mask, 5: CMYK + var intp = (out["t262"] ? out["t262"][0]: 2), bps = (out["t258"]?Math.min(32,out["t258"][0]):1); + if(out["t262"]==null && bps==1) intp=0; + + var smpls = out["t277"]?out["t277"][0] : (out["t258"]?out["t258"].length : [1,1,3,1,1,4,3][intp]); + var sfmt = out["t339"]?out["t339"][0] : null; if(intp==1 && bps==32 && sfmt!=3) throw "e"; // sample format + var bpl = Math.ceil(smpls*bps*w/8); + + //log("interpretation: ", intp, "smpls", smpls, "bps", bps, "sample format",sfmt, out); + + if(false) {} + else if(intp==0) + { + scl = 1/256; // "Photopeatest.tif" + for(var y=0; y>3)])>>(7- (i&7)))& 1; img[qi]=img[qi+1]=img[qi+2]=( 1-px)*255; img[qi+3]=255; } + if(bps== 4) for(var i=0; i>1)])>>(4-4*(i&1)))&15; img[qi]=img[qi+1]=img[qi+2]=(15-px)* 17; img[qi+3]=255; } + if(bps== 8) for(var i=0; i>3)])>>(7- (i&7)))&1; img[qi]=img[qi+1]=img[qi+2]=(px)*255; img[qi+3]=255; } + if(bps== 2) for(var i=0; i>2)])>>(6-2*(i&3)))&3; img[qi]=img[qi+1]=img[qi+2]=(px)* 85; img[qi+3]=255; } + if(bps== 8) for(var i=0; i>>2)+i, px=f32[o]; img[qi]=img[qi+1]=img[qi+2]= ~~(0.5+255*px); img[qi+3]=255; } + } + } + else if(intp==2) + { + if(bps== 8) + { + if(smpls==1) for(var i=0; i=4) for(var i=0; i1 && out["t338"] && out["t338"][0]!=0; + + for(var y=0; y>>3)]>>>(7- (x&7)))& 1; + else if(bps==2) mi=(data[dof+(x>>>2)]>>>(6-2*(x&3)))& 3; + else if(bps==4) mi=(data[dof+(x>>>1)]>>>(4-4*(x&1)))&15; + else if(bps==8) mi= data[dof+x*smpls]; + else throw bps; + img[qi]=(map[mi]>>8); img[qi+1]=(map[cn+mi]>>8); img[qi+2]=(map[cn+cn+mi]>>8); img[qi+3]=nexta ? data[dof+x*smpls+1] : 255; + } + } + else if(intp==5) + { + var gotAlpha = smpls>4 ? 1 : 0; + for(var i=0; i>>1); + var Y = data[si+(j&1)], Cb=data[si+2]-128, Cr=data[si+3]-128; + + var r = Y + ( (Cr >> 2) + (Cr >> 3) + (Cr >> 5) ) ; + var g = Y - ( (Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ( (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5)) ; + var b = Y + ( Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)) ; + + img[qi ]=Math.max(0,Math.min(255,r)); + img[qi+1]=Math.max(0,Math.min(255,g)); + img[qi+2]=Math.max(0,Math.min(255,b)); + img[qi+3]=255; + } + } + } + else if(intp==32845) { + + for(var y=0; yma) { ma=ar; page=img; } + } + UTIF.decodeImage(buff, page, ifds); + var rgba = UTIF.toRGBA8(page), w=page.width, h=page.height; + + var cnv = document.createElement("canvas"); cnv.width=w; cnv.height=h; + var ctx = cnv.getContext("2d"); + var imgd = new ImageData(new Uint8ClampedArray(rgba.buffer),w,h); + ctx.putImageData(imgd,0,0); + return cnv.toDataURL(); + } + + + UTIF._binBE = + { + nextZero : function(data, o) { while(data[o]!=0) o++; return o; }, + readUshort : function(buff, p) { return (buff[p]<< 8) | buff[p+1]; }, + readShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+1]; a[1]=buff[p+0]; return UTIF._binBE. i16[0]; }, + readInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE. i32[0]; }, + readUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE.ui32[0]; }, + readASCII : function(buff, p, l) { var s = ""; for(var i=0; i> 8)&255; buff[p+1] = n&255; }, + writeInt : function(buff, p, n) { var a=UTIF._binBE.ui8; UTIF._binBE.i32[0]=n; buff[p+3]=a[0]; buff[p+2]=a[1]; buff[p+1]=a[2]; buff[p+0]=a[3]; }, + writeUint : function(buff, p, n) { buff[p] = (n>>24)&255; buff[p+1] = (n>>16)&255; buff[p+2] = (n>>8)&255; buff[p+3] = (n>>0)&255; }, + writeASCII : function(buff, p, s) { for(var i = 0; i < s.length; i++) buff[p+i] = s.charCodeAt(i); }, + writeDouble: function(buff, p, n) + { + UTIF._binBE.fl64[0] = n; + for (var i = 0; i < 8; i++) buff[p + i] = UTIF._binBE.ui8[7 - i]; + } + } + UTIF._binBE.ui8 = new Uint8Array (8); + UTIF._binBE.i16 = new Int16Array (UTIF._binBE.ui8.buffer); + UTIF._binBE.i32 = new Int32Array (UTIF._binBE.ui8.buffer); + UTIF._binBE.ui32 = new Uint32Array (UTIF._binBE.ui8.buffer); + UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer); + UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer); + + UTIF._binLE = + { + nextZero : UTIF._binBE.nextZero, + readUshort : function(buff, p) { return (buff[p+1]<< 8) | buff[p]; }, + readShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; return UTIF._binBE. i16[0]; }, + readInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE. i32[0]; }, + readUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE.ui32[0]; }, + readASCII : UTIF._binBE.readASCII, + readFloat : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<4;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl32[0]; }, + readDouble : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<8;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl64[0]; }, + + writeUshort: function(buff, p, n) { buff[p] = (n)&255; buff[p+1] = (n>>8)&255; }, + writeInt : function(buff, p, n) { var a=UTIF._binBE.ui8; UTIF._binBE.i32[0]=n; buff[p+0]=a[0]; buff[p+1]=a[1]; buff[p+2]=a[2]; buff[p+3]=a[3]; }, + writeUint : function(buff, p, n) { buff[p] = (n>>>0)&255; buff[p+1] = (n>>>8)&255; buff[p+2] = (n>>>16)&255; buff[p+3] = (n>>>24)&255; }, + writeASCII : UTIF._binBE.writeASCII + } + UTIF._copyTile = function(tb, tw, th, b, w, h, xoff, yoff) + { + //log("copyTile", tw, th, w, h, xoff, yoff); + var xlim = Math.min(tw, w-xoff); + var ylim = Math.min(th, h-yoff); + for(var y=0; y>--s&1; + Y=I[Y+F]}E[w]=Y}}function z(h,V,I,f){if(h[V+3]!=255)return 0;if(I==0)return V;for(var w=0;w<2;w++){if(h[V+w]==0){h[V+w]=h.length; + h.push(0,0,f,255)}var x=z(h,h[V+w],I-1,f+1);if(x!=0)return x}return 0}function i(h){var V=h.b,I=h.f; + while(V<25&&h.a>(V.b-=h)&65535>>16-h}function g(h,V){var I=h[0],f=0,w=255,x=0;if(V.b<16)i(V);var T=V.f>>V.b-8&255; + f=h[1][T];w=I[f+3];V.b-=I[f+2];while(w==255){x=V.f>>--V.b&1;f=I[f+x];w=I[f+3]}return w}function P(h,V){if(h<32768>>16-V)h+=-(1<>4,J&15]}}else if(Y==65476){var a3=O+F-2;while(O>>4];x[v[0]]=v.slice(1)}I=l();O+=2;break}else if(Y==65501){w=m()}else{O+=F-2}}var a4=f>8?Uint16Array:Uint8Array,$=new a4(s*_*E),M={b:0,f:0,c:I==8,a:O,data:b,d:b.length,e:w}; + if(M.c)a1($,_*E,M,G[0],s);else{var c=[],p=0,D=0;for(var t=0;tp)p=S; + if(K>D)D=K;c.push(S*K)}if(p!=1||D!=1){if(E!=3||c[1]!=1||c[2]!=1)throw"e";if(p!=2||D!=1&&D!=2)throw"e"; + var u=[],Z=0;for(var t=0;t>>1)*B+(S>>>1))*Z,y=(K&1)*2+(S&1); + $[q]=n[k+y];$[q+1]=n[k+4];$[q+2]=n[k+5]}else for(var S=0;S<_;S++){var q=(K*_+S)*E,k=(K*B+(S>>>1))*Z,y=S&1; + $[q]=n[k+y];$[q+1]=n[k+2];$[q+2]=n[k+3]}}}else{X($,_*E,M,G,E,s);if(w==0)j($,I,_,s,0,E,E,f);else{var U=Math.floor(w/_); + for(var K=0;K>>1);else if(V==6)Q=h[J]+(r-h[J-G]>>>1);else if(V==7)Q=r+h[J]>>>1;else throw V; + h[a]+=Q}}}}return C}(); + + + (function(){var G=0,F=1,i=2,b=3,J=4,N=5,E=6,s=7,c=8,T=9,a3=10,f=11,q=12,M=13,m=14,x=15,L=16,$=17,p=18; + function a5(t){var Z=UTIF._binBE.readUshort,u={b:Z(t,0),i:t[2],C:t[3],u:t[4],q:Z(t,5),k:Z(t,7),e:Z(t,9),l:Z(t,11),s:t[13],d:Z(t,14)}; + if(u.b!=18771||u.i>1||u.q<6||u.q%6||u.e<768||u.e%24||u.l!=768||u.k=u.l||u.s>16||u.s!=u.k/u.l||u.s!=Math.ceil(u.e/u.l)||u.d!=u.q/6||u.u!=12&&u.u!=14&&u.u!=16||u.C!=16&&u.C!=0){throw"Invalid data"}if(u.i==0){throw"Not implemented. We need this file!"}u.h=u.C==16; + u.m=(u.h?u.l*2/3:u.l>>>1)|0;u.A=u.m+2;u.f=64;u.g=(1<>>6);for(var e=0;e<3;e++){for(var Q=0; + Q<41;Q++){Z[e][Q]=[u,1]}}return Z}function a4(t){for(var Z=-1,u=0;!u;Z++){u=t[t.j]>>>7-t.a&1;t.a++;t.a&=7; + if(!t.a)t.j++}return Z}function K(t,Z){var u=0,e=8-t.a,Q=t.j,V=t.a;if(Z){if(Z>=e){do{u<<=e;Z-=e;u|=t[t.j]&(1<=8)}if(Z){u<<=Z;e-=Z;u|=t[t.j]>>>e&(1<n&&C>>2;if(o){w[X]=h;return}l=Z.t*Z.c[t.g+Y-H]+Z.c[t.g+g-Y]}else{h=Y>g&&Y>P||Y>>2:A+v>>>1; + l=Z.t*Z.c[t.g+Y-g]+Z.c[t.g+g-A]}R=y(l);var W=a4(u);if(W>>1):a>>>1; + O[R][0]+=y(a);if(O[R][1]==t.f){O[R][0]>>>=1;O[R][1]>>>=1}O[R][1]++;h=l<0?h-a:h+a;if(t.i){if(h<0)h+=Z.w; + else if(h>t.g)h-=Z.w}w[X]=h>=0?Math.min(h,t.g):0}function U(t,Z,u){var e=t[0].length;for(var Q=Z;Q<=u; + Q++){t[Q][0]=t[Q-1][1];t[Q][e-1]=t[Q-1][e-2]}}function B(t){U(t,s,q);U(t,i,J);U(t,x,$)}function _(t,Z,u,e,Q,V,O,o,X,k,j,I,a){var l=0,R=1,w=QJ; + while(R8){r(t,Z,u,e,Q,R,o[X]);r(t,Z,u,e,V,R,o[X]);R+=2}}B(e)}function a8(t,Z,u,e,Q,V){_(t,Z,u,e,i,s,Q,V,0,0,1,0,8); + _(t,Z,u,e,c,x,Q,V,1,0,1,0,8);_(t,Z,u,e,b,T,Q,V,2,1,0,3,0);_(t,Z,u,e,a3,L,Q,V,0,0,0,3,2);_(t,Z,u,e,J,f,Q,V,1,0,0,3,2); + _(t,Z,u,e,q,$,Q,V,2,1,0,3,0)}function a9(t,Z,u,e,Q,V){var O=V.length,o=t.l;if(Q+1==t.s)o=t.e-Q*t.l;var X=6*t.e*e+Q*t.l; + for(var k=0;k<6;k++){for(var j=0;j>>1)}else if(I==2){a=x+(k>>>1)}else{a=s+k}var l=t.h?(j*2/3&2147483646|j%3&1)+(j%3>>>1):j>>>1; + Z[X+j]=u[a][l+1]}X+=t.e}}UTIF._decompressRAF=function(t,Z){var u=a5(t),e=a7(t,u),Q=a2(u),V=new Int16Array(u.e*u.q); + if(Z==null){Z=u.h?[[1,1,0,1,1,2],[1,1,2,1,1,0],[2,0,1,0,2,1],[1,1,2,1,1,0],[1,1,0,1,1,2],[0,2,1,2,0,1]]:[[0,1],[3,2]]}var O=[[G,b],[F,J],[N,f],[E,q],[M,L],[m,$]],o=[]; + for(var X=0;X= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/node_modules/whatwg-url/lib/utils.js b/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 00000000..a562009c --- /dev/null +++ b/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,20 @@ +"use strict"; + +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; + +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); + +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; + +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; + diff --git a/node_modules/whatwg-url/node_modules/webidl-conversions/LICENSE.md b/node_modules/whatwg-url/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 00000000..d4a994f5 --- /dev/null +++ b/node_modules/whatwg-url/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +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. + +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/whatwg-url/node_modules/webidl-conversions/README.md b/node_modules/whatwg-url/node_modules/webidl-conversions/README.md new file mode 100644 index 00000000..3657890a --- /dev/null +++ b/node_modules/whatwg-url/node_modules/webidl-conversions/README.md @@ -0,0 +1,53 @@ +# WebIDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a WebIDL operation declared as + +```webidl +void doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +## Status + +All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! + +I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. + +We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't Use This + +Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. diff --git a/node_modules/whatwg-url/node_modules/webidl-conversions/lib/index.js b/node_modules/whatwg-url/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 00000000..c5153a3a --- /dev/null +++ b/node_modules/whatwg-url/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,189 @@ +"use strict"; + +var conversions = {}; +module.exports = conversions; + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); + } +} + +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + + return function(V, opts) { + if (!opts) opts = {}; + + let x = +V; + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + + return x; + } + + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); + + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; + } + } + + return x; + } +} + +conversions["void"] = function () { + return undefined; +}; + +conversions["boolean"] = function (val) { + return !!val; +}; + +conversions["byte"] = createNumberConversion(8, { unsigned: false }); +conversions["octet"] = createNumberConversion(8, { unsigned: true }); + +conversions["short"] = createNumberConversion(16, { unsigned: false }); +conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + +conversions["long"] = createNumberConversion(32, { unsigned: false }); +conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + +conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + +conversions["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); + } + + return x; +}; + +conversions["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); + } + + return x; +}; + +// not quite valid, but good enough for JS +conversions["float"] = conversions["double"]; +conversions["unrestricted float"] = conversions["unrestricted double"]; + +conversions["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + return String(V); +}; + +conversions["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); + } + } + + return x; +}; + +conversions["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + } + + return U.join(''); +}; + +conversions["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; diff --git a/node_modules/whatwg-url/node_modules/webidl-conversions/package.json b/node_modules/whatwg-url/node_modules/webidl-conversions/package.json new file mode 100644 index 00000000..c31bc074 --- /dev/null +++ b/node_modules/whatwg-url/node_modules/webidl-conversions/package.json @@ -0,0 +1,23 @@ +{ + "name": "webidl-conversions", + "version": "3.0.1", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "test": "mocha test/*.js" + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "mocha": "^1.21.4" + } +} diff --git a/node_modules/whatwg-url/package.json b/node_modules/whatwg-url/package.json new file mode 100644 index 00000000..fce35ae7 --- /dev/null +++ b/node_modules/whatwg-url/package.json @@ -0,0 +1,32 @@ +{ + "name": "whatwg-url", + "version": "5.0.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "lib/public-api.js", + "files": [ + "lib/" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + }, + "devDependencies": { + "eslint": "^2.6.0", + "istanbul": "~0.4.3", + "mocha": "^2.2.4", + "recast": "~0.10.29", + "request": "^2.55.0", + "webidl2js": "^3.0.2" + }, + "scripts": { + "build": "node scripts/transform.js && node scripts/convert-idl.js", + "coverage": "istanbul cover node_modules/mocha/bin/_mocha", + "lint": "eslint .", + "prepublish": "npm run build", + "pretest": "node scripts/get-latest-platform-tests.js && npm run build", + "test": "mocha" + } +} diff --git a/node_modules/xhr/CONTRIBUTING.md b/node_modules/xhr/CONTRIBUTING.md new file mode 100644 index 00000000..3d4053b5 --- /dev/null +++ b/node_modules/xhr/CONTRIBUTING.md @@ -0,0 +1,27 @@ +# XHR is an OPEN Open Source Project + +----------------------------------------- + +## What? + +Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project. + +## Rules + +There are a few basic ground-rules for contributors: + +1. **No `--force` pushes** or modifying the Git history in any way. +1. **Non-master branches** ought to be used for ongoing work. +1. **External API changes and significant modifications** ought to be subject to an **internal pull-request** to solicit feedback from other contributors. +1. Internal pull-requests to solicit feedback are *encouraged* for any other non-trivial contribution but left to the discretion of the contributor. +1. Contributors should attempt to adhere to the prevailing code-style. + +## Releases + +Declaring formal releases remains the prerogative of the project maintainer. + +## Changes to this arrangement + +This is an experiment and feedback is welcome! This document may also be subject to pull-requests or changes by contributors where you believe you have something valuable to add or change. + +----------------------------------------- diff --git a/node_modules/xhr/LICENCE b/node_modules/xhr/LICENCE new file mode 100644 index 00000000..a23e08a8 --- /dev/null +++ b/node_modules/xhr/LICENCE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/xhr/README.md b/node_modules/xhr/README.md new file mode 100644 index 00000000..1cb2ba76 --- /dev/null +++ b/node_modules/xhr/README.md @@ -0,0 +1,255 @@ +# xhr + +[![Join the chat at https://gitter.im/naugtur-xhr/Lobby](https://badges.gitter.im/naugtur-xhr/Lobby.svg)](https://gitter.im/naugtur-xhr/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + + +A small XMLHttpRequest wrapper. Designed for use with [browserify](http://browserify.org/), [webpack](https://webpack.github.io/) etc. + +API is a subset of [request](https://github.com/request/request) so you can write code that works in both node.js and the browser by using `require('request')` in your code and telling your browser bundler to load `xhr` instead of `request`. + +For browserify, add a [browser](https://github.com/substack/node-browserify#browser-field) field to your `package.json`: + +``` +"browser": { + "request": "xhr" +} +``` + +For webpack, add a [resolve.alias](http://webpack.github.io/docs/configuration.html#resolve-alias) field to your configuration: + +``` +"resolve": { + "alias": { + "request$": "xhr" + } +} +``` + +Browser support: IE8+ and everything else. + +## Installation + +``` +npm install xhr +``` + +## Example + +```js +var xhr = require("xhr") + +xhr({ + method: "post", + body: someJSONString, + uri: "/foo", + headers: { + "Content-Type": "application/json" + } +}, function (err, resp, body) { + // check resp.statusCode +}) +``` + +## `var req = xhr(options, callback)` + +```js +type XhrOptions = String | { + useXDR: Boolean?, + sync: Boolean?, + uri: String, + url: String, + method: String?, + timeout: Number?, + headers: Object?, + body: String? | Object?, + json: Boolean? | Object?, + username: String?, + password: String?, + withCredentials: Boolean?, + responseType: String?, + beforeSend: Function? +} +xhr := (XhrOptions, Callback) => Request +``` +the returned object is either an [`XMLHttpRequest`][3] instance + or an [`XDomainRequest`][4] instance (if on IE8/IE9 && + `options.useXDR` is set to `true`) + +Your callback will be called once with the arguments + ( [`Error`][5], `response` , `body` ) where the response is an object: +```js +{ + body: Object||String, + statusCode: Number, + method: String, + headers: {}, + url: String, + rawRequest: xhr +} +``` + - `body`: HTTP response body - [`XMLHttpRequest.response`][6], [`XMLHttpRequest.responseText`][7] or + [`XMLHttpRequest.responseXML`][8] depending on the request type. + - `rawRequest`: Original [`XMLHttpRequest`][3] instance + or [`XDomainRequest`][4] instance (if on IE8/IE9 && + `options.useXDR` is set to `true`) + - `headers`: A collection of headers where keys are header names converted to lowercase + + +Your callback will be called with an [`Error`][5] if there is an error in the browser that prevents sending the request. +A HTTP 500 response is not going to cause an error to be returned. + +## Other signatures + +* `var req = xhr(url, callback)` - +a simple string instead of the options. In this case, a GET request will be made to that url. + +* `var req = xhr(url, options, callback)` - +the above may also be called with the standard set of options. + +### Convience methods +* `var req = xhr.{post, put, patch, del, head, get}(url, callback)` +* `var req = xhr.{post, put, patch, del, head, get}(options, callback)` +* `var req = xhr.{post, put, patch, del, head, get}(url, options, callback)` + +The `xhr` module has convience functions attached that will make requests with the given method. +Each function is named after its method, with the exception of `DELETE` which is called `xhr.del` for compatibility. + +The method shorthands may be combined with the url-first form of `xhr` for succinct and descriptive requests. For example, + +```js +xhr.post('/post-to-me', function(err, resp) { + console.log(resp.body) +}) +``` + +or + +```js +xhr.del('/delete-me', { headers: { my: 'auth' } }, function (err, resp) { + console.log(resp.statusCode); +}) +``` + +## Options + +### `options.method` + +Specify the method the [`XMLHttpRequest`][3] should be opened + with. Passed to [`XMLHttpRequest.open`][2]. Defaults to "GET" + +### `options.useXDR` + +Specify whether this is a cross origin (CORS) request for IE<10. + Switches IE to use [`XDomainRequest`][4] instead of `XMLHttpRequest`. + Ignored in other browsers. + +Note that headers cannot be set on an XDomainRequest instance. + +### `options.sync` + +Specify whether this is a synchrounous request. Note that when + this is true the callback will be called synchronously. In + most cases this option should not be used. Only use if you + know what you are doing! + +### `options.body` + +Pass in body to be send across the [`XMLHttpRequest`][3]. + Generally should be a string. But anything that's valid as + a parameter to [`XMLHttpRequest.send`][1] should work (Buffer for file, etc.). + +If `options.json` is `true`, then this must be a JSON-serializable object. `options.body` is passed to `JSON.stringify` and sent. + +### `options.uri` or `options.url` + +The uri to send a request to. Passed to [`XMLHttpRequest.open`][2]. `options.url` and `options.uri` are aliases for each other. + +### `options.headers` + +An object of headers that should be set on the request. The + key, value pair is passed to [`XMLHttpRequest.setRequestHeader`][9] + +### `options.timeout` + +Number of miliseconds to wait for response. Defaults to 0 (no timeout). Ignored when `options.sync` is true. + +### `options.json` + +Set to `true` to send request as `application/json` (see `options.body`) and parse response from JSON. + +For backwards compatibility `options.json` can also be a valid JSON-serializable value to be sent to the server. Additionally the response body is still parsed as JSON + +For sending booleans as JSON body see FAQ + +### `options.withCredentials` + +Specify whether user credentials are to be included in a cross-origin + request. Sets [`XMLHttpRequest.withCredentials`][10]. Defaults to false. + +A wildcard `*` cannot be used in the `Access-Control-Allow-Origin` header when `withCredentials` is true. + The header needs to specify your origin explicitly or browser will abort the request. + +### `options.responseType` + +Determines the data type of the `response`. Sets [`XMLHttpRequest.responseType`][11]. For example, a `responseType` of `document` will return a parsed `Document` object as the `response.body` for an XML resource. + +### `options.beforeSend` + +A function being called right before the `send` method of the `XMLHttpRequest` or `XDomainRequest` instance is called. The `XMLHttpRequest` or `XDomainRequest` instance is passed as an argument. + +### `options.xhr` + +Pass an `XMLHttpRequest` object (or something that acts like one) to use instead of constructing a new one using the `XMLHttpRequest` or `XDomainRequest` constructors. Useful for testing. + +## FAQ + +- Why is my server's JSON response not parsed? I returned the right content-type. + - See `options.json` - you can set it to `true` on a GET request to tell `xhr` to parse the response body. + - Without `options.json` body is returned as-is (a string or when `responseType` is set and the browser supports it - a result of parsing JSON or XML) +- How do I send an object or array as POST body? + - `options.body` should be a string. You need to serialize your object before passing to `xhr` for sending. + - To serialize to JSON you can use + `options.json:true` with `options.body` for convenience - then `xhr` will do the serialization and set content-type accordingly. +- Where's stream API? `.pipe()` etc. + - Not implemented. You can't reasonably have that in the browser. +- Why can't I send `"true"` as body by passing it as `options.json` anymore? + - Accepting `true` as a value was a bug. Despite what `JSON.stringify` does, the string `"true"` is not valid JSON. If you're sending booleans as JSON, please consider wrapping them in an object or array to save yourself from more trouble in the future. To bring back the old behavior, hardcode `options.json` to `true` and set `options.body` to your boolean value. +- How do I add an `onprogress` listener? + - use `beforeSend` function for non-standard things that are browser specific. In this case: + ```js + xhr({ + ... + beforeSend: function(xhrObject){ + xhrObject.onprogress = function(){} + } + }) + ``` + +## Mocking Requests +You can override the constructor used to create new requests for testing. When you're making a new request: + +```js +xhr({ xhr: new MockXMLHttpRequest() }) +``` + +or you can override the constructors used to create requests at the module level: + +```js +xhr.XMLHttpRequest = MockXMLHttpRequest +xhr.XDomainRequest = MockXDomainRequest +``` + +## MIT Licenced + + [1]: http://xhr.spec.whatwg.org/#the-send()-method + [2]: http://xhr.spec.whatwg.org/#the-open()-method + [3]: http://xhr.spec.whatwg.org/#interface-xmlhttprequest + [4]: http://msdn.microsoft.com/en-us/library/ie/cc288060(v=vs.85).aspx + [5]: http://es5.github.com/#x15.11 + [6]: http://xhr.spec.whatwg.org/#the-response-attribute + [7]: http://xhr.spec.whatwg.org/#the-responsetext-attribute + [8]: http://xhr.spec.whatwg.org/#the-responsexml-attribute + [9]: http://xhr.spec.whatwg.org/#the-setrequestheader()-method + [10]: http://xhr.spec.whatwg.org/#the-withcredentials-attribute + [11]: https://xhr.spec.whatwg.org/#the-responsetype-attribute diff --git a/node_modules/xhr/index.d.ts b/node_modules/xhr/index.d.ts new file mode 100644 index 00000000..0de08c28 --- /dev/null +++ b/node_modules/xhr/index.d.ts @@ -0,0 +1,61 @@ +export type XhrCallback = ( + error: Error, + response: XhrResponse, + body: any +) => void; + +export interface XhrResponse { + body: Object | string; + statusCode: number; + method: string; + headers: XhrHeaders; + url: string; + rawRequest: XMLHttpRequest; +} + +export interface XhrHeaders { + [key: string]: string; +} + +export interface XhrBaseConfig { + useXDR?: boolean; + sync?: boolean; + method?: 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH'; + timeout?: number; + headers?: XhrHeaders; + body?: string | any; + json?: boolean; + username?: string; + password?: string; + withCredentials?: boolean; + responseType?: '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text'; + beforeSend?: (xhrObject: XMLHttpRequest) => void; + xhr?: XMLHttpRequest; +} + +export interface XhrUriConfig extends XhrBaseConfig { + uri: string; +} + +export interface XhrUrlConfig extends XhrBaseConfig { + url: string; +} + +export interface XhrInstance { + (options: XhrUriConfig | XhrUrlConfig, callback: XhrCallback): any; + (url: string, callback: XhrCallback): any; + (url: string, options: XhrBaseConfig, callback: XhrCallback): any; +} + +export interface XhrStatic extends XhrInstance { + del: XhrInstance; + get: XhrInstance; + head: XhrInstance; + patch: XhrInstance; + post: XhrInstance; + put: XhrInstance; +} + +declare const Xhr: XhrStatic; + +export default Xhr; diff --git a/node_modules/xhr/index.js b/node_modules/xhr/index.js new file mode 100644 index 00000000..1bc328f2 --- /dev/null +++ b/node_modules/xhr/index.js @@ -0,0 +1,247 @@ +"use strict"; +var window = require("global/window") +var isFunction = require("is-function") +var parseHeaders = require("parse-headers") +var xtend = require("xtend") + +module.exports = createXHR +// Allow use of default import syntax in TypeScript +module.exports.default = createXHR; +createXHR.XMLHttpRequest = window.XMLHttpRequest || noop +createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest + +forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) { + createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) { + options = initParams(uri, options, callback) + options.method = method.toUpperCase() + return _createXHR(options) + } +}) + +function forEachArray(array, iterator) { + for (var i = 0; i < array.length; i++) { + iterator(array[i]) + } +} + +function isEmpty(obj){ + for(var i in obj){ + if(obj.hasOwnProperty(i)) return false + } + return true +} + +function initParams(uri, options, callback) { + var params = uri + + if (isFunction(options)) { + callback = options + if (typeof uri === "string") { + params = {uri:uri} + } + } else { + params = xtend(options, {uri: uri}) + } + + params.callback = callback + return params +} + +function createXHR(uri, options, callback) { + options = initParams(uri, options, callback) + return _createXHR(options) +} + +function _createXHR(options) { + if(typeof options.callback === "undefined"){ + throw new Error("callback argument missing") + } + + var called = false + var callback = function cbOnce(err, response, body){ + if(!called){ + called = true + options.callback(err, response, body) + } + } + + function readystatechange() { + if (xhr.readyState === 4) { + setTimeout(loadFunc, 0) + } + } + + function getBody() { + // Chrome with requestType=blob throws errors arround when even testing access to responseText + var body = undefined + + if (xhr.response) { + body = xhr.response + } else { + body = xhr.responseText || getXml(xhr) + } + + if (isJson) { + try { + body = JSON.parse(body) + } catch (e) {} + } + + return body + } + + function errorFunc(evt) { + clearTimeout(timeoutTimer) + if(!(evt instanceof Error)){ + evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) + } + evt.statusCode = 0 + return callback(evt, failureResponse) + } + + // will load the data & process the response in a special response object + function loadFunc() { + if (aborted) return + var status + clearTimeout(timeoutTimer) + if(options.useXDR && xhr.status===undefined) { + //IE8 CORS GET successful response doesn't have a status field, but body is fine + status = 200 + } else { + status = (xhr.status === 1223 ? 204 : xhr.status) + } + var response = failureResponse + var err = null + + if (status !== 0){ + response = { + body: getBody(), + statusCode: status, + method: method, + headers: {}, + url: uri, + rawRequest: xhr + } + if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE + response.headers = parseHeaders(xhr.getAllResponseHeaders()) + } + } else { + err = new Error("Internal XMLHttpRequest Error") + } + return callback(err, response, response.body) + } + + var xhr = options.xhr || null + + if (!xhr) { + if (options.cors || options.useXDR) { + xhr = new createXHR.XDomainRequest() + }else{ + xhr = new createXHR.XMLHttpRequest() + } + } + + var key + var aborted + var uri = xhr.url = options.uri || options.url + var method = xhr.method = options.method || "GET" + var body = options.body || options.data + var headers = xhr.headers = options.headers || {} + var sync = !!options.sync + var isJson = false + var timeoutTimer + var failureResponse = { + body: undefined, + headers: {}, + statusCode: 0, + method: method, + url: uri, + rawRequest: xhr + } + + if ("json" in options && options.json !== false) { + isJson = true + headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user + if (method !== "GET" && method !== "HEAD") { + headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user + body = JSON.stringify(options.json === true ? body : options.json) + } + } + + xhr.onreadystatechange = readystatechange + xhr.onload = loadFunc + xhr.onerror = errorFunc + // IE9 must have onprogress be set to a unique function. + xhr.onprogress = function () { + // IE must die + } + xhr.onabort = function(){ + aborted = true; + } + xhr.ontimeout = errorFunc + xhr.open(method, uri, !sync, options.username, options.password) + //has to be after open + if(!sync) { + xhr.withCredentials = !!options.withCredentials + } + // Cannot set timeout with sync request + // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly + // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent + if (!sync && options.timeout > 0 ) { + timeoutTimer = setTimeout(function(){ + if (aborted) return + aborted = true//IE9 may still call readystatechange + xhr.abort("timeout") + var e = new Error("XMLHttpRequest timeout") + e.code = "ETIMEDOUT" + errorFunc(e) + }, options.timeout ) + } + + if (xhr.setRequestHeader) { + for(key in headers){ + if(headers.hasOwnProperty(key)){ + xhr.setRequestHeader(key, headers[key]) + } + } + } else if (options.headers && !isEmpty(options.headers)) { + throw new Error("Headers cannot be set on an XDomainRequest object") + } + + if ("responseType" in options) { + xhr.responseType = options.responseType + } + + if ("beforeSend" in options && + typeof options.beforeSend === "function" + ) { + options.beforeSend(xhr) + } + + // Microsoft Edge browser sends "undefined" when send is called with undefined value. + // XMLHttpRequest spec says to pass null as body to indicate no body + // See https://github.com/naugtur/xhr/issues/100. + xhr.send(body || null) + + return xhr + + +} + +function getXml(xhr) { + // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException" + // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML. + try { + if (xhr.responseType === "document") { + return xhr.responseXML + } + var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror" + if (xhr.responseType === "" && !firefoxBugTakenEffect) { + return xhr.responseXML + } + } catch (e) {} + + return null +} + +function noop() {} diff --git a/node_modules/xhr/package.json b/node_modules/xhr/package.json new file mode 100644 index 00000000..61c72ee6 --- /dev/null +++ b/node_modules/xhr/package.json @@ -0,0 +1,48 @@ +{ + "name": "xhr", + "version": "2.6.0", + "description": "small xhr abstraction", + "keywords": [ + "xhr", + "http", + "xmlhttprequest", + "xhr2", + "browserify" + ], + "author": "Raynos ", + "repository": "git://github.com/naugtur/xhr.git", + "main": "index", + "homepage": "https://github.com/naugtur/xhr", + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Zbyszek Tenerowicz", + "email": "naugtur@gmail.com" + } + ], + "bugs": { + "url": "https://github.com/naugtur/xhr/issues", + "email": "naugtur@gmail.com" + }, + "typings": "./index.d.ts", + "dependencies": { + "global": "~4.4.0", + "is-function": "^1.0.1", + "parse-headers": "^2.0.0", + "xtend": "^4.0.0" + }, + "devDependencies": { + "for-each": "^0.3.2", + "pre-commit": "1.2.2", + "run-browser": "naugtur/run-browser", + "tap-spec": "^4.0.2", + "tape": "^4.0.0" + }, + "license": "MIT", + "scripts": { + "test": "run-browser test/index.js -b -m test/mock-server.js | tap-spec", + "browser": "run-browser -m test/mock-server.js test/index.js" + } +} diff --git a/node_modules/xml-parse-from-string/LICENSE.md b/node_modules/xml-parse-from-string/LICENSE.md new file mode 100644 index 00000000..9b10ce2a --- /dev/null +++ b/node_modules/xml-parse-from-string/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) +Copyright (c) 2015 Jam3 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/xml-parse-from-string/README.md b/node_modules/xml-parse-from-string/README.md new file mode 100644 index 00000000..3fc7f962 --- /dev/null +++ b/node_modules/xml-parse-from-string/README.md @@ -0,0 +1,35 @@ +# xml-parse-from-string + +[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) + +A light browser wrapper around `DOMParser.parseFromString` for XML, with fallback for IE8 and other browsers. + +- attempts to use DOMParser with `"application/xml"` +- falls back to `ActiveXObject('Microsoft.XMLDOM')` +- then falls back to `createElement` / `innerHTML` + +```js +var parseXML = require('xml-parse-from-string') + +var str = '' +var doc = parseXML(str) +var tag = doc.getElementsByTagName('foobar')[0] + +console.log(tag.getAttribute('id')) // -> "blah" +``` + +Be wary of subtle differences between implementations, such as case-sensitivity in `attribute.nodeName`. + +PRs for Node version welcome. + +## Usage + +[![NPM](https://nodei.co/npm/xml-parse-from-string.png)](https://www.npmjs.com/package/xml-parse-from-string) + +#### `root = parse(str)` + +Parses the string as XML and returns the `root` element as a DOM element, so you can do operations similar to `document.getElementById`, `document.getElementsByTagName`, and so forth. + +## License + +MIT, see [LICENSE.md](http://github.com/Jam3/xml-parse-from-string/blob/master/LICENSE.md) for details. diff --git a/node_modules/xml-parse-from-string/index.js b/node_modules/xml-parse-from-string/index.js new file mode 100644 index 00000000..c045afab --- /dev/null +++ b/node_modules/xml-parse-from-string/index.js @@ -0,0 +1,27 @@ +module.exports = (function xmlparser() { + //common browsers + if (typeof self.DOMParser !== 'undefined') { + return function(str) { + var parser = new self.DOMParser() + return parser.parseFromString(str, 'application/xml') + } + } + + //IE8 fallback + if (typeof self.ActiveXObject !== 'undefined' + && new self.ActiveXObject('Microsoft.XMLDOM')) { + return function(str) { + var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM") + xmlDoc.async = "false" + xmlDoc.loadXML(str) + return xmlDoc + } + } + + //last resort fallback + return function(str) { + var div = document.createElement('div') + div.innerHTML = str + return div + } +})() diff --git a/node_modules/xml-parse-from-string/package.json b/node_modules/xml-parse-from-string/package.json new file mode 100644 index 00000000..2f8b61d4 --- /dev/null +++ b/node_modules/xml-parse-from-string/package.json @@ -0,0 +1,45 @@ +{ + "name": "xml-parse-from-string", + "version": "1.0.1", + "description": "DOMParser.parseFromString for XML with IE8 fallback", + "main": "index.js", + "license": "MIT", + "author": { + "name": "Matt DesLauriers", + "email": "dave.des@gmail.com", + "url": "https://github.com/mattdesl" + }, + "dependencies": {}, + "devDependencies": { + "brfs": "^1.4.0", + "browserify": "^9.0.3", + "faucet": "0.0.1", + "tape": "^3.5.0", + "testling": "^1.7.1" + }, + "scripts": { + "test": "browserify test.js -t brfs | testling | faucet" + }, + "keywords": [ + "ie8", + "fallback", + "dom", + "parser", + "DOMParser", + "xml", + "string", + "parse", + "browser", + "browserify", + "webpack", + "activeXObject" + ], + "repository": { + "type": "git", + "url": "git://github.com/Jam3/xml-parse-from-string.git" + }, + "homepage": "https://github.com/Jam3/xml-parse-from-string", + "bugs": { + "url": "https://github.com/Jam3/xml-parse-from-string/issues" + } +} diff --git a/node_modules/xtend/.jshintrc b/node_modules/xtend/.jshintrc new file mode 100644 index 00000000..77887b5f --- /dev/null +++ b/node_modules/xtend/.jshintrc @@ -0,0 +1,30 @@ +{ + "maxdepth": 4, + "maxstatements": 200, + "maxcomplexity": 12, + "maxlen": 80, + "maxparams": 5, + + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": false, + "noarg": true, + "noempty": true, + "nonew": true, + "undef": true, + "unused": "vars", + "trailing": true, + + "quotmark": true, + "expr": true, + "asi": true, + + "browser": false, + "esnext": true, + "devel": false, + "node": false, + "nonstandard": false, + + "predef": ["require", "module", "__dirname", "__filename"] +} diff --git a/node_modules/xtend/LICENSE b/node_modules/xtend/LICENSE new file mode 100644 index 00000000..0099f4f6 --- /dev/null +++ b/node_modules/xtend/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2012-2014 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/xtend/README.md b/node_modules/xtend/README.md new file mode 100644 index 00000000..4a2703cf --- /dev/null +++ b/node_modules/xtend/README.md @@ -0,0 +1,32 @@ +# xtend + +[![browser support][3]][4] + +[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) + +Extend like a boss + +xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence. + +## Examples + +```js +var extend = require("xtend") + +// extend returns a new object. Does not mutate arguments +var combination = extend({ + a: "a", + b: "c" +}, { + b: "b" +}) +// { a: "a", b: "b" } +``` + +## Stability status: Locked + +## MIT Licensed + + + [3]: http://ci.testling.com/Raynos/xtend.png + [4]: http://ci.testling.com/Raynos/xtend diff --git a/node_modules/xtend/immutable.js b/node_modules/xtend/immutable.js new file mode 100644 index 00000000..94889c9d --- /dev/null +++ b/node_modules/xtend/immutable.js @@ -0,0 +1,19 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/node_modules/xtend/mutable.js b/node_modules/xtend/mutable.js new file mode 100644 index 00000000..72debede --- /dev/null +++ b/node_modules/xtend/mutable.js @@ -0,0 +1,17 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/node_modules/xtend/package.json b/node_modules/xtend/package.json new file mode 100644 index 00000000..f7a39d10 --- /dev/null +++ b/node_modules/xtend/package.json @@ -0,0 +1,55 @@ +{ + "name": "xtend", + "version": "4.0.2", + "description": "extend like a boss", + "keywords": [ + "extend", + "merge", + "options", + "opts", + "object", + "array" + ], + "author": "Raynos ", + "repository": "git://github.com/Raynos/xtend.git", + "main": "immutable", + "scripts": { + "test": "node test" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~1.1.0" + }, + "homepage": "https://github.com/Raynos/xtend", + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Matt Esch" + } + ], + "bugs": { + "url": "https://github.com/Raynos/xtend/issues", + "email": "raynos2@gmail.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/7..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest" + ] + }, + "engines": { + "node": ">=0.4" + } +} diff --git a/node_modules/xtend/test.js b/node_modules/xtend/test.js new file mode 100644 index 00000000..b895b42b --- /dev/null +++ b/node_modules/xtend/test.js @@ -0,0 +1,103 @@ +var test = require("tape") +var extend = require("./") +var mutableExtend = require("./mutable") + +test("merge", function(assert) { + var a = { a: "foo" } + var b = { b: "bar" } + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("replace", function(assert) { + var a = { a: "foo" } + var b = { a: "bar" } + + assert.deepEqual(extend(a, b), { a: "bar" }) + assert.end() +}) + +test("undefined", function(assert) { + var a = { a: undefined } + var b = { b: "foo" } + + assert.deepEqual(extend(a, b), { a: undefined, b: "foo" }) + assert.deepEqual(extend(b, a), { a: undefined, b: "foo" }) + assert.end() +}) + +test("handle 0", function(assert) { + var a = { a: "default" } + var b = { a: 0 } + + assert.deepEqual(extend(a, b), { a: 0 }) + assert.deepEqual(extend(b, a), { a: "default" }) + assert.end() +}) + +test("is immutable", function (assert) { + var record = {} + + extend(record, { foo: "bar" }) + assert.equal(record.foo, undefined) + assert.end() +}) + +test("null as argument", function (assert) { + var a = { foo: "bar" } + var b = null + var c = void 0 + + assert.deepEqual(extend(b, a, c), { foo: "bar" }) + assert.end() +}) + +test("mutable", function (assert) { + var a = { foo: "bar" } + + mutableExtend(a, { bar: "baz" }) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("null prototype", function(assert) { + var a = { a: "foo" } + var b = Object.create(null) + b.b = "bar"; + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("null prototype mutable", function (assert) { + var a = { foo: "bar" } + var b = Object.create(null) + b.bar = "baz"; + + mutableExtend(a, b) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("prototype pollution", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + extend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) + +test("prototype pollution mutable", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + mutableExtend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) diff --git a/pad_icon.js b/pad_icon.js new file mode 100644 index 00000000..5ec29322 --- /dev/null +++ b/pad_icon.js @@ -0,0 +1,29 @@ +const fs = require('fs'); +const path = require('path'); + +// Fallback to Jimp if sharp is not available +try { + const Jimp = require('jimp'); + + async function padIconJimp() { + console.log('Padding icon using Jimp...'); + const img = await Jimp.read('Icon.png'); + // Scale down image to fit within 720x720 while maintaining aspect ratio + img.scaleToFit(720, 720); + + // Create a transparent 1080x1080 background + const bg = new Jimp(1080, 1080, 0x00000000); + + // Center the scaled image on the background + const x = (1080 - img.bitmap.width) / 2; + const y = (1080 - img.bitmap.height) / 2; + + bg.composite(img, x, y); + await bg.writeAsync('Icon-padded.png'); + console.log('Icon successfully padded to Icon-padded.png'); + } + + padIconJimp().catch(console.error); +} catch (e) { + console.log('Jimp not found. Please install it first using: npm install jimp --no-save'); +} diff --git a/src/screens/CameraScreen.tsx b/src/screens/CameraScreen.tsx index 12d29759..c8653af1 100644 --- a/src/screens/CameraScreen.tsx +++ b/src/screens/CameraScreen.tsx @@ -260,10 +260,15 @@ export default function CameraScreen({ // Final burst photo setBurstIndex(0); setBurstUris([]); - onBurstComplete(newUris); + // Short delay prevents Android expo-camera crash on immediate unmount + setTimeout(() => { + onBurstComplete(newUris); + }, 400); } else { // Single shot mode - onPhotoCaptured(capturedUri); + setTimeout(() => { + onPhotoCaptured(capturedUri); + }, 400); } } catch (error: any) { console.error('Capture failed:', error);