Compare commits

...

3 Commits

443 changed files with 2 additions and 223386 deletions

View File

@ -1,5 +1,5 @@
.DS_Store
node_modules
node_modules/
/dist
/admin/
# local env files
@ -36,6 +36,7 @@ pnpm-lock.yaml
!.yarn/sdks
!.yarn/versions
.pnp.*
.history
# Vab
public/video
@ -45,4 +46,3 @@ public/video
src/vab/styles/themes/red.scss
/src/vab/styles/themes/red-black.scss
/src/vab/styles/themes/red-white.scss
/.history

View File

@ -1,12 +0,0 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../detect-libc/bin/detect-libc.js" "$@"
else
exec node "$basedir/../detect-libc/bin/detect-libc.js" "$@"
fi

View File

@ -1,17 +0,0 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\detect-libc\bin\detect-libc.js" %*

View File

@ -1,28 +0,0 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../detect-libc/bin/detect-libc.js" $args
} else {
& "$basedir/node$exe" "$basedir/../detect-libc/bin/detect-libc.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../detect-libc/bin/detect-libc.js" $args
} else {
& "node$exe" "$basedir/../detect-libc/bin/detect-libc.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

View File

@ -1,12 +0,0 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../sass/sass.js" "$@"
else
exec node "$basedir/../sass/sass.js" "$@"
fi

View File

@ -1,17 +0,0 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sass\sass.js" %*

View File

@ -1,28 +0,0 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../sass/sass.js" $args
} else {
& "$basedir/node$exe" "$basedir/../sass/sass.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../sass/sass.js" $args
} else {
& "node$exe" "$basedir/../sass/sass.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

View File

@ -1,383 +0,0 @@
{
"name": "java-mall-app-shop-admin",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/@parcel/watcher": {
"version": "2.5.0",
"resolved": "https://mirrors.tencent.com/npm/@parcel/watcher/-/watcher-2.5.0.tgz",
"integrity": "sha512-i0GV1yJnm2n3Yq1qw6QrUrd/LI9bE8WEBOTtOkpCXHHdyN3TAGgqAK/DAT05z4fq2x04cARXt2pDmjWjL92iTQ==",
"dev": true,
"hasInstallScript": true,
"optional": true,
"dependencies": {
"detect-libc": "^1.0.3",
"is-glob": "^4.0.3",
"micromatch": "^4.0.5",
"node-addon-api": "^7.0.0"
},
"engines": {
"node": ">= 10.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
},
"optionalDependencies": {
"@parcel/watcher-android-arm64": "2.5.0",
"@parcel/watcher-darwin-arm64": "2.5.0",
"@parcel/watcher-darwin-x64": "2.5.0",
"@parcel/watcher-freebsd-x64": "2.5.0",
"@parcel/watcher-linux-arm-glibc": "2.5.0",
"@parcel/watcher-linux-arm-musl": "2.5.0",
"@parcel/watcher-linux-arm64-glibc": "2.5.0",
"@parcel/watcher-linux-arm64-musl": "2.5.0",
"@parcel/watcher-linux-x64-glibc": "2.5.0",
"@parcel/watcher-linux-x64-musl": "2.5.0",
"@parcel/watcher-win32-arm64": "2.5.0",
"@parcel/watcher-win32-ia32": "2.5.0",
"@parcel/watcher-win32-x64": "2.5.0"
}
},
"node_modules/@parcel/watcher-win32-x64": {
"version": "2.5.0",
"resolved": "https://mirrors.tencent.com/npm/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.0.tgz",
"integrity": "sha512-lPrxve92zEHdgeff3aiu4gDOIt4u7sJYha6wbdEZDCDUhtjTsOMiaJzG5lMY4GkWH8p0fMmO2Ppq5G5XXG+DQw==",
"cpu": [
"x64"
],
"dev": true,
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://mirrors.tencent.com/npm/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz",
"integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==",
"dependencies": {
"follow-redirects": "^1.14.9",
"form-data": "^4.0.0"
}
},
"node_modules/axios-adapter-uniapp": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/axios-adapter-uniapp/-/axios-adapter-uniapp-0.1.4.tgz",
"integrity": "sha512-4je5JcWGrrTjPEJXVXJZnOkv+BsnYn/fKbQmjxzdCGFyoQw1gq3tfQ4/WhLzy+Gi9cQJl3K8EH26G7U0BK3wcw==",
"dependencies": {
"axios": "^0.27.2"
}
},
"node_modules/braces": {
"version": "3.0.3",
"resolved": "https://mirrors.tencent.com/npm/braces/-/braces-3.0.3.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
"dev": true,
"optional": true,
"dependencies": {
"fill-range": "^7.1.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/chokidar": {
"version": "4.0.1",
"resolved": "https://mirrors.tencent.com/npm/chokidar/-/chokidar-4.0.1.tgz",
"integrity": "sha512-n8enUVCED/KVRQlab1hr3MVpcVMvxtZjmEa956u+4YijlmQED223XMSYj2tLuKvr4jcCTzNNMpQDUer72MMmzA==",
"dev": true,
"dependencies": {
"readdirp": "^4.0.1"
},
"engines": {
"node": ">= 14.16.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://mirrors.tencent.com/npm/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://mirrors.tencent.com/npm/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/detect-libc": {
"version": "1.0.3",
"resolved": "https://mirrors.tencent.com/npm/detect-libc/-/detect-libc-1.0.3.tgz",
"integrity": "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg==",
"dev": true,
"optional": true,
"bin": {
"detect-libc": "bin/detect-libc.js"
},
"engines": {
"node": ">=0.10"
}
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://mirrors.tencent.com/npm/fill-range/-/fill-range-7.1.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
"dev": true,
"optional": true,
"dependencies": {
"to-regex-range": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/follow-redirects": {
"version": "1.15.9",
"resolved": "https://mirrors.tencent.com/npm/follow-redirects/-/follow-redirects-1.15.9.tgz",
"integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.1",
"resolved": "https://mirrors.tencent.com/npm/form-data/-/form-data-4.0.1.tgz",
"integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/immutable": {
"version": "4.3.7",
"resolved": "https://mirrors.tencent.com/npm/immutable/-/immutable-4.3.7.tgz",
"integrity": "sha512-1hqclzwYwjRDFLjcFxOM5AYkkG0rpFPpr1RLPMEuGczoS7YA8gLhy8SWXYRAA/XwfEHpfo3cw5JGioS32fnMRw==",
"dev": true
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://mirrors.tencent.com/npm/is-extglob/-/is-extglob-2.1.1.tgz",
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
"dev": true,
"optional": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-glob": {
"version": "4.0.3",
"resolved": "https://mirrors.tencent.com/npm/is-glob/-/is-glob-4.0.3.tgz",
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
"dev": true,
"optional": true,
"dependencies": {
"is-extglob": "^2.1.1"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-number": {
"version": "7.0.0",
"resolved": "https://mirrors.tencent.com/npm/is-number/-/is-number-7.0.0.tgz",
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"dev": true,
"optional": true,
"engines": {
"node": ">=0.12.0"
}
},
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://mirrors.tencent.com/npm/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"optional": true,
"dependencies": {
"braces": "^3.0.3",
"picomatch": "^2.3.1"
},
"engines": {
"node": ">=8.6"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://mirrors.tencent.com/npm/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://mirrors.tencent.com/npm/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/neo-async": {
"version": "2.6.2",
"resolved": "https://mirrors.tencent.com/npm/neo-async/-/neo-async-2.6.2.tgz",
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"dev": true
},
"node_modules/node-addon-api": {
"version": "7.1.1",
"resolved": "https://mirrors.tencent.com/npm/node-addon-api/-/node-addon-api-7.1.1.tgz",
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
"dev": true,
"optional": true
},
"node_modules/picomatch": {
"version": "2.3.1",
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"optional": true,
"engines": {
"node": ">=8.6"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/readdirp": {
"version": "4.0.2",
"resolved": "https://mirrors.tencent.com/npm/readdirp/-/readdirp-4.0.2.tgz",
"integrity": "sha512-yDMz9g+VaZkqBYS/ozoBJwaBhTbZo3UNYQHNRw1D3UFQB8oHB4uS/tAODO+ZLjGWmUbKnIlOWO+aaIiAxrUWHA==",
"dev": true,
"engines": {
"node": ">= 14.16.0"
},
"funding": {
"type": "individual",
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/sass": {
"version": "1.80.6",
"resolved": "https://mirrors.tencent.com/npm/sass/-/sass-1.80.6.tgz",
"integrity": "sha512-ccZgdHNiBF1NHBsWvacvT5rju3y1d/Eu+8Ex6c21nHp2lZGLBEtuwc415QfiI1PJa1TpCo3iXwwSRjRpn2Ckjg==",
"dev": true,
"dependencies": {
"chokidar": "^4.0.0",
"immutable": "^4.0.0",
"source-map-js": ">=0.6.2 <2.0.0"
},
"bin": {
"sass": "sass.js"
},
"engines": {
"node": ">=14.0.0"
},
"optionalDependencies": {
"@parcel/watcher": "^2.4.1"
}
},
"node_modules/sass-loader": {
"version": "16.0.3",
"resolved": "https://mirrors.tencent.com/npm/sass-loader/-/sass-loader-16.0.3.tgz",
"integrity": "sha512-gosNorT1RCkuCMyihv6FBRR7BMV06oKRAs+l4UMp1mlcVg9rWN6KMmUj3igjQwmYys4mDP3etEYJgiHRbgHCHA==",
"dev": true,
"dependencies": {
"neo-async": "^2.6.2"
},
"engines": {
"node": ">= 18.12.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/webpack"
},
"peerDependencies": {
"@rspack/core": "0.x || 1.x",
"node-sass": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0",
"sass": "^1.3.0",
"sass-embedded": "*",
"webpack": "^5.0.0"
},
"peerDependenciesMeta": {
"@rspack/core": {
"optional": true
},
"node-sass": {
"optional": true
},
"sass": {
"optional": true
},
"sass-embedded": {
"optional": true
},
"webpack": {
"optional": true
}
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://mirrors.tencent.com/npm/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://mirrors.tencent.com/npm/to-regex-range/-/to-regex-range-5.0.1.tgz",
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
"dev": true,
"optional": true,
"dependencies": {
"is-number": "^7.0.0"
},
"engines": {
"node": ">=8.0"
}
}
}
}

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017-present Devon Govett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1 +0,0 @@
This is the win32-x64 build of @parcel/watcher. See https://github.com/parcel-bundler/watcher for details.

View File

@ -1,30 +0,0 @@
{
"name": "@parcel/watcher-win32-x64",
"version": "2.5.0",
"main": "watcher.node",
"repository": {
"type": "git",
"url": "https://github.com/parcel-bundler/watcher.git"
},
"description": "A native C++ Node module for querying and subscribing to filesystem events. Used by Parcel 2.",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
},
"files": [
"watcher.node"
],
"engines": {
"node": ">= 10.0.0"
},
"os": [
"win32"
],
"cpu": [
"x64"
]
}

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017-present Devon Govett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,135 +0,0 @@
# @parcel/watcher
A native C++ Node module for querying and subscribing to filesystem events. Used by [Parcel 2](https://github.com/parcel-bundler/parcel).
## Features
- **Watch** - subscribe to realtime recursive directory change notifications when files or directories are created, updated, or deleted.
- **Query** - performantly query for historical change events in a directory, even when your program is not running.
- **Native** - implemented in C++ for performance and low-level integration with the operating system.
- **Cross platform** - includes backends for macOS, Linux, Windows, FreeBSD, and Watchman.
- **Performant** - events are throttled in C++ so the JavaScript thread is not overwhelmed during large filesystem changes (e.g. `git checkout` or `npm install`).
- **Scalable** - tens of thousands of files can be watched or queried at once with good performance.
## Example
```javascript
const watcher = require('@parcel/watcher');
const path = require('path');
// Subscribe to events
let subscription = await watcher.subscribe(process.cwd(), (err, events) => {
console.log(events);
});
// later on...
await subscription.unsubscribe();
// Get events since some saved snapshot in the past
let snapshotPath = path.join(process.cwd(), 'snapshot.txt');
let events = await watcher.getEventsSince(process.cwd(), snapshotPath);
// Save a snapshot for later
await watcher.writeSnapshot(process.cwd(), snapshotPath);
```
## Watching
`@parcel/watcher` supports subscribing to realtime notifications of changes in a directory. It works recursively, so changes in sub-directories will also be emitted.
Events are throttled and coalesced for performance during large changes like `git checkout` or `npm install`, and a single notification will be emitted with all of the events at the end.
Only one notification will be emitted per file. For example, if a file was both created and updated since the last event, you'll get only a `create` event. If a file is both created and deleted, you will not be notifed of that file. Renames cause two events: a `delete` for the old name, and a `create` for the new name.
```javascript
let subscription = await watcher.subscribe(process.cwd(), (err, events) => {
console.log(events);
});
```
Events have two properties:
- `type` - the event type: `create`, `update`, or `delete`.
- `path` - the absolute path to the file or directory.
To unsubscribe from change notifications, call the `unsubscribe` method on the returned subscription object.
```javascript
await subscription.unsubscribe();
```
`@parcel/watcher` has the following watcher backends, listed in priority order:
- [FSEvents](https://developer.apple.com/documentation/coreservices/file_system_events) on macOS
- [Watchman](https://facebook.github.io/watchman/) if installed
- [inotify](http://man7.org/linux/man-pages/man7/inotify.7.html) on Linux
- [ReadDirectoryChangesW](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v%3Dvs.85%29.aspx) on Windows
- [kqueue](https://man.freebsd.org/cgi/man.cgi?kqueue) on FreeBSD, or as an alternative to FSEvents on macOS
You can specify the exact backend you wish to use by passing the `backend` option. If that backend is not available on the current platform, the default backend will be used instead. See below for the list of backend names that can be passed to the options.
## Querying
`@parcel/watcher` also supports querying for historical changes made in a directory, even when your program is not running. This makes it easy to invalidate a cache and re-build only the files that have changed, for example. It can be **significantly** faster than traversing the entire filesystem to determine what files changed, depending on the platform.
In order to query for historical changes, you first need a previous snapshot to compare to. This can be saved to a file with the `writeSnapshot` function, e.g. just before your program exits.
```javascript
await watcher.writeSnapshot(dirPath, snapshotPath);
```
When your program starts up, you can query for changes that have occurred since that snapshot using the `getEventsSince` function.
```javascript
let events = await watcher.getEventsSince(dirPath, snapshotPath);
```
The events returned are exactly the same as the events that would be passed to the `subscribe` callback (see above).
`@parcel/watcher` has the following watcher backends, listed in priority order:
- [FSEvents](https://developer.apple.com/documentation/coreservices/file_system_events) on macOS
- [Watchman](https://facebook.github.io/watchman/) if installed
- [fts](http://man7.org/linux/man-pages/man3/fts.3.html) (brute force) on Linux and FreeBSD
- [FindFirstFile](https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfilea) (brute force) on Windows
The FSEvents (macOS) and Watchman backends are significantly more performant than the brute force backends used by default on Linux and Windows, for example returning results in miliseconds instead of seconds for large directory trees. This is because a background daemon monitoring filesystem changes on those platforms allows us to query cached data rather than traversing the filesystem manually (brute force).
macOS has good performance with FSEvents by default. For the best performance on other platforms, install [Watchman](https://facebook.github.io/watchman/) and it will be used by `@parcel/watcher` automatically.
You can specify the exact backend you wish to use by passing the `backend` option. If that backend is not available on the current platform, the default backend will be used instead. See below for the list of backend names that can be passed to the options.
## Options
All of the APIs in `@parcel/watcher` support the following options, which are passed as an object as the last function argument.
- `ignore` - an array of paths or glob patterns to ignore. uses [`is-glob`](https://github.com/micromatch/is-glob) to distinguish paths from globs. glob patterns are parsed with [`micromatch`](https://github.com/micromatch/micromatch) (see [features](https://github.com/micromatch/micromatch#matching-features)).
- paths can be relative or absolute and can either be files or directories. No events will be emitted about these files or directories or their children.
- glob patterns match on relative paths from the root that is watched. No events will be emitted for matching paths.
- `backend` - the name of an explicitly chosen backend to use. Allowed options are `"fs-events"`, `"watchman"`, `"inotify"`, `"kqueue"`, `"windows"`, or `"brute-force"` (only for querying). If the specified backend is not available on the current platform, the default backend will be used instead.
## WASM
The `@parcel/watcher-wasm` package can be used in place of `@parcel/watcher` on unsupported platforms. It relies on the Node `fs` module, so in non-Node environments such as browsers, an `fs` polyfill will be needed.
**Note**: the WASM implementation is significantly less efficient than the native implementations because it must crawl the file system to watch each directory individually. Use the native `@parcel/watcher` package wherever possible.
```js
import {subscribe} from '@parcel/watcher-wasm';
// Use the module as documented above.
subscribe(/* ... */);
```
## Who is using this?
- [Parcel 2](https://parceljs.org/)
- [VSCode](https://code.visualstudio.com/updates/v1_62#_file-watching-changes)
- [Tailwind CSS Intellisense](https://github.com/tailwindlabs/tailwindcss-intellisense)
- [Gatsby Cloud](https://twitter.com/chatsidhartha/status/1435647412828196867)
- [Nx](https://nx.dev)
- [Nuxt](https://nuxt.com)
## License
MIT

View File

@ -1,92 +0,0 @@
{
"targets": [
{
"target_name": "watcher",
"defines": [ "NAPI_DISABLE_CPP_EXCEPTIONS" ],
"sources": [ "src/binding.cc", "src/Watcher.cc", "src/Backend.cc", "src/DirTree.cc", "src/Glob.cc", "src/Debounce.cc" ],
"include_dirs" : ["<!(node -p \"require('node-addon-api').include_dir\")"],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
"conditions": [
['OS=="mac"', {
"sources": [
"src/watchman/BSER.cc",
"src/watchman/WatchmanBackend.cc",
"src/shared/BruteForceBackend.cc",
"src/unix/fts.cc",
"src/macos/FSEventsBackend.cc",
"src/kqueue/KqueueBackend.cc"
],
"link_settings": {
"libraries": ["CoreServices.framework"]
},
"defines": [
"WATCHMAN",
"BRUTE_FORCE",
"FS_EVENTS",
"KQUEUE"
],
"xcode_settings": {
"GCC_ENABLE_CPP_EXCEPTIONS": "YES"
}
}],
['OS=="mac" and target_arch=="arm64"', {
"xcode_settings": {
"ARCHS": ["arm64"]
}
}],
['OS=="linux" or OS=="android"', {
"sources": [
"src/watchman/BSER.cc",
"src/watchman/WatchmanBackend.cc",
"src/shared/BruteForceBackend.cc",
"src/linux/InotifyBackend.cc",
"src/unix/legacy.cc"
],
"defines": [
"WATCHMAN",
"INOTIFY",
"BRUTE_FORCE"
]
}],
['OS=="win"', {
"sources": [
"src/watchman/BSER.cc",
"src/watchman/WatchmanBackend.cc",
"src/shared/BruteForceBackend.cc",
"src/windows/WindowsBackend.cc",
"src/windows/win_utils.cc"
],
"defines": [
"WATCHMAN",
"WINDOWS",
"BRUTE_FORCE"
],
"msvs_settings": {
"VCCLCompilerTool": {
"ExceptionHandling": 1, # /EHsc
}
}
}],
['OS=="freebsd"', {
"sources": [
"src/watchman/BSER.cc",
"src/watchman/WatchmanBackend.cc",
"src/shared/BruteForceBackend.cc",
"src/unix/fts.cc",
"src/kqueue/KqueueBackend.cc"
],
"defines": [
"WATCHMAN",
"BRUTE_FORCE",
"KQUEUE"
]
}]
]
}
],
"variables": {
"openssl_fips": "",
"node_use_dtrace": "false"
}
}

View File

@ -1,49 +0,0 @@
declare type FilePath = string;
declare type GlobPattern = string;
declare namespace ParcelWatcher {
export type BackendType =
| 'fs-events'
| 'watchman'
| 'inotify'
| 'windows'
| 'brute-force';
export type EventType = 'create' | 'update' | 'delete';
export interface Options {
ignore?: (FilePath|GlobPattern)[];
backend?: BackendType;
}
export type SubscribeCallback = (
err: Error | null,
events: Event[]
) => unknown;
export interface AsyncSubscription {
unsubscribe(): Promise<void>;
}
export interface Event {
path: FilePath;
type: EventType;
}
export function getEventsSince(
dir: FilePath,
snapshot: FilePath,
opts?: Options
): Promise<Event[]>;
export function subscribe(
dir: FilePath,
fn: SubscribeCallback,
opts?: Options
): Promise<AsyncSubscription>;
export function unsubscribe(
dir: FilePath,
fn: SubscribeCallback,
opts?: Options
): Promise<void>;
export function writeSnapshot(
dir: FilePath,
snapshot: FilePath,
opts?: Options
): Promise<FilePath>;
}
export = ParcelWatcher;

View File

@ -1,41 +0,0 @@
const {createWrapper} = require('./wrapper');
let name = `@parcel/watcher-${process.platform}-${process.arch}`;
if (process.platform === 'linux') {
const { MUSL, family } = require('detect-libc');
if (family === MUSL) {
name += '-musl';
} else {
name += '-glibc';
}
}
let binding;
try {
binding = require(name);
} catch (err) {
handleError(err);
try {
binding = require('./build/Release/watcher.node');
} catch (err) {
handleError(err);
try {
binding = require('./build/Debug/watcher.node');
} catch (err) {
handleError(err);
throw new Error(`No prebuild or local build of @parcel/watcher found. Tried ${name}. Please ensure it is installed (don't use --no-optional when installing with npm). Otherwise it is possible we don't support your platform yet. If this is the case, please report an issue to https://github.com/parcel-bundler/watcher.`);
}
}
}
function handleError(err) {
if (err?.code !== 'MODULE_NOT_FOUND') {
throw err;
}
}
const wrapper = createWrapper(binding);
exports.writeSnapshot = wrapper.writeSnapshot;
exports.getEventsSince = wrapper.getEventsSince;
exports.subscribe = wrapper.subscribe;
exports.unsubscribe = wrapper.unsubscribe;

View File

@ -1,48 +0,0 @@
// @flow
declare type FilePath = string;
declare type GlobPattern = string;
export type BackendType =
| 'fs-events'
| 'watchman'
| 'inotify'
| 'windows'
| 'brute-force';
export type EventType = 'create' | 'update' | 'delete';
export interface Options {
ignore?: Array<FilePath | GlobPattern>,
backend?: BackendType
}
export type SubscribeCallback = (
err: ?Error,
events: Array<Event>
) => mixed;
export interface AsyncSubscription {
unsubscribe(): Promise<void>
}
export interface Event {
path: FilePath,
type: EventType
}
declare module.exports: {
getEventsSince(
dir: FilePath,
snapshot: FilePath,
opts?: Options
): Promise<Array<Event>>,
subscribe(
dir: FilePath,
fn: SubscribeCallback,
opts?: Options
): Promise<AsyncSubscription>,
unsubscribe(
dir: FilePath,
fn: SubscribeCallback,
opts?: Options
): Promise<void>,
writeSnapshot(
dir: FilePath,
snapshot: FilePath,
opts?: Options
): Promise<FilePath>
}

View File

@ -1,88 +0,0 @@
{
"name": "@parcel/watcher",
"version": "2.5.0",
"main": "index.js",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/parcel-bundler/watcher.git"
},
"description": "A native C++ Node module for querying and subscribing to filesystem events. Used by Parcel 2.",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
},
"files": [
"index.js",
"index.js.flow",
"index.d.ts",
"wrapper.js",
"package.json",
"README.md",
"LICENSE",
"src",
"scripts/build-from-source.js",
"binding.gyp"
],
"scripts": {
"prebuild": "prebuildify --napi --strip --tag-libc",
"format": "prettier --write \"./**/*.{js,json,md}\"",
"build": "node-gyp rebuild",
"install": "node scripts/build-from-source.js",
"test": "mocha"
},
"engines": {
"node": ">= 10.0.0"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,json,md}": [
"prettier --write",
"git add"
]
},
"dependencies": {
"detect-libc": "^1.0.3",
"is-glob": "^4.0.3",
"micromatch": "^4.0.5",
"node-addon-api": "^7.0.0"
},
"devDependencies": {
"esbuild": "^0.19.8",
"fs-extra": "^10.0.0",
"husky": "^7.0.2",
"lint-staged": "^11.1.2",
"mocha": "^9.1.1",
"napi-wasm": "^1.1.0",
"prebuildify": "^6.0.1",
"prettier": "^2.3.2"
},
"binary": {
"napi_versions": [
3
]
},
"optionalDependencies": {
"@parcel/watcher-darwin-x64": "2.5.0",
"@parcel/watcher-darwin-arm64": "2.5.0",
"@parcel/watcher-win32-x64": "2.5.0",
"@parcel/watcher-win32-arm64": "2.5.0",
"@parcel/watcher-win32-ia32": "2.5.0",
"@parcel/watcher-linux-x64-glibc": "2.5.0",
"@parcel/watcher-linux-x64-musl": "2.5.0",
"@parcel/watcher-linux-arm64-glibc": "2.5.0",
"@parcel/watcher-linux-arm64-musl": "2.5.0",
"@parcel/watcher-linux-arm-glibc": "2.5.0",
"@parcel/watcher-linux-arm-musl": "2.5.0",
"@parcel/watcher-android-arm64": "2.5.0",
"@parcel/watcher-freebsd-x64": "2.5.0"
}
}

View File

@ -1,13 +0,0 @@
#!/usr/bin/env node
const {spawn} = require('child_process');
if (process.env.npm_config_build_from_source === 'true') {
build();
}
function build() {
spawn('node-gyp', ['rebuild'], { stdio: 'inherit', shell: true }).on('exit', function (code) {
process.exit(code);
});
}

View File

@ -1,182 +0,0 @@
#ifdef FS_EVENTS
#include "macos/FSEventsBackend.hh"
#endif
#ifdef WATCHMAN
#include "watchman/WatchmanBackend.hh"
#endif
#ifdef WINDOWS
#include "windows/WindowsBackend.hh"
#endif
#ifdef INOTIFY
#include "linux/InotifyBackend.hh"
#endif
#ifdef KQUEUE
#include "kqueue/KqueueBackend.hh"
#endif
#ifdef __wasm32__
#include "wasm/WasmBackend.hh"
#endif
#include "shared/BruteForceBackend.hh"
#include "Backend.hh"
#include <unordered_map>
static std::unordered_map<std::string, std::shared_ptr<Backend>> sharedBackends;
std::shared_ptr<Backend> getBackend(std::string backend) {
// Use FSEvents on macOS by default.
// Use watchman by default if available on other platforms.
// Fall back to brute force.
#ifdef FS_EVENTS
if (backend == "fs-events" || backend == "default") {
return std::make_shared<FSEventsBackend>();
}
#endif
#ifdef WATCHMAN
if ((backend == "watchman" || backend == "default") && WatchmanBackend::checkAvailable()) {
return std::make_shared<WatchmanBackend>();
}
#endif
#ifdef WINDOWS
if (backend == "windows" || backend == "default") {
return std::make_shared<WindowsBackend>();
}
#endif
#ifdef INOTIFY
if (backend == "inotify" || backend == "default") {
return std::make_shared<InotifyBackend>();
}
#endif
#ifdef KQUEUE
if (backend == "kqueue" || backend == "default") {
return std::make_shared<KqueueBackend>();
}
#endif
#ifdef __wasm32__
if (backend == "wasm" || backend == "default") {
return std::make_shared<WasmBackend>();
}
#endif
if (backend == "brute-force" || backend == "default") {
return std::make_shared<BruteForceBackend>();
}
return nullptr;
}
std::shared_ptr<Backend> Backend::getShared(std::string backend) {
auto found = sharedBackends.find(backend);
if (found != sharedBackends.end()) {
return found->second;
}
auto result = getBackend(backend);
if (!result) {
return getShared("default");
}
result->run();
sharedBackends.emplace(backend, result);
return result;
}
void removeShared(Backend *backend) {
for (auto it = sharedBackends.begin(); it != sharedBackends.end(); it++) {
if (it->second.get() == backend) {
sharedBackends.erase(it);
break;
}
}
// Free up memory.
if (sharedBackends.size() == 0) {
sharedBackends.rehash(0);
}
}
void Backend::run() {
#ifndef __wasm32__
mThread = std::thread([this] () {
try {
start();
} catch (std::exception &err) {
handleError(err);
}
});
if (mThread.joinable()) {
mStartedSignal.wait();
}
#else
try {
start();
} catch (std::exception &err) {
handleError(err);
}
#endif
}
void Backend::notifyStarted() {
mStartedSignal.notify();
}
void Backend::start() {
notifyStarted();
}
Backend::~Backend() {
#ifndef __wasm32__
// Wait for thread to stop
if (mThread.joinable()) {
// If the backend is being destroyed from the thread itself, detach, otherwise join.
if (mThread.get_id() == std::this_thread::get_id()) {
mThread.detach();
} else {
mThread.join();
}
}
#endif
}
void Backend::watch(WatcherRef watcher) {
std::unique_lock<std::mutex> lock(mMutex);
auto res = mSubscriptions.find(watcher);
if (res == mSubscriptions.end()) {
try {
this->subscribe(watcher);
mSubscriptions.insert(watcher);
} catch (std::exception &err) {
unref();
throw;
}
}
}
void Backend::unwatch(WatcherRef watcher) {
std::unique_lock<std::mutex> lock(mMutex);
size_t deleted = mSubscriptions.erase(watcher);
if (deleted > 0) {
this->unsubscribe(watcher);
unref();
}
}
void Backend::unref() {
if (mSubscriptions.size() == 0) {
removeShared(this);
}
}
void Backend::handleWatcherError(WatcherError &err) {
unwatch(err.mWatcher);
err.mWatcher->notifyError(err);
}
void Backend::handleError(std::exception &err) {
std::unique_lock<std::mutex> lock(mMutex);
for (auto it = mSubscriptions.begin(); it != mSubscriptions.end(); it++) {
(*it)->notifyError(err);
}
removeShared(this);
}

View File

@ -1,37 +0,0 @@
#ifndef BACKEND_H
#define BACKEND_H
#include "Event.hh"
#include "Watcher.hh"
#include "Signal.hh"
#include <thread>
class Backend {
public:
virtual ~Backend();
void run();
void notifyStarted();
virtual void start();
virtual void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) = 0;
virtual void getEventsSince(WatcherRef watcher, std::string *snapshotPath) = 0;
virtual void subscribe(WatcherRef watcher) = 0;
virtual void unsubscribe(WatcherRef watcher) = 0;
static std::shared_ptr<Backend> getShared(std::string backend);
void watch(WatcherRef watcher);
void unwatch(WatcherRef watcher);
void unref();
void handleWatcherError(WatcherError &err);
std::mutex mMutex;
std::thread mThread;
private:
std::unordered_set<WatcherRef> mSubscriptions;
Signal mStartedSignal;
void handleError(std::exception &err);
};
#endif

View File

@ -1,113 +0,0 @@
#include "Debounce.hh"
#ifdef __wasm32__
extern "C" void on_timeout(void *ctx) {
Debounce *debounce = (Debounce *)ctx;
debounce->notify();
}
#endif
std::shared_ptr<Debounce> Debounce::getShared() {
static std::weak_ptr<Debounce> sharedInstance;
std::shared_ptr<Debounce> shared = sharedInstance.lock();
if (!shared) {
shared = std::make_shared<Debounce>();
sharedInstance = shared;
}
return shared;
}
Debounce::Debounce() {
mRunning = true;
#ifndef __wasm32__
mThread = std::thread([this] () {
loop();
});
#endif
}
Debounce::~Debounce() {
mRunning = false;
#ifndef __wasm32__
mWaitSignal.notify();
mThread.join();
#endif
}
void Debounce::add(void *key, std::function<void()> cb) {
std::unique_lock<std::mutex> lock(mMutex);
mCallbacks.emplace(key, cb);
}
void Debounce::remove(void *key) {
std::unique_lock<std::mutex> lock(mMutex);
mCallbacks.erase(key);
}
void Debounce::trigger() {
std::unique_lock<std::mutex> lock(mMutex);
#ifdef __wasm32__
notifyIfReady();
#else
mWaitSignal.notify();
#endif
}
#ifndef __wasm32__
void Debounce::loop() {
while (mRunning) {
mWaitSignal.wait();
if (!mRunning) {
break;
}
notifyIfReady();
}
}
#endif
void Debounce::notifyIfReady() {
if (!mRunning) {
return;
}
// If we haven't seen an event in more than the maximum wait time, notify callbacks immediately
// to ensure that we don't wait forever. Otherwise, wait for the minimum wait time and batch
// subsequent fast changes. This also means the first file change in a batch is notified immediately,
// separately from the rest of the batch. This seems like an acceptable tradeoff if the common case
// is that only a single file was updated at a time.
auto time = std::chrono::steady_clock::now();
if ((time - mLastTime) > std::chrono::milliseconds(MAX_WAIT_TIME)) {
mLastTime = time;
notify();
} else {
wait();
}
}
void Debounce::wait() {
#ifdef __wasm32__
clear_timeout(mTimeout);
mTimeout = set_timeout(MIN_WAIT_TIME, this);
#else
auto status = mWaitSignal.waitFor(std::chrono::milliseconds(MIN_WAIT_TIME));
if (mRunning && (status == std::cv_status::timeout)) {
notify();
}
#endif
}
void Debounce::notify() {
std::unique_lock<std::mutex> lock(mMutex);
mLastTime = std::chrono::steady_clock::now();
for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
auto cb = it->second;
cb();
}
#ifndef __wasm32__
mWaitSignal.reset();
#endif
}

View File

@ -1,49 +0,0 @@
#ifndef DEBOUNCE_H
#define DEBOUNCE_H
#include <thread>
#include <unordered_map>
#include <functional>
#include "Signal.hh"
#define MIN_WAIT_TIME 50
#define MAX_WAIT_TIME 500
#ifdef __wasm32__
extern "C" {
int set_timeout(int ms, void *ctx);
void clear_timeout(int timeout);
void on_timeout(void *ctx);
};
#endif
class Debounce {
public:
static std::shared_ptr<Debounce> getShared();
Debounce();
~Debounce();
void add(void *key, std::function<void()> cb);
void remove(void *key);
void trigger();
void notify();
private:
bool mRunning;
std::mutex mMutex;
#ifdef __wasm32__
int mTimeout;
#else
Signal mWaitSignal;
std::thread mThread;
#endif
std::unordered_map<void *, std::function<void()>> mCallbacks;
std::chrono::time_point<std::chrono::steady_clock> mLastTime;
void loop();
void notifyIfReady();
void wait();
};
#endif

View File

@ -1,152 +0,0 @@
#include "DirTree.hh"
#include <inttypes.h>
static std::mutex mDirCacheMutex;
static std::unordered_map<std::string, std::weak_ptr<DirTree>> dirTreeCache;
struct DirTreeDeleter {
void operator()(DirTree *tree) {
std::lock_guard<std::mutex> lock(mDirCacheMutex);
dirTreeCache.erase(tree->root);
delete tree;
// Free up memory.
if (dirTreeCache.size() == 0) {
dirTreeCache.rehash(0);
}
}
};
std::shared_ptr<DirTree> DirTree::getCached(std::string root) {
std::lock_guard<std::mutex> lock(mDirCacheMutex);
auto found = dirTreeCache.find(root);
std::shared_ptr<DirTree> tree;
// Use cached tree, or create an empty one.
if (found != dirTreeCache.end()) {
tree = found->second.lock();
} else {
tree = std::shared_ptr<DirTree>(new DirTree(root), DirTreeDeleter());
dirTreeCache.emplace(root, tree);
}
return tree;
}
DirTree::DirTree(std::string root, FILE *f) : root(root), isComplete(true) {
size_t size;
if (fscanf(f, "%zu", &size)) {
for (size_t i = 0; i < size; i++) {
DirEntry entry(f);
entries.emplace(entry.path, entry);
}
}
}
// Internal find method that has no lock
DirEntry *DirTree::_find(std::string path) {
auto found = entries.find(path);
if (found == entries.end()) {
return NULL;
}
return &found->second;
}
DirEntry *DirTree::add(std::string path, uint64_t mtime, bool isDir) {
std::lock_guard<std::mutex> lock(mMutex);
DirEntry entry(path, mtime, isDir);
auto it = entries.emplace(entry.path, entry);
return &it.first->second;
}
DirEntry *DirTree::find(std::string path) {
std::lock_guard<std::mutex> lock(mMutex);
return _find(path);
}
DirEntry *DirTree::update(std::string path, uint64_t mtime) {
std::lock_guard<std::mutex> lock(mMutex);
DirEntry *found = _find(path);
if (found) {
found->mtime = mtime;
}
return found;
}
void DirTree::remove(std::string path) {
std::lock_guard<std::mutex> lock(mMutex);
DirEntry *found = _find(path);
// Remove all sub-entries if this is a directory
if (found && found->isDir) {
std::string pathStart = path + DIR_SEP;
for (auto it = entries.begin(); it != entries.end();) {
if (it->first.rfind(pathStart, 0) == 0) {
it = entries.erase(it);
} else {
it++;
}
}
}
entries.erase(path);
}
void DirTree::write(FILE *f) {
std::lock_guard<std::mutex> lock(mMutex);
fprintf(f, "%zu\n", entries.size());
for (auto it = entries.begin(); it != entries.end(); it++) {
it->second.write(f);
}
}
void DirTree::getChanges(DirTree *snapshot, EventList &events) {
std::lock_guard<std::mutex> lock(mMutex);
std::lock_guard<std::mutex> snapshotLock(snapshot->mMutex);
for (auto it = entries.begin(); it != entries.end(); it++) {
auto found = snapshot->entries.find(it->first);
if (found == snapshot->entries.end()) {
events.create(it->second.path);
} else if (found->second.mtime != it->second.mtime && !found->second.isDir && !it->second.isDir) {
events.update(it->second.path);
}
}
for (auto it = snapshot->entries.begin(); it != snapshot->entries.end(); it++) {
size_t count = entries.count(it->first);
if (count == 0) {
events.remove(it->second.path);
}
}
}
DirEntry::DirEntry(std::string p, uint64_t t, bool d) {
path = p;
mtime = t;
isDir = d;
state = NULL;
}
DirEntry::DirEntry(FILE *f) {
size_t size;
if (fscanf(f, "%zu", &size)) {
path.resize(size);
if (fread(&path[0], sizeof(char), size, f)) {
int d = 0;
fscanf(f, "%" PRIu64 " %d\n", &mtime, &d);
isDir = d == 1;
}
}
}
void DirEntry::write(FILE *f) const {
fprintf(f, "%zu%s%" PRIu64 " %d\n", path.size(), path.c_str(), mtime, isDir);
}

View File

@ -1,50 +0,0 @@
#ifndef DIR_TREE_H
#define DIR_TREE_H
#include <string>
#include <unordered_map>
#include <memory>
#include "Event.hh"
#ifdef _WIN32
#define DIR_SEP "\\"
#else
#define DIR_SEP "/"
#endif
struct DirEntry {
std::string path;
uint64_t mtime;
bool isDir;
mutable void *state;
DirEntry(std::string p, uint64_t t, bool d);
DirEntry(FILE *f);
void write(FILE *f) const;
bool operator==(const DirEntry &other) const {
return path == other.path;
}
};
class DirTree {
public:
static std::shared_ptr<DirTree> getCached(std::string root);
DirTree(std::string root) : root(root), isComplete(false) {}
DirTree(std::string root, FILE *f);
DirEntry *add(std::string path, uint64_t mtime, bool isDir);
DirEntry *find(std::string path);
DirEntry *update(std::string path, uint64_t mtime);
void remove(std::string path);
void write(FILE *f);
void getChanges(DirTree *snapshot, EventList &events);
std::mutex mMutex;
std::string root;
bool isComplete;
std::unordered_map<std::string, DirEntry> entries;
private:
DirEntry *_find(std::string path);
};
#endif

View File

@ -1,89 +0,0 @@
#ifndef EVENT_H
#define EVENT_H
#include <string>
#include <node_api.h>
#include "wasm/include.h"
#include <napi.h>
#include <mutex>
#include <map>
using namespace Napi;
struct Event {
std::string path;
bool isCreated;
bool isDeleted;
Event(std::string path) : path(path), isCreated(false), isDeleted(false) {}
Value toJS(const Env& env) {
EscapableHandleScope scope(env);
Object res = Object::New(env);
std::string type = isCreated ? "create" : isDeleted ? "delete" : "update";
res.Set(String::New(env, "path"), String::New(env, path.c_str()));
res.Set(String::New(env, "type"), String::New(env, type.c_str()));
return scope.Escape(res);
}
};
class EventList {
public:
void create(std::string path) {
std::lock_guard<std::mutex> l(mMutex);
Event *event = internalUpdate(path);
if (event->isDeleted) {
// Assume update event when rapidly removed and created
// https://github.com/parcel-bundler/watcher/issues/72
event->isDeleted = false;
} else {
event->isCreated = true;
}
}
Event *update(std::string path) {
std::lock_guard<std::mutex> l(mMutex);
return internalUpdate(path);
}
void remove(std::string path) {
std::lock_guard<std::mutex> l(mMutex);
Event *event = internalUpdate(path);
event->isDeleted = true;
}
size_t size() {
std::lock_guard<std::mutex> l(mMutex);
return mEvents.size();
}
std::vector<Event> getEvents() {
std::lock_guard<std::mutex> l(mMutex);
std::vector<Event> eventsCloneVector;
for(auto it = mEvents.begin(); it != mEvents.end(); ++it) {
if (!(it->second.isCreated && it->second.isDeleted)) {
eventsCloneVector.push_back(it->second);
}
}
return eventsCloneVector;
}
void clear() {
std::lock_guard<std::mutex> l(mMutex);
mEvents.clear();
}
private:
mutable std::mutex mMutex;
std::map<std::string, Event> mEvents;
Event *internalUpdate(std::string path) {
auto found = mEvents.find(path);
if (found == mEvents.end()) {
auto it = mEvents.emplace(path, Event(path));
return &it.first->second;
}
return &found->second;
}
};
#endif

View File

@ -1,22 +0,0 @@
#include "Glob.hh"
#ifdef __wasm32__
extern "C" bool wasm_regex_match(const char *s, const char *regex);
#endif
Glob::Glob(std::string raw) {
mRaw = raw;
mHash = std::hash<std::string>()(raw);
#ifndef __wasm32__
mRegex = std::regex(raw);
#endif
}
bool Glob::isIgnored(std::string relative_path) const {
// Use native JS regex engine for wasm to reduce binary size.
#ifdef __wasm32__
return wasm_regex_match(relative_path.c_str(), mRaw.c_str());
#else
return std::regex_match(relative_path, mRegex);
#endif
}

View File

@ -1,34 +0,0 @@
#ifndef GLOB_H
#define GLOB_H
#include <unordered_set>
#include <regex>
struct Glob {
std::size_t mHash;
std::string mRaw;
#ifndef __wasm32__
std::regex mRegex;
#endif
Glob(std::string raw);
bool operator==(const Glob &other) const {
return mHash == other.mHash;
}
bool isIgnored(std::string relative_path) const;
};
namespace std
{
template <>
struct hash<Glob>
{
size_t operator()(const Glob& g) const {
return g.mHash;
}
};
}
#endif

View File

@ -1,101 +0,0 @@
#ifndef PROMISE_RUNNER_H
#define PROMISE_RUNNER_H
#include <node_api.h>
#include "wasm/include.h"
#include <napi.h>
using namespace Napi;
class PromiseRunner {
public:
const Env env;
Promise::Deferred deferred;
PromiseRunner(Env env) : env(env), deferred(Promise::Deferred::New(env)) {
napi_status status = napi_create_async_work(env, nullptr, env.Undefined(),
onExecute, onWorkComplete, this, &work);
if (status != napi_ok) {
work = nullptr;
const napi_extended_error_info *error_info = 0;
napi_get_last_error_info(env, &error_info);
if (error_info->error_message) {
Error::New(env, error_info->error_message).ThrowAsJavaScriptException();
} else {
Error::New(env).ThrowAsJavaScriptException();
}
}
}
virtual ~PromiseRunner() {}
Value queue() {
if (work) {
napi_status status = napi_queue_async_work(env, work);
if (status != napi_ok) {
onError(Error::New(env));
}
}
return deferred.Promise();
}
private:
napi_async_work work;
std::string error;
static void onExecute(napi_env env, void *this_pointer) {
PromiseRunner* self = (PromiseRunner*) this_pointer;
try {
self->execute();
} catch (std::exception &err) {
self->error = err.what();
}
}
static void onWorkComplete(napi_env env, napi_status status, void *this_pointer) {
PromiseRunner* self = (PromiseRunner*) this_pointer;
if (status != napi_cancelled) {
HandleScope scope(self->env);
if (status == napi_ok) {
status = napi_delete_async_work(self->env, self->work);
if (status == napi_ok) {
if (self->error.size() == 0) {
self->onOK();
} else {
self->onError(Error::New(self->env, self->error));
}
delete self;
return;
}
}
}
// fallthrough for error handling
const napi_extended_error_info *error_info = 0;
napi_get_last_error_info(env, &error_info);
if (error_info->error_message){
self->onError(Error::New(env, error_info->error_message));
} else {
self->onError(Error::New(env));
}
delete self;
}
virtual void execute() {}
virtual Value getResult() {
return env.Null();
}
void onOK() {
HandleScope scope(env);
Value result = getResult();
deferred.Resolve(result);
}
void onError(const Error &e) {
deferred.Reject(e.Value());
}
};
#endif

View File

@ -1,46 +0,0 @@
#ifndef SIGNAL_H
#define SIGNAL_H
#include <mutex>
#include <condition_variable>
class Signal {
public:
Signal() : mFlag(false), mWaiting(false) {}
void wait() {
std::unique_lock<std::mutex> lock(mMutex);
while (!mFlag) {
mWaiting = true;
mCond.wait(lock);
}
}
std::cv_status waitFor(std::chrono::milliseconds ms) {
std::unique_lock<std::mutex> lock(mMutex);
return mCond.wait_for(lock, ms);
}
void notify() {
std::unique_lock<std::mutex> lock(mMutex);
mFlag = true;
mCond.notify_all();
}
void reset() {
std::unique_lock<std::mutex> lock(mMutex);
mFlag = false;
mWaiting = false;
}
bool isWaiting() {
return mWaiting;
}
private:
bool mFlag;
bool mWaiting;
std::mutex mMutex;
std::condition_variable mCond;
};
#endif

View File

@ -1,236 +0,0 @@
#include "Watcher.hh"
#include <unordered_set>
using namespace Napi;
struct WatcherHash {
std::size_t operator() (WatcherRef const &k) const {
return std::hash<std::string>()(k->mDir);
}
};
struct WatcherCompare {
size_t operator() (WatcherRef const &a, WatcherRef const &b) const {
return *a == *b;
}
};
static std::unordered_set<WatcherRef , WatcherHash, WatcherCompare> sharedWatchers;
WatcherRef Watcher::getShared(std::string dir, std::unordered_set<std::string> ignorePaths, std::unordered_set<Glob> ignoreGlobs) {
WatcherRef watcher = std::make_shared<Watcher>(dir, ignorePaths, ignoreGlobs);
auto found = sharedWatchers.find(watcher);
if (found != sharedWatchers.end()) {
return *found;
}
sharedWatchers.insert(watcher);
return watcher;
}
void removeShared(Watcher *watcher) {
for (auto it = sharedWatchers.begin(); it != sharedWatchers.end(); it++) {
if (it->get() == watcher) {
sharedWatchers.erase(it);
break;
}
}
// Free up memory.
if (sharedWatchers.size() == 0) {
sharedWatchers.rehash(0);
}
}
Watcher::Watcher(std::string dir, std::unordered_set<std::string> ignorePaths, std::unordered_set<Glob> ignoreGlobs)
: mDir(dir),
mIgnorePaths(ignorePaths),
mIgnoreGlobs(ignoreGlobs) {
mDebounce = Debounce::getShared();
mDebounce->add(this, [this] () {
triggerCallbacks();
});
}
Watcher::~Watcher() {
mDebounce->remove(this);
}
void Watcher::wait() {
std::unique_lock<std::mutex> lk(mMutex);
mCond.wait(lk);
}
void Watcher::notify() {
std::unique_lock<std::mutex> lk(mMutex);
mCond.notify_all();
if (mCallbacks.size() > 0 && mEvents.size() > 0) {
// We must release our lock before calling into the debouncer
// to avoid a deadlock: the debouncer thread itself will require
// our lock from its thread when calling into `triggerCallbacks`
// while holding its own debouncer lock.
lk.unlock();
mDebounce->trigger();
}
}
struct CallbackData {
std::string error;
std::vector<Event> events;
CallbackData(std::string error, std::vector<Event> events) : error(error), events(events) {}
};
Value callbackEventsToJS(const Env &env, std::vector<Event> &events) {
EscapableHandleScope scope(env);
Array arr = Array::New(env, events.size());
size_t currentEventIndex = 0;
for (auto eventIterator = events.begin(); eventIterator != events.end(); eventIterator++) {
arr.Set(currentEventIndex++, eventIterator->toJS(env));
}
return scope.Escape(arr);
}
void callJSFunction(Napi::Env env, Function jsCallback, CallbackData *data) {
HandleScope scope(env);
auto err = data->error.size() > 0 ? Error::New(env, data->error).Value() : env.Null();
auto events = callbackEventsToJS(env, data->events);
jsCallback.Call({err, events});
delete data;
// Throw errors from the callback as fatal exceptions
// If we don't handle these node segfaults...
if (env.IsExceptionPending()) {
Napi::Error err = env.GetAndClearPendingException();
napi_fatal_exception(env, err.Value());
}
}
void Watcher::notifyError(std::exception &err) {
std::unique_lock<std::mutex> lk(mMutex);
for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
CallbackData *data = new CallbackData(err.what(), {});
it->tsfn.BlockingCall(data, callJSFunction);
}
clearCallbacks();
}
// This function is called from the debounce thread.
void Watcher::triggerCallbacks() {
std::unique_lock<std::mutex> lk(mMutex);
if (mCallbacks.size() > 0 && mEvents.size() > 0) {
auto events = mEvents.getEvents();
mEvents.clear();
for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
it->tsfn.BlockingCall(new CallbackData("", events), callJSFunction);
}
}
}
// This should be called from the JavaScript thread.
bool Watcher::watch(Function callback) {
std::unique_lock<std::mutex> lk(mMutex);
auto it = findCallback(callback);
if (it != mCallbacks.end()) {
return false;
}
auto tsfn = ThreadSafeFunction::New(
callback.Env(),
callback,
"Watcher callback",
0, // Unlimited queue
1 // Initial thread count
);
mCallbacks.push_back(Callback {
tsfn,
Napi::Persistent(callback),
std::this_thread::get_id()
});
return true;
}
// This should be called from the JavaScript thread.
std::vector<Callback>::iterator Watcher::findCallback(Function callback) {
for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
// Only consider callbacks created by the same thread, or V8 will panic.
if (it->threadId == std::this_thread::get_id() && it->ref.Value() == callback) {
return it;
}
}
return mCallbacks.end();
}
// This should be called from the JavaScript thread.
bool Watcher::unwatch(Function callback) {
std::unique_lock<std::mutex> lk(mMutex);
bool removed = false;
auto it = findCallback(callback);
if (it != mCallbacks.end()) {
it->tsfn.Release();
it->ref.Unref();
mCallbacks.erase(it);
removed = true;
}
if (removed && mCallbacks.size() == 0) {
unref();
return true;
}
return false;
}
void Watcher::unref() {
if (mCallbacks.size() == 0) {
removeShared(this);
}
}
void Watcher::destroy() {
std::unique_lock<std::mutex> lk(mMutex);
clearCallbacks();
}
// Private because it doesn't lock.
void Watcher::clearCallbacks() {
for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
it->tsfn.Release();
it->ref.Unref();
}
mCallbacks.clear();
unref();
}
bool Watcher::isIgnored(std::string path) {
for (auto it = mIgnorePaths.begin(); it != mIgnorePaths.end(); it++) {
auto dir = *it + DIR_SEP;
if (*it == path || path.compare(0, dir.size(), dir) == 0) {
return true;
}
}
auto basePath = mDir + DIR_SEP;
if (path.rfind(basePath, 0) != 0) {
return false;
}
auto relativePath = path.substr(basePath.size());
for (auto it = mIgnoreGlobs.begin(); it != mIgnoreGlobs.end(); it++) {
if (it->isIgnored(relativePath)) {
return true;
}
}
return false;
}

View File

@ -1,73 +0,0 @@
#ifndef WATCHER_H
#define WATCHER_H
#include <condition_variable>
#include <unordered_set>
#include <set>
#include <node_api.h>
#include "Glob.hh"
#include "Event.hh"
#include "Debounce.hh"
#include "DirTree.hh"
#include "Signal.hh"
using namespace Napi;
struct Watcher;
using WatcherRef = std::shared_ptr<Watcher>;
struct Callback {
Napi::ThreadSafeFunction tsfn;
Napi::FunctionReference ref;
std::thread::id threadId;
};
class WatcherState {
public:
virtual ~WatcherState() = default;
};
struct Watcher {
std::string mDir;
std::unordered_set<std::string> mIgnorePaths;
std::unordered_set<Glob> mIgnoreGlobs;
EventList mEvents;
std::shared_ptr<WatcherState> state;
Watcher(std::string dir, std::unordered_set<std::string> ignorePaths, std::unordered_set<Glob> ignoreGlobs);
~Watcher();
bool operator==(const Watcher &other) const {
return mDir == other.mDir && mIgnorePaths == other.mIgnorePaths && mIgnoreGlobs == other.mIgnoreGlobs;
}
void wait();
void notify();
void notifyError(std::exception &err);
bool watch(Function callback);
bool unwatch(Function callback);
void unref();
bool isIgnored(std::string path);
void destroy();
static WatcherRef getShared(std::string dir, std::unordered_set<std::string> ignorePaths, std::unordered_set<Glob> ignoreGlobs);
private:
std::mutex mMutex;
std::condition_variable mCond;
std::vector<Callback> mCallbacks;
std::shared_ptr<Debounce> mDebounce;
std::vector<Callback>::iterator findCallback(Function callback);
void clearCallbacks();
void triggerCallbacks();
};
class WatcherError : public std::runtime_error {
public:
WatcherRef mWatcher;
WatcherError(std::string msg, WatcherRef watcher) : std::runtime_error(msg), mWatcher(watcher) {}
WatcherError(const char *msg, WatcherRef watcher) : std::runtime_error(msg), mWatcher(watcher) {}
};
#endif

View File

@ -1,261 +0,0 @@
#include <unordered_set>
#include <node_api.h>
#include "wasm/include.h"
#include <napi.h>
#include "Glob.hh"
#include "Event.hh"
#include "Backend.hh"
#include "Watcher.hh"
#include "PromiseRunner.hh"
using namespace Napi;
std::unordered_set<std::string> getIgnorePaths(Env env, Value opts) {
std::unordered_set<std::string> result;
if (opts.IsObject()) {
Value v = opts.As<Object>().Get(String::New(env, "ignorePaths"));
if (v.IsArray()) {
Array items = v.As<Array>();
for (size_t i = 0; i < items.Length(); i++) {
Value item = items.Get(Number::New(env, i));
if (item.IsString()) {
result.insert(std::string(item.As<String>().Utf8Value().c_str()));
}
}
}
}
return result;
}
std::unordered_set<Glob> getIgnoreGlobs(Env env, Value opts) {
std::unordered_set<Glob> result;
if (opts.IsObject()) {
Value v = opts.As<Object>().Get(String::New(env, "ignoreGlobs"));
if (v.IsArray()) {
Array items = v.As<Array>();
for (size_t i = 0; i < items.Length(); i++) {
Value item = items.Get(Number::New(env, i));
if (item.IsString()) {
auto key = item.As<String>().Utf8Value();
result.emplace(key);
}
}
}
}
return result;
}
std::shared_ptr<Backend> getBackend(Env env, Value opts) {
Value b = opts.As<Object>().Get(String::New(env, "backend"));
std::string backendName;
if (b.IsString()) {
backendName = std::string(b.As<String>().Utf8Value().c_str());
}
return Backend::getShared(backendName);
}
class WriteSnapshotRunner : public PromiseRunner {
public:
WriteSnapshotRunner(Env env, Value dir, Value snap, Value opts)
: PromiseRunner(env),
snapshotPath(std::string(snap.As<String>().Utf8Value().c_str())) {
watcher = Watcher::getShared(
std::string(dir.As<String>().Utf8Value().c_str()),
getIgnorePaths(env, opts),
getIgnoreGlobs(env, opts)
);
backend = getBackend(env, opts);
}
~WriteSnapshotRunner() {
watcher->unref();
backend->unref();
}
private:
std::shared_ptr<Backend> backend;
WatcherRef watcher;
std::string snapshotPath;
void execute() override {
backend->writeSnapshot(watcher, &snapshotPath);
}
};
class GetEventsSinceRunner : public PromiseRunner {
public:
GetEventsSinceRunner(Env env, Value dir, Value snap, Value opts)
: PromiseRunner(env),
snapshotPath(std::string(snap.As<String>().Utf8Value().c_str())) {
watcher = std::make_shared<Watcher>(
std::string(dir.As<String>().Utf8Value().c_str()),
getIgnorePaths(env, opts),
getIgnoreGlobs(env, opts)
);
backend = getBackend(env, opts);
}
~GetEventsSinceRunner() {
watcher->unref();
backend->unref();
}
private:
std::shared_ptr<Backend> backend;
WatcherRef watcher;
std::string snapshotPath;
void execute() override {
backend->getEventsSince(watcher, &snapshotPath);
}
Value getResult() override {
std::vector<Event> events = watcher->mEvents.getEvents();
Array eventsArray = Array::New(env, events.size());
size_t i = 0;
for (auto it = events.begin(); it != events.end(); it++) {
eventsArray.Set(i++, it->toJS(env));
}
return eventsArray;
}
};
template<class Runner>
Value queueSnapshotWork(const CallbackInfo& info) {
Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
TypeError::New(env, "Expected a string").ThrowAsJavaScriptException();
return env.Null();
}
if (info.Length() < 2 || !info[1].IsString()) {
TypeError::New(env, "Expected a string").ThrowAsJavaScriptException();
return env.Null();
}
if (info.Length() >= 3 && !info[2].IsObject()) {
TypeError::New(env, "Expected an object").ThrowAsJavaScriptException();
return env.Null();
}
Runner *runner = new Runner(info.Env(), info[0], info[1], info[2]);
return runner->queue();
}
Value writeSnapshot(const CallbackInfo& info) {
return queueSnapshotWork<WriteSnapshotRunner>(info);
}
Value getEventsSince(const CallbackInfo& info) {
return queueSnapshotWork<GetEventsSinceRunner>(info);
}
class SubscribeRunner : public PromiseRunner {
public:
SubscribeRunner(Env env, Value dir, Value fn, Value opts) : PromiseRunner(env) {
watcher = Watcher::getShared(
std::string(dir.As<String>().Utf8Value().c_str()),
getIgnorePaths(env, opts),
getIgnoreGlobs(env, opts)
);
backend = getBackend(env, opts);
watcher->watch(fn.As<Function>());
}
private:
WatcherRef watcher;
std::shared_ptr<Backend> backend;
FunctionReference callback;
void execute() override {
try {
backend->watch(watcher);
} catch (std::exception &err) {
watcher->destroy();
throw;
}
}
};
class UnsubscribeRunner : public PromiseRunner {
public:
UnsubscribeRunner(Env env, Value dir, Value fn, Value opts) : PromiseRunner(env) {
watcher = Watcher::getShared(
std::string(dir.As<String>().Utf8Value().c_str()),
getIgnorePaths(env, opts),
getIgnoreGlobs(env, opts)
);
backend = getBackend(env, opts);
shouldUnwatch = watcher->unwatch(fn.As<Function>());
}
private:
WatcherRef watcher;
std::shared_ptr<Backend> backend;
bool shouldUnwatch;
void execute() override {
if (shouldUnwatch) {
backend->unwatch(watcher);
}
}
};
template<class Runner>
Value queueSubscriptionWork(const CallbackInfo& info) {
Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
TypeError::New(env, "Expected a string").ThrowAsJavaScriptException();
return env.Null();
}
if (info.Length() < 2 || !info[1].IsFunction()) {
TypeError::New(env, "Expected a function").ThrowAsJavaScriptException();
return env.Null();
}
if (info.Length() >= 3 && !info[2].IsObject()) {
TypeError::New(env, "Expected an object").ThrowAsJavaScriptException();
return env.Null();
}
Runner *runner = new Runner(info.Env(), info[0], info[1], info[2]);
return runner->queue();
}
Value subscribe(const CallbackInfo& info) {
return queueSubscriptionWork<SubscribeRunner>(info);
}
Value unsubscribe(const CallbackInfo& info) {
return queueSubscriptionWork<UnsubscribeRunner>(info);
}
Object Init(Env env, Object exports) {
exports.Set(
String::New(env, "writeSnapshot"),
Function::New(env, writeSnapshot)
);
exports.Set(
String::New(env, "getEventsSince"),
Function::New(env, getEventsSince)
);
exports.Set(
String::New(env, "subscribe"),
Function::New(env, subscribe)
);
exports.Set(
String::New(env, "unsubscribe"),
Function::New(env, unsubscribe)
);
return exports;
}
NODE_API_MODULE(watcher, Init)

View File

@ -1,307 +0,0 @@
#include <memory>
#include <poll.h>
#include <unistd.h>
#include <libgen.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "KqueueBackend.hh"
#if __APPLE__
#define st_mtim st_mtimespec
#endif
#if !defined(O_EVTONLY)
#define O_EVTONLY O_RDONLY
#endif
#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
void KqueueBackend::start() {
if ((mKqueue = kqueue()) < 0) {
throw std::runtime_error(std::string("Unable to open kqueue: ") + strerror(errno));
}
// Create a pipe that we will write to when we want to end the thread.
int err = pipe(mPipe);
if (err == -1) {
throw std::runtime_error(std::string("Unable to open pipe: ") + strerror(errno));
}
// Subscribe kqueue to this pipe.
struct kevent ev;
EV_SET(
&ev,
mPipe[0],
EVFILT_READ,
EV_ADD | EV_CLEAR,
0,
0,
0
);
if (kevent(mKqueue, &ev, 1, NULL, 0, 0)) {
close(mPipe[0]);
close(mPipe[1]);
throw std::runtime_error(std::string("Unable to watch pipe: ") + strerror(errno));
}
notifyStarted();
struct kevent events[128];
while (true) {
int event_count = kevent(mKqueue, NULL, 0, events, 128, 0);
if (event_count < 0 || events[0].flags == EV_ERROR) {
throw std::runtime_error(std::string("kevent error: ") + strerror(errno));
}
// Track all of the watchers that are touched so we can notify them at the end of the events.
std::unordered_set<WatcherRef> watchers;
for (int i = 0; i < event_count; i++) {
int flags = events[i].fflags;
int fd = events[i].ident;
if (fd == mPipe[0]) {
// pipe was written to. break out of the loop.
goto done;
}
auto it = mFdToEntry.find(fd);
if (it == mFdToEntry.end()) {
// If fd wasn't in our map, we may have already stopped watching it. Ignore the event.
continue;
}
DirEntry *entry = it->second;
if (flags & NOTE_WRITE && entry && entry->isDir) {
// If a write occurred on a directory, we have to diff the contents of that
// directory to determine what file was added/deleted.
compareDir(fd, entry->path, watchers);
} else {
std::vector<KqueueSubscription *> subs = findSubscriptions(entry->path);
for (auto it = subs.begin(); it != subs.end(); it++) {
KqueueSubscription *sub = *it;
if (flags & (NOTE_DELETE | NOTE_RENAME | NOTE_REVOKE)) {
sub->watcher->mEvents.remove(sub->path);
sub->tree->remove(sub->path);
mFdToEntry.erase((int)(size_t)entry->state);
mSubscriptions.erase(sub->path);
} else if (flags & (NOTE_WRITE | NOTE_ATTRIB | NOTE_EXTEND)) {
struct stat st;
lstat(sub->path.c_str(), &st);
if (entry->mtime != CONVERT_TIME(st.st_mtim)) {
entry->mtime = CONVERT_TIME(st.st_mtim);
sub->watcher->mEvents.update(sub->path);
}
}
watchers.insert(sub->watcher);
}
}
}
for (auto it = watchers.begin(); it != watchers.end(); it++) {
(*it)->notify();
}
}
done:
close(mPipe[0]);
close(mPipe[1]);
mEndedSignal.notify();
}
KqueueBackend::~KqueueBackend() {
write(mPipe[1], "X", 1);
mEndedSignal.wait();
}
void KqueueBackend::subscribe(WatcherRef watcher) {
// Build a full directory tree recursively, and watch each directory.
std::shared_ptr<DirTree> tree = getTree(watcher);
for (auto it = tree->entries.begin(); it != tree->entries.end(); it++) {
bool success = watchDir(watcher, it->second.path, tree);
if (!success) {
throw WatcherError(std::string("error watching " + watcher->mDir + ": " + strerror(errno)), watcher);
}
}
}
bool KqueueBackend::watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree) {
if (watcher->isIgnored(path)) {
return false;
}
DirEntry *entry = tree->find(path);
if (!entry) {
return false;
}
KqueueSubscription sub = {
.watcher = watcher,
.path = path,
.tree = tree
};
if (!entry->state) {
int fd = open(path.c_str(), O_EVTONLY);
if (fd <= 0) {
return false;
}
struct kevent event;
EV_SET(
&event,
fd,
EVFILT_VNODE,
EV_ADD | EV_CLEAR | EV_ENABLE,
NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_RENAME | NOTE_REVOKE,
0,
0
);
if (kevent(mKqueue, &event, 1, NULL, 0, 0)) {
close(fd);
return false;
}
entry->state = (void *)(size_t)fd;
mFdToEntry.emplace(fd, entry);
}
sub.fd = (int)(size_t)entry->state;
mSubscriptions.emplace(path, sub);
return true;
}
std::vector<KqueueSubscription *> KqueueBackend::findSubscriptions(std::string &path) {
// Find the subscriptions affected by this path.
// Copy pointers to them into a vector so that modifying mSubscriptions doesn't invalidate the iterator.
auto range = mSubscriptions.equal_range(path);
std::vector<KqueueSubscription *> subs;
for (auto it = range.first; it != range.second; it++) {
subs.push_back(&it->second);
}
return subs;
}
bool KqueueBackend::compareDir(int fd, std::string &path, std::unordered_set<WatcherRef> &watchers) {
// macOS doesn't support fdclosedir, so we have to duplicate the file descriptor
// to ensure the closedir doesn't also stop watching.
#if __APPLE__
fd = dup(fd);
#endif
DIR *dir = fdopendir(fd);
if (dir == NULL) {
return false;
}
// fdopendir doesn't rewind to the beginning.
rewinddir(dir);
std::vector<KqueueSubscription *> subs = findSubscriptions(path);
std::string dirStart = path + DIR_SEP;
std::unordered_set<std::shared_ptr<DirTree>> trees;
for (auto it = subs.begin(); it != subs.end(); it++) {
trees.emplace((*it)->tree);
}
std::unordered_set<std::string> entries;
struct dirent *entry;
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
std::string fullpath = dirStart + entry->d_name;
entries.emplace(fullpath);
for (auto it = trees.begin(); it != trees.end(); it++) {
std::shared_ptr<DirTree> tree = *it;
if (!tree->find(fullpath)) {
struct stat st;
fstatat(fd, entry->d_name, &st, AT_SYMLINK_NOFOLLOW);
tree->add(fullpath, CONVERT_TIME(st.st_mtim), S_ISDIR(st.st_mode));
// Notify all watchers with the same tree.
for (auto i = subs.begin(); i != subs.end(); i++) {
KqueueSubscription *sub = *i;
if (sub->tree == tree) {
if (sub->watcher->isIgnored(fullpath)) {
continue;
}
sub->watcher->mEvents.create(fullpath);
watchers.emplace(sub->watcher);
bool success = watchDir(sub->watcher, fullpath, sub->tree);
if (!success) {
sub->tree->remove(fullpath);
return false;
}
}
}
}
}
}
for (auto it = trees.begin(); it != trees.end(); it++) {
std::shared_ptr<DirTree> tree = *it;
for (auto entry = tree->entries.begin(); entry != tree->entries.end();) {
if (
entry->first.rfind(dirStart, 0) == 0 &&
entry->first.find(DIR_SEP, dirStart.length()) == std::string::npos &&
entries.count(entry->first) == 0
) {
// Notify all watchers with the same tree.
for (auto i = subs.begin(); i != subs.end(); i++) {
if ((*i)->tree == tree) {
KqueueSubscription *sub = *i;
if (!sub->watcher->isIgnored(entry->first)) {
sub->watcher->mEvents.remove(entry->first);
watchers.emplace(sub->watcher);
}
}
}
mFdToEntry.erase((int)(size_t)entry->second.state);
mSubscriptions.erase(entry->first);
entry = tree->entries.erase(entry);
} else {
entry++;
}
}
}
#if __APPLE__
closedir(dir);
#else
fdclosedir(dir);
#endif
return true;
}
void KqueueBackend::unsubscribe(WatcherRef watcher) {
// Find any subscriptions pointing to this watcher, and remove them.
for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) {
if (it->second.watcher.get() == watcher.get()) {
if (mSubscriptions.count(it->first) == 1) {
// Closing the file descriptor automatically unwatches it in the kqueue.
close(it->second.fd);
mFdToEntry.erase(it->second.fd);
}
it = mSubscriptions.erase(it);
} else {
it++;
}
}
}

View File

@ -1,35 +0,0 @@
#ifndef KQUEUE_H
#define KQUEUE_H
#include <unordered_map>
#include <sys/event.h>
#include "../shared/BruteForceBackend.hh"
#include "../DirTree.hh"
#include "../Signal.hh"
struct KqueueSubscription {
WatcherRef watcher;
std::string path;
std::shared_ptr<DirTree> tree;
int fd;
};
class KqueueBackend : public BruteForceBackend {
public:
void start() override;
~KqueueBackend();
void subscribe(WatcherRef watcher) override;
void unsubscribe(WatcherRef watcher) override;
private:
int mKqueue;
int mPipe[2];
std::unordered_multimap<std::string, KqueueSubscription> mSubscriptions;
std::unordered_map<int, DirEntry *> mFdToEntry;
Signal mEndedSignal;
bool watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree);
bool compareDir(int fd, std::string &dir, std::unordered_set<WatcherRef> &watchers);
std::vector<KqueueSubscription *> findSubscriptions(std::string &path);
};
#endif

View File

@ -1,232 +0,0 @@
#include <memory>
#include <poll.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "InotifyBackend.hh"
#define INOTIFY_MASK \
IN_ATTRIB | IN_CREATE | IN_DELETE | \
IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | \
IN_MOVED_TO | IN_DONT_FOLLOW | IN_ONLYDIR | IN_EXCL_UNLINK
#define BUFFER_SIZE 8192
#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
void InotifyBackend::start() {
// Create a pipe that we will write to when we want to end the thread.
int err = pipe2(mPipe, O_CLOEXEC | O_NONBLOCK);
if (err == -1) {
throw std::runtime_error(std::string("Unable to open pipe: ") + strerror(errno));
}
// Init inotify file descriptor.
mInotify = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (mInotify == -1) {
throw std::runtime_error(std::string("Unable to initialize inotify: ") + strerror(errno));
}
pollfd pollfds[2];
pollfds[0].fd = mPipe[0];
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
pollfds[1].fd = mInotify;
pollfds[1].events = POLLIN;
pollfds[1].revents = 0;
notifyStarted();
// Loop until we get an event from the pipe.
while (true) {
int result = poll(pollfds, 2, 500);
if (result < 0) {
throw std::runtime_error(std::string("Unable to poll: ") + strerror(errno));
}
if (pollfds[0].revents) {
break;
}
if (pollfds[1].revents) {
handleEvents();
}
}
close(mPipe[0]);
close(mPipe[1]);
close(mInotify);
mEndedSignal.notify();
}
InotifyBackend::~InotifyBackend() {
write(mPipe[1], "X", 1);
mEndedSignal.wait();
}
// This function is called by Backend::watch which takes a lock on mMutex
void InotifyBackend::subscribe(WatcherRef watcher) {
// Build a full directory tree recursively, and watch each directory.
std::shared_ptr<DirTree> tree = getTree(watcher);
for (auto it = tree->entries.begin(); it != tree->entries.end(); it++) {
if (it->second.isDir) {
bool success = watchDir(watcher, it->second.path, tree);
if (!success) {
throw WatcherError(std::string("inotify_add_watch on '") + it->second.path + std::string("' failed: ") + strerror(errno), watcher);
}
}
}
}
bool InotifyBackend::watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree) {
int wd = inotify_add_watch(mInotify, path.c_str(), INOTIFY_MASK);
if (wd == -1) {
return false;
}
std::shared_ptr<InotifySubscription> sub = std::make_shared<InotifySubscription>();
sub->tree = tree;
sub->path = path;
sub->watcher = watcher;
mSubscriptions.emplace(wd, sub);
return true;
}
void InotifyBackend::handleEvents() {
char buf[BUFFER_SIZE] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
struct inotify_event *event;
// Track all of the watchers that are touched so we can notify them at the end of the events.
std::unordered_set<WatcherRef> watchers;
while (true) {
int n = read(mInotify, &buf, BUFFER_SIZE);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
throw std::runtime_error(std::string("Error reading from inotify: ") + strerror(errno));
}
if (n == 0) {
break;
}
for (char *ptr = buf; ptr < buf + n; ptr += sizeof(*event) + event->len) {
event = (struct inotify_event *)ptr;
if ((event->mask & IN_Q_OVERFLOW) == IN_Q_OVERFLOW) {
// overflow
continue;
}
handleEvent(event, watchers);
}
}
for (auto it = watchers.begin(); it != watchers.end(); it++) {
(*it)->notify();
}
}
void InotifyBackend::handleEvent(struct inotify_event *event, std::unordered_set<WatcherRef> &watchers) {
std::unique_lock<std::mutex> lock(mMutex);
// Find the subscriptions for this watch descriptor
auto range = mSubscriptions.equal_range(event->wd);
std::unordered_set<std::shared_ptr<InotifySubscription>> set;
for (auto it = range.first; it != range.second; it++) {
set.insert(it->second);
}
for (auto it = set.begin(); it != set.end(); it++) {
if (handleSubscription(event, *it)) {
watchers.insert((*it)->watcher);
}
}
}
bool InotifyBackend::handleSubscription(struct inotify_event *event, std::shared_ptr<InotifySubscription> sub) {
// Build full path and check if its in our ignore list.
std::shared_ptr<Watcher> watcher = sub->watcher;
std::string path = std::string(sub->path);
bool isDir = event->mask & IN_ISDIR;
if (event->len > 0) {
path += "/" + std::string(event->name);
}
if (watcher->isIgnored(path)) {
return false;
}
// If this is a create, check if it's a directory and start watching if it is.
// In any case, keep the directory tree up to date.
if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
watcher->mEvents.create(path);
struct stat st;
// Use lstat to avoid resolving symbolic links that we cannot watch anyway
// https://github.com/parcel-bundler/watcher/issues/76
lstat(path.c_str(), &st);
DirEntry *entry = sub->tree->add(path, CONVERT_TIME(st.st_mtim), S_ISDIR(st.st_mode));
if (entry->isDir) {
bool success = watchDir(watcher, path, sub->tree);
if (!success) {
sub->tree->remove(path);
return false;
}
}
} else if (event->mask & (IN_MODIFY | IN_ATTRIB)) {
watcher->mEvents.update(path);
struct stat st;
stat(path.c_str(), &st);
sub->tree->update(path, CONVERT_TIME(st.st_mtim));
} else if (event->mask & (IN_DELETE | IN_DELETE_SELF | IN_MOVED_FROM | IN_MOVE_SELF)) {
bool isSelfEvent = (event->mask & (IN_DELETE_SELF | IN_MOVE_SELF));
// Ignore delete/move self events unless this is the recursive watch root
if (isSelfEvent && path != watcher->mDir) {
return false;
}
// If the entry being deleted/moved is a directory, remove it from the list of subscriptions
// XXX: self events don't have the IN_ISDIR mask
if (isSelfEvent || isDir) {
for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) {
if (it->second->path == path) {
it = mSubscriptions.erase(it);
} else {
++it;
}
}
}
watcher->mEvents.remove(path);
sub->tree->remove(path);
}
return true;
}
// This function is called by Backend::unwatch which takes a lock on mMutex
void InotifyBackend::unsubscribe(WatcherRef watcher) {
// Find any subscriptions pointing to this watcher, and remove them.
for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) {
if (it->second->watcher.get() == watcher.get()) {
if (mSubscriptions.count(it->first) == 1) {
int err = inotify_rm_watch(mInotify, it->first);
if (err == -1) {
throw WatcherError(std::string("Unable to remove watcher: ") + strerror(errno), watcher);
}
}
it = mSubscriptions.erase(it);
} else {
it++;
}
}
}

View File

@ -1,34 +0,0 @@
#ifndef INOTIFY_H
#define INOTIFY_H
#include <unordered_map>
#include <sys/inotify.h>
#include "../shared/BruteForceBackend.hh"
#include "../DirTree.hh"
#include "../Signal.hh"
struct InotifySubscription {
std::shared_ptr<DirTree> tree;
std::string path;
WatcherRef watcher;
};
class InotifyBackend : public BruteForceBackend {
public:
void start() override;
~InotifyBackend();
void subscribe(WatcherRef watcher) override;
void unsubscribe(WatcherRef watcher) override;
private:
int mPipe[2];
int mInotify;
std::unordered_multimap<int, std::shared_ptr<InotifySubscription>> mSubscriptions;
Signal mEndedSignal;
bool watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree);
void handleEvents();
void handleEvent(struct inotify_event *event, std::unordered_set<WatcherRef> &watchers);
bool handleSubscription(struct inotify_event *event, std::shared_ptr<InotifySubscription> sub);
};
#endif

View File

@ -1,325 +0,0 @@
#include <CoreServices/CoreServices.h>
#include <sys/stat.h>
#include <string>
#include <fstream>
#include <unordered_set>
#include "../Event.hh"
#include "../Backend.hh"
#include "./FSEventsBackend.hh"
#include "../Watcher.hh"
#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
#define IGNORED_FLAGS (kFSEventStreamEventFlagItemIsHardlink | kFSEventStreamEventFlagItemIsLastHardlink | kFSEventStreamEventFlagItemIsSymlink | kFSEventStreamEventFlagItemIsDir | kFSEventStreamEventFlagItemIsFile)
void stopStream(FSEventStreamRef stream, CFRunLoopRef runLoop) {
FSEventStreamStop(stream);
FSEventStreamUnscheduleFromRunLoop(stream, runLoop, kCFRunLoopDefaultMode);
FSEventStreamInvalidate(stream);
FSEventStreamRelease(stream);
}
// macOS has a case insensitive file system by default. In order to detect
// file renames that only affect case, we need to get the canonical path
// and compare it with the input path to determine if a file was created or deleted.
bool pathExists(char *path) {
int fd = open(path, O_RDONLY | O_SYMLINK);
if (fd == -1) {
return false;
}
char buf[PATH_MAX];
if (fcntl(fd, F_GETPATH, buf) == -1) {
close(fd);
return false;
}
bool res = strncmp(path, buf, PATH_MAX) == 0;
close(fd);
return res;
}
class State: public WatcherState {
public:
FSEventStreamRef stream;
std::shared_ptr<DirTree> tree;
uint64_t since;
};
void FSEventsCallback(
ConstFSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[]
) {
char **paths = (char **)eventPaths;
std::shared_ptr<Watcher>& watcher = *static_cast<std::shared_ptr<Watcher> *>(clientCallBackInfo);
EventList& list = watcher->mEvents;
if (watcher->state == nullptr) {
return;
}
auto stateGuard = watcher->state;
auto* state = static_cast<State*>(stateGuard.get());
uint64_t since = state->since;
bool deletedRoot = false;
for (size_t i = 0; i < numEvents; ++i) {
bool isCreated = (eventFlags[i] & kFSEventStreamEventFlagItemCreated) == kFSEventStreamEventFlagItemCreated;
bool isRemoved = (eventFlags[i] & kFSEventStreamEventFlagItemRemoved) == kFSEventStreamEventFlagItemRemoved;
bool isModified = (eventFlags[i] & kFSEventStreamEventFlagItemModified) == kFSEventStreamEventFlagItemModified ||
(eventFlags[i] & kFSEventStreamEventFlagItemInodeMetaMod) == kFSEventStreamEventFlagItemInodeMetaMod ||
(eventFlags[i] & kFSEventStreamEventFlagItemFinderInfoMod) == kFSEventStreamEventFlagItemFinderInfoMod ||
(eventFlags[i] & kFSEventStreamEventFlagItemChangeOwner) == kFSEventStreamEventFlagItemChangeOwner ||
(eventFlags[i] & kFSEventStreamEventFlagItemXattrMod) == kFSEventStreamEventFlagItemXattrMod;
bool isRenamed = (eventFlags[i] & kFSEventStreamEventFlagItemRenamed) == kFSEventStreamEventFlagItemRenamed;
bool isDone = (eventFlags[i] & kFSEventStreamEventFlagHistoryDone) == kFSEventStreamEventFlagHistoryDone;
bool isDir = (eventFlags[i] & kFSEventStreamEventFlagItemIsDir) == kFSEventStreamEventFlagItemIsDir;
if (isDone) {
watcher->notify();
break;
}
auto ignoredFlags = IGNORED_FLAGS;
if (__builtin_available(macOS 10.13, *)) {
ignoredFlags |= kFSEventStreamEventFlagItemCloned;
}
// If we don't care about any of the flags that are set, ignore this event.
if ((eventFlags[i] & ~ignoredFlags) == 0) {
continue;
}
// FSEvents exclusion paths only apply to files, not directories.
if (watcher->isIgnored(paths[i])) {
continue;
}
// Handle unambiguous events first
if (isCreated && !(isRemoved || isModified || isRenamed)) {
state->tree->add(paths[i], 0, isDir);
list.create(paths[i]);
} else if (isRemoved && !(isCreated || isModified || isRenamed)) {
state->tree->remove(paths[i]);
list.remove(paths[i]);
if (paths[i] == watcher->mDir) {
deletedRoot = true;
}
} else if (isModified && !(isCreated || isRemoved || isRenamed)) {
struct stat file;
if (stat(paths[i], &file)) {
continue;
}
// Ignore if mtime is the same as the last event.
// This prevents duplicate events from being emitted.
// If tv_nsec is zero, the file system probably only has second-level
// granularity so allow the even through in that case.
uint64_t mtime = CONVERT_TIME(file.st_mtimespec);
DirEntry *entry = state->tree->find(paths[i]);
if (entry && mtime == entry->mtime && file.st_mtimespec.tv_nsec != 0) {
continue;
}
if (entry) {
// Update mtime.
entry->mtime = mtime;
} else {
// Add to tree if this path has not been discovered yet.
state->tree->add(paths[i], mtime, S_ISDIR(file.st_mode));
}
list.update(paths[i]);
} else {
// If multiple flags were set, then we need to call `stat` to determine if the file really exists.
// This helps disambiguate creates, updates, and deletes.
struct stat file;
if (stat(paths[i], &file) || !pathExists(paths[i])) {
// File does not exist, so we have to assume it was removed. This is not exact since the
// flags set by fsevents get coalesced together (e.g. created & deleted), so there is no way to
// know whether the create and delete both happened since our snapshot (in which case
// we'd rather ignore this event completely). This will result in some extra delete events
// being emitted for files we don't know about, but that is the best we can do.
state->tree->remove(paths[i]);
list.remove(paths[i]);
if (paths[i] == watcher->mDir) {
deletedRoot = true;
}
continue;
}
// If the file was modified, and existed before, then this is an update, otherwise a create.
uint64_t ctime = CONVERT_TIME(file.st_birthtimespec);
uint64_t mtime = CONVERT_TIME(file.st_mtimespec);
DirEntry *entry = !since ? state->tree->find(paths[i]) : NULL;
if (entry && entry->mtime == mtime && file.st_mtimespec.tv_nsec != 0) {
continue;
}
// Some mounted file systems report a creation time of 0/unix epoch which we special case.
if (isModified && (entry || (ctime <= since && ctime != 0))) {
state->tree->update(paths[i], mtime);
list.update(paths[i]);
} else {
state->tree->add(paths[i], mtime, S_ISDIR(file.st_mode));
list.create(paths[i]);
}
}
}
watcher->notify();
// Stop watching if the root directory was deleted.
if (deletedRoot) {
stopStream((FSEventStreamRef)streamRef, CFRunLoopGetCurrent());
watcher->state = nullptr;
}
}
void checkWatcher(WatcherRef watcher) {
struct stat file;
if (stat(watcher->mDir.c_str(), &file)) {
throw WatcherError(strerror(errno), watcher);
}
if (!S_ISDIR(file.st_mode)) {
throw WatcherError(strerror(ENOTDIR), watcher);
}
}
void FSEventsBackend::startStream(WatcherRef watcher, FSEventStreamEventId id) {
checkWatcher(watcher);
CFAbsoluteTime latency = 0.001;
CFStringRef fileWatchPath = CFStringCreateWithCString(
NULL,
watcher->mDir.c_str(),
kCFStringEncodingUTF8
);
CFArrayRef pathsToWatch = CFArrayCreate(
NULL,
(const void **)&fileWatchPath,
1,
NULL
);
// Make a watcher reference we can pass into the callback. This ensures bumped ref-count.
std::shared_ptr<Watcher>* callbackWatcher = new std::shared_ptr<Watcher> (watcher);
FSEventStreamContext callbackInfo {0, static_cast<void*> (callbackWatcher), nullptr, nullptr, nullptr};
FSEventStreamRef stream = FSEventStreamCreate(
NULL,
&FSEventsCallback,
&callbackInfo,
pathsToWatch,
id,
latency,
kFSEventStreamCreateFlagFileEvents
);
CFMutableArrayRef exclusions = CFArrayCreateMutable(NULL, watcher->mIgnorePaths.size(), NULL);
for (auto it = watcher->mIgnorePaths.begin(); it != watcher->mIgnorePaths.end(); it++) {
CFStringRef path = CFStringCreateWithCString(
NULL,
it->c_str(),
kCFStringEncodingUTF8
);
CFArrayAppendValue(exclusions, (const void *)path);
}
FSEventStreamSetExclusionPaths(stream, exclusions);
FSEventStreamScheduleWithRunLoop(stream, mRunLoop, kCFRunLoopDefaultMode);
bool started = FSEventStreamStart(stream);
CFRelease(pathsToWatch);
CFRelease(fileWatchPath);
if (!started) {
FSEventStreamRelease(stream);
throw WatcherError("Error starting FSEvents stream", watcher);
}
auto stateGuard = watcher->state;
State* s = static_cast<State*>(stateGuard.get());
s->tree = std::make_shared<DirTree>(watcher->mDir);
s->stream = stream;
}
void FSEventsBackend::start() {
mRunLoop = CFRunLoopGetCurrent();
CFRetain(mRunLoop);
// Unlock once run loop has started.
CFRunLoopPerformBlock(mRunLoop, kCFRunLoopDefaultMode, ^ {
notifyStarted();
});
CFRunLoopWakeUp(mRunLoop);
CFRunLoopRun();
}
FSEventsBackend::~FSEventsBackend() {
std::unique_lock<std::mutex> lock(mMutex);
CFRunLoopStop(mRunLoop);
CFRelease(mRunLoop);
}
void FSEventsBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) {
std::unique_lock<std::mutex> lock(mMutex);
checkWatcher(watcher);
FSEventStreamEventId id = FSEventsGetCurrentEventId();
std::ofstream ofs(*snapshotPath);
ofs << id;
ofs << "\n";
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
ofs << CONVERT_TIME(now);
}
void FSEventsBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) {
std::unique_lock<std::mutex> lock(mMutex);
std::ifstream ifs(*snapshotPath);
if (ifs.fail()) {
return;
}
FSEventStreamEventId id;
uint64_t since;
ifs >> id;
ifs >> since;
auto s = std::make_shared<State>();
s->since = since;
watcher->state = s;
startStream(watcher, id);
watcher->wait();
stopStream(s->stream, mRunLoop);
watcher->state = nullptr;
}
// This function is called by Backend::watch which takes a lock on mMutex
void FSEventsBackend::subscribe(WatcherRef watcher) {
auto s = std::make_shared<State>();
s->since = 0;
watcher->state = s;
startStream(watcher, kFSEventStreamEventIdSinceNow);
}
// This function is called by Backend::unwatch which takes a lock on mMutex
void FSEventsBackend::unsubscribe(WatcherRef watcher) {
auto stateGuard = watcher->state;
State* s = static_cast<State*>(stateGuard.get());
if (s != nullptr) {
stopStream(s->stream, mRunLoop);
watcher->state = nullptr;
}
}

View File

@ -1,20 +0,0 @@
#ifndef FS_EVENTS_H
#define FS_EVENTS_H
#include <CoreServices/CoreServices.h>
#include "../Backend.hh"
class FSEventsBackend : public Backend {
public:
void start() override;
~FSEventsBackend();
void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override;
void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override;
void subscribe(WatcherRef watcher) override;
void unsubscribe(WatcherRef watcher) override;
private:
void startStream(WatcherRef watcher, FSEventStreamEventId id);
CFRunLoopRef mRunLoop;
};
#endif

View File

@ -1,41 +0,0 @@
#include <string>
#include "../DirTree.hh"
#include "../Event.hh"
#include "./BruteForceBackend.hh"
std::shared_ptr<DirTree> BruteForceBackend::getTree(WatcherRef watcher, bool shouldRead) {
auto tree = DirTree::getCached(watcher->mDir);
// If the tree is not complete, read it if needed.
if (!tree->isComplete && shouldRead) {
readTree(watcher, tree);
tree->isComplete = true;
}
return tree;
}
void BruteForceBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) {
std::unique_lock<std::mutex> lock(mMutex);
auto tree = getTree(watcher);
FILE *f = fopen(snapshotPath->c_str(), "w");
if (!f) {
throw std::runtime_error(std::string("Unable to open snapshot file: ") + strerror(errno));
}
tree->write(f);
fclose(f);
}
void BruteForceBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) {
std::unique_lock<std::mutex> lock(mMutex);
FILE *f = fopen(snapshotPath->c_str(), "r");
if (!f) {
throw std::runtime_error(std::string("Unable to open snapshot file: ") + strerror(errno));
}
DirTree snapshot{watcher->mDir, f};
auto now = getTree(watcher);
now->getChanges(&snapshot, watcher->mEvents);
fclose(f);
}

View File

@ -1,25 +0,0 @@
#ifndef BRUTE_FORCE_H
#define BRUTE_FORCE_H
#include "../Backend.hh"
#include "../DirTree.hh"
#include "../Watcher.hh"
class BruteForceBackend : public Backend {
public:
void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override;
void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override;
void subscribe(WatcherRef watcher) override {
throw "Brute force backend doesn't support subscriptions.";
}
void unsubscribe(WatcherRef watcher) override {
throw "Brute force backend doesn't support subscriptions.";
}
std::shared_ptr<DirTree> getTree(WatcherRef watcher, bool shouldRead = true);
private:
void readTree(WatcherRef watcher, std::shared_ptr<DirTree> tree);
};
#endif

View File

@ -1,50 +0,0 @@
#include <string>
// weird error on linux
#ifdef __THROW
#undef __THROW
#endif
#define __THROW
#include <fts.h>
#include <sys/stat.h>
#include "../DirTree.hh"
#include "../shared/BruteForceBackend.hh"
#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
#if __APPLE__
#define st_mtim st_mtimespec
#endif
void BruteForceBackend::readTree(WatcherRef watcher, std::shared_ptr<DirTree> tree) {
char *paths[2] {(char *)watcher->mDir.c_str(), NULL};
FTS *fts = fts_open(paths, FTS_NOCHDIR | FTS_PHYSICAL, NULL);
if (!fts) {
throw WatcherError(strerror(errno), watcher);
}
FTSENT *node;
bool isRoot = true;
while ((node = fts_read(fts)) != NULL) {
if (node->fts_errno) {
fts_close(fts);
throw WatcherError(strerror(node->fts_errno), watcher);
}
if (isRoot && !(node->fts_info & FTS_D)) {
fts_close(fts);
throw WatcherError(strerror(ENOTDIR), watcher);
}
if (watcher->isIgnored(std::string(node->fts_path))) {
fts_set(fts, node, FTS_SKIP);
continue;
}
tree->add(node->fts_path, CONVERT_TIME(node->fts_statp->st_mtim), (node->fts_info & FTS_D) == FTS_D);
isRoot = false;
}
fts_close(fts);
}

View File

@ -1,77 +0,0 @@
#include <string>
// weird error on linux
#ifdef __THROW
#undef __THROW
#endif
#define __THROW
#ifdef _LIBC
# include <include/sys/stat.h>
#else
# include <sys/stat.h>
#endif
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#include "../DirTree.hh"
#include "../shared/BruteForceBackend.hh"
#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
#if __APPLE__
#define st_mtim st_mtimespec
#endif
#define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
void iterateDir(WatcherRef watcher, const std::shared_ptr <DirTree> tree, const char *relative, int parent_fd, const std::string &dirname) {
int open_flags = (O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW);
int new_fd = openat(parent_fd, relative, open_flags);
if (new_fd == -1) {
if (errno == EACCES) {
return; // ignore insufficient permissions
}
throw WatcherError(strerror(errno), watcher);
}
struct stat rootAttributes;
fstatat(new_fd, ".", &rootAttributes, AT_SYMLINK_NOFOLLOW);
tree->add(dirname, CONVERT_TIME(rootAttributes.st_mtim), true);
if (DIR *dir = fdopendir(new_fd)) {
while (struct dirent *ent = (errno = 0, readdir(dir))) {
if (ISDOT(ent->d_name)) continue;
std::string fullPath = dirname + "/" + ent->d_name;
if (!watcher->isIgnored(fullPath)) {
struct stat attrib;
fstatat(new_fd, ent->d_name, &attrib, AT_SYMLINK_NOFOLLOW);
bool isDir = ent->d_type == DT_DIR;
if (isDir) {
iterateDir(watcher, tree, ent->d_name, new_fd, fullPath);
} else {
tree->add(fullPath, CONVERT_TIME(attrib.st_mtim), isDir);
}
}
}
closedir(dir);
} else {
close(new_fd);
}
if (errno) {
throw WatcherError(strerror(errno), watcher);
}
}
void BruteForceBackend::readTree(WatcherRef watcher, std::shared_ptr <DirTree> tree) {
int fd = open(watcher->mDir.c_str(), O_RDONLY);
if (fd) {
iterateDir(watcher, tree, ".", fd, watcher->mDir);
close(fd);
}
}

View File

@ -1,132 +0,0 @@
#include <sys/stat.h>
#include "WasmBackend.hh"
#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
void WasmBackend::start() {
notifyStarted();
}
void WasmBackend::subscribe(WatcherRef watcher) {
// Build a full directory tree recursively, and watch each directory.
std::shared_ptr<DirTree> tree = getTree(watcher);
for (auto it = tree->entries.begin(); it != tree->entries.end(); it++) {
if (it->second.isDir) {
watchDir(watcher, it->second.path, tree);
}
}
}
void WasmBackend::watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree) {
int wd = wasm_backend_add_watch(path.c_str(), (void *)this);
std::shared_ptr<WasmSubscription> sub = std::make_shared<WasmSubscription>();
sub->tree = tree;
sub->path = path;
sub->watcher = watcher;
mSubscriptions.emplace(wd, sub);
}
extern "C" void wasm_backend_event_handler(void *backend, int wd, int type, char *filename) {
WasmBackend *b = (WasmBackend *)(backend);
b->handleEvent(wd, type, filename);
}
void WasmBackend::handleEvent(int wd, int type, char *filename) {
// Find the subscriptions for this watch descriptor
auto range = mSubscriptions.equal_range(wd);
std::unordered_set<std::shared_ptr<WasmSubscription>> set;
for (auto it = range.first; it != range.second; it++) {
set.insert(it->second);
}
for (auto it = set.begin(); it != set.end(); it++) {
if (handleSubscription(type, filename, *it)) {
(*it)->watcher->notify();
}
}
}
bool WasmBackend::handleSubscription(int type, char *filename, std::shared_ptr<WasmSubscription> sub) {
// Build full path and check if its in our ignore list.
WatcherRef watcher = sub->watcher;
std::string path = std::string(sub->path);
if (filename[0] != '\0') {
path += "/" + std::string(filename);
}
if (watcher->isIgnored(path)) {
return false;
}
if (type == 1) {
struct stat st;
stat(path.c_str(), &st);
sub->tree->update(path, CONVERT_TIME(st.st_mtim));
watcher->mEvents.update(path);
} else if (type == 2) {
// Determine if this is a create or delete depending on if the file exists or not.
struct stat st;
if (lstat(path.c_str(), &st)) {
// If the entry being deleted/moved is a directory, remove it from the list of subscriptions
DirEntry *entry = sub->tree->find(path);
if (!entry) {
return false;
}
if (entry->isDir) {
std::string pathStart = path + DIR_SEP;
for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) {
if (it->second->path == path || it->second->path.rfind(pathStart, 0) == 0) {
wasm_backend_remove_watch(it->first);
it = mSubscriptions.erase(it);
} else {
++it;
}
}
// Remove all sub-entries
for (auto it = sub->tree->entries.begin(); it != sub->tree->entries.end();) {
if (it->first.rfind(pathStart, 0) == 0) {
watcher->mEvents.remove(it->first);
it = sub->tree->entries.erase(it);
} else {
it++;
}
}
}
watcher->mEvents.remove(path);
sub->tree->remove(path);
} else if (sub->tree->find(path)) {
sub->tree->update(path, CONVERT_TIME(st.st_mtim));
watcher->mEvents.update(path);
} else {
watcher->mEvents.create(path);
// If this is a create, check if it's a directory and start watching if it is.
DirEntry *entry = sub->tree->add(path, CONVERT_TIME(st.st_mtim), S_ISDIR(st.st_mode));
if (entry->isDir) {
watchDir(watcher, path, sub->tree);
}
}
}
return true;
}
void WasmBackend::unsubscribe(WatcherRef watcher) {
// Find any subscriptions pointing to this watcher, and remove them.
for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) {
if (it->second->watcher.get() == watcher.get()) {
if (mSubscriptions.count(it->first) == 1) {
wasm_backend_remove_watch(it->first);
}
it = mSubscriptions.erase(it);
} else {
it++;
}
}
}

View File

@ -1,34 +0,0 @@
#ifndef WASM_H
#define WASM_H
#include <unordered_map>
#include "../shared/BruteForceBackend.hh"
#include "../DirTree.hh"
extern "C" {
int wasm_backend_add_watch(const char *filename, void *backend);
void wasm_backend_remove_watch(int wd);
void wasm_backend_event_handler(void *backend, int wd, int type, char *filename);
};
struct WasmSubscription {
std::shared_ptr<DirTree> tree;
std::string path;
WatcherRef watcher;
};
class WasmBackend : public BruteForceBackend {
public:
void start() override;
void subscribe(WatcherRef watcher) override;
void unsubscribe(WatcherRef watcher) override;
void handleEvent(int wd, int type, char *filename);
private:
int mWasm;
std::unordered_multimap<int, std::shared_ptr<WasmSubscription>> mSubscriptions;
void watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree);
bool handleSubscription(int type, char *filename, std::shared_ptr<WasmSubscription> sub);
};
#endif

View File

@ -1,74 +0,0 @@
/*
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.
*/
// Node does not include the headers for these functions when compiling for WASM, so add them here.
#ifdef __wasm32__
extern "C" {
NAPI_EXTERN napi_status NAPI_CDECL
napi_create_threadsafe_function(napi_env env,
napi_value func,
napi_value async_resource,
napi_value async_resource_name,
size_t max_queue_size,
size_t initial_thread_count,
void* thread_finalize_data,
napi_finalize thread_finalize_cb,
void* context,
napi_threadsafe_function_call_js call_js_cb,
napi_threadsafe_function* result);
NAPI_EXTERN napi_status NAPI_CDECL napi_get_threadsafe_function_context(
napi_threadsafe_function func, void** result);
NAPI_EXTERN napi_status NAPI_CDECL
napi_call_threadsafe_function(napi_threadsafe_function func,
void* data,
napi_threadsafe_function_call_mode is_blocking);
NAPI_EXTERN napi_status NAPI_CDECL
napi_acquire_threadsafe_function(napi_threadsafe_function func);
NAPI_EXTERN napi_status NAPI_CDECL napi_release_threadsafe_function(
napi_threadsafe_function func, napi_threadsafe_function_release_mode mode);
NAPI_EXTERN napi_status NAPI_CDECL
napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func);
NAPI_EXTERN napi_status NAPI_CDECL
napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func);
NAPI_EXTERN napi_status NAPI_CDECL
napi_create_async_work(napi_env env,
napi_value async_resource,
napi_value async_resource_name,
napi_async_execute_callback execute,
napi_async_complete_callback complete,
void* data,
napi_async_work* result);
NAPI_EXTERN napi_status NAPI_CDECL napi_delete_async_work(napi_env env,
napi_async_work work);
NAPI_EXTERN napi_status NAPI_CDECL napi_queue_async_work(napi_env env,
napi_async_work work);
NAPI_EXTERN napi_status NAPI_CDECL napi_cancel_async_work(napi_env env,
napi_async_work work);
}
#endif

View File

@ -1,302 +0,0 @@
#include <stdint.h>
#include "./BSER.hh"
BSERType decodeType(std::istream &iss) {
int8_t type;
iss.read(reinterpret_cast<char*>(&type), sizeof(type));
return (BSERType) type;
}
void expectType(std::istream &iss, BSERType expected) {
BSERType got = decodeType(iss);
if (got != expected) {
throw std::runtime_error("Unexpected BSER type");
}
}
void encodeType(std::ostream &oss, BSERType type) {
int8_t t = (int8_t)type;
oss.write(reinterpret_cast<char*>(&t), sizeof(t));
}
template<typename T>
class Value : public BSERValue {
public:
T value;
Value(T val) {
value = val;
}
Value() {}
};
class BSERInteger : public Value<int64_t> {
public:
BSERInteger(int64_t value) : Value(value) {}
BSERInteger(std::istream &iss) {
int8_t int8;
int16_t int16;
int32_t int32;
int64_t int64;
BSERType type = decodeType(iss);
switch (type) {
case BSER_INT8:
iss.read(reinterpret_cast<char*>(&int8), sizeof(int8));
value = int8;
break;
case BSER_INT16:
iss.read(reinterpret_cast<char*>(&int16), sizeof(int16));
value = int16;
break;
case BSER_INT32:
iss.read(reinterpret_cast<char*>(&int32), sizeof(int32));
value = int32;
break;
case BSER_INT64:
iss.read(reinterpret_cast<char*>(&int64), sizeof(int64));
value = int64;
break;
default:
throw std::runtime_error("Invalid BSER int type");
}
}
int64_t intValue() override {
return value;
}
void encode(std::ostream &oss) override {
if (value <= INT8_MAX) {
encodeType(oss, BSER_INT8);
int8_t v = (int8_t)value;
oss.write(reinterpret_cast<char*>(&v), sizeof(v));
} else if (value <= INT16_MAX) {
encodeType(oss, BSER_INT16);
int16_t v = (int16_t)value;
oss.write(reinterpret_cast<char*>(&v), sizeof(v));
} else if (value <= INT32_MAX) {
encodeType(oss, BSER_INT32);
int32_t v = (int32_t)value;
oss.write(reinterpret_cast<char*>(&v), sizeof(v));
} else {
encodeType(oss, BSER_INT64);
oss.write(reinterpret_cast<char*>(&value), sizeof(value));
}
}
};
class BSERArray : public Value<BSER::Array> {
public:
BSERArray() : Value() {}
BSERArray(BSER::Array value) : Value(value) {}
BSERArray(std::istream &iss) {
expectType(iss, BSER_ARRAY);
int64_t len = BSERInteger(iss).intValue();
for (int64_t i = 0; i < len; i++) {
value.push_back(BSER(iss));
}
}
BSER::Array arrayValue() override {
return value;
}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_ARRAY);
BSERInteger(value.size()).encode(oss);
for (auto it = value.begin(); it != value.end(); it++) {
it->encode(oss);
}
}
};
class BSERString : public Value<std::string> {
public:
BSERString(std::string value) : Value(value) {}
BSERString(std::istream &iss) {
expectType(iss, BSER_STRING);
int64_t len = BSERInteger(iss).intValue();
value.resize(len);
iss.read(&value[0], len);
}
std::string stringValue() override {
return value;
}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_STRING);
BSERInteger(value.size()).encode(oss);
oss << value;
}
};
class BSERObject : public Value<BSER::Object> {
public:
BSERObject() : Value() {}
BSERObject(BSER::Object value) : Value(value) {}
BSERObject(std::istream &iss) {
expectType(iss, BSER_OBJECT);
int64_t len = BSERInteger(iss).intValue();
for (int64_t i = 0; i < len; i++) {
auto key = BSERString(iss).stringValue();
auto val = BSER(iss);
value.emplace(key, val);
}
}
BSER::Object objectValue() override {
return value;
}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_OBJECT);
BSERInteger(value.size()).encode(oss);
for (auto it = value.begin(); it != value.end(); it++) {
BSERString(it->first).encode(oss);
it->second.encode(oss);
}
}
};
class BSERDouble : public Value<double> {
public:
BSERDouble(double value) : Value(value) {}
BSERDouble(std::istream &iss) {
expectType(iss, BSER_REAL);
iss.read(reinterpret_cast<char*>(&value), sizeof(value));
}
double doubleValue() override {
return value;
}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_REAL);
oss.write(reinterpret_cast<char*>(&value), sizeof(value));
}
};
class BSERBoolean : public Value<bool> {
public:
BSERBoolean(bool value) : Value(value) {}
bool boolValue() override { return value; }
void encode(std::ostream &oss) override {
int8_t t = value == true ? BSER_BOOL_TRUE : BSER_BOOL_FALSE;
oss.write(reinterpret_cast<char*>(&t), sizeof(t));
}
};
class BSERNull : public Value<bool> {
public:
BSERNull() : Value(false) {}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_NULL);
}
};
std::shared_ptr<BSERArray> decodeTemplate(std::istream &iss) {
expectType(iss, BSER_TEMPLATE);
auto keys = BSERArray(iss).arrayValue();
auto len = BSERInteger(iss).intValue();
std::shared_ptr<BSERArray> arr = std::make_shared<BSERArray>();
for (int64_t i = 0; i < len; i++) {
BSER::Object obj;
for (auto it = keys.begin(); it != keys.end(); it++) {
if (iss.peek() == 0x0c) {
iss.ignore(1);
continue;
}
auto val = BSER(iss);
obj.emplace(it->stringValue(), val);
}
arr->value.push_back(obj);
}
return arr;
}
BSER::BSER(std::istream &iss) {
BSERType type = decodeType(iss);
iss.unget();
switch (type) {
case BSER_ARRAY:
m_ptr = std::make_shared<BSERArray>(iss);
break;
case BSER_OBJECT:
m_ptr = std::make_shared<BSERObject>(iss);
break;
case BSER_STRING:
m_ptr = std::make_shared<BSERString>(iss);
break;
case BSER_INT8:
case BSER_INT16:
case BSER_INT32:
case BSER_INT64:
m_ptr = std::make_shared<BSERInteger>(iss);
break;
case BSER_REAL:
m_ptr = std::make_shared<BSERDouble>(iss);
break;
case BSER_BOOL_TRUE:
iss.ignore(1);
m_ptr = std::make_shared<BSERBoolean>(true);
break;
case BSER_BOOL_FALSE:
iss.ignore(1);
m_ptr = std::make_shared<BSERBoolean>(false);
break;
case BSER_NULL:
iss.ignore(1);
m_ptr = std::make_shared<BSERNull>();
break;
case BSER_TEMPLATE:
m_ptr = decodeTemplate(iss);
break;
default:
throw std::runtime_error("unknown BSER type");
}
}
BSER::BSER() : m_ptr(std::make_shared<BSERNull>()) {}
BSER::BSER(BSER::Array value) : m_ptr(std::make_shared<BSERArray>(value)) {}
BSER::BSER(BSER::Object value) : m_ptr(std::make_shared<BSERObject>(value)) {}
BSER::BSER(const char *value) : m_ptr(std::make_shared<BSERString>(value)) {}
BSER::BSER(std::string value) : m_ptr(std::make_shared<BSERString>(value)) {}
BSER::BSER(int64_t value) : m_ptr(std::make_shared<BSERInteger>(value)) {}
BSER::BSER(double value) : m_ptr(std::make_shared<BSERDouble>(value)) {}
BSER::BSER(bool value) : m_ptr(std::make_shared<BSERBoolean>(value)) {}
BSER::Array BSER::arrayValue() { return m_ptr->arrayValue(); }
BSER::Object BSER::objectValue() { return m_ptr->objectValue(); }
std::string BSER::stringValue() { return m_ptr->stringValue(); }
int64_t BSER::intValue() { return m_ptr->intValue(); }
double BSER::doubleValue() { return m_ptr->doubleValue(); }
bool BSER::boolValue() { return m_ptr->boolValue(); }
void BSER::encode(std::ostream &oss) {
m_ptr->encode(oss);
}
int64_t BSER::decodeLength(std::istream &iss) {
char pdu[2];
if (!iss.read(pdu, 2) || pdu[0] != 0 || pdu[1] != 1) {
throw std::runtime_error("Invalid BSER");
}
return BSERInteger(iss).intValue();
}
std::string BSER::encode() {
std::ostringstream oss(std::ios_base::binary);
encode(oss);
std::ostringstream res(std::ios_base::binary);
res.write("\x00\x01", 2);
BSERInteger(oss.str().size()).encode(res);
res << oss.str();
return res.str();
}

View File

@ -1,69 +0,0 @@
#ifndef BSER_H
#define BSER_H
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <memory>
enum BSERType {
BSER_ARRAY = 0x00,
BSER_OBJECT = 0x01,
BSER_STRING = 0x02,
BSER_INT8 = 0x03,
BSER_INT16 = 0x04,
BSER_INT32 = 0x05,
BSER_INT64 = 0x06,
BSER_REAL = 0x07,
BSER_BOOL_TRUE = 0x08,
BSER_BOOL_FALSE = 0x09,
BSER_NULL = 0x0a,
BSER_TEMPLATE = 0x0b
};
class BSERValue;
class BSER {
public:
typedef std::vector<BSER> Array;
typedef std::unordered_map<std::string, BSER> Object;
BSER();
BSER(BSER::Array value);
BSER(BSER::Object value);
BSER(std::string value);
BSER(const char *value);
BSER(int64_t value);
BSER(double value);
BSER(bool value);
BSER(std::istream &iss);
BSER::Array arrayValue();
BSER::Object objectValue();
std::string stringValue();
int64_t intValue();
double doubleValue();
bool boolValue();
void encode(std::ostream &oss);
static int64_t decodeLength(std::istream &iss);
std::string encode();
private:
std::shared_ptr<BSERValue> m_ptr;
};
class BSERValue {
protected:
friend class BSER;
virtual BSER::Array arrayValue() { return BSER::Array(); }
virtual BSER::Object objectValue() { return BSER::Object(); }
virtual std::string stringValue() { return std::string(); }
virtual int64_t intValue() { return 0; }
virtual double doubleValue() { return 0; }
virtual bool boolValue() { return false; }
virtual void encode(std::ostream &oss) {}
virtual ~BSERValue() {}
};
#endif

View File

@ -1,175 +0,0 @@
#ifndef IPC_H
#define IPC_H
#include <string>
#include <stdlib.h>
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#endif
class IPC {
public:
IPC(std::string path) {
mStopped = false;
#ifdef _WIN32
while (true) {
mPipe = CreateFile(
path.data(), // pipe name
GENERIC_READ | GENERIC_WRITE, // read and write access
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
FILE_FLAG_OVERLAPPED, // attributes
NULL // no template file
);
if (mPipe != INVALID_HANDLE_VALUE) {
break;
}
if (GetLastError() != ERROR_PIPE_BUSY) {
throw std::runtime_error("Could not open pipe");
}
// Wait for pipe to become available if it is busy
if (!WaitNamedPipe(path.data(), 30000)) {
throw std::runtime_error("Error waiting for pipe");
}
}
mReader = CreateEvent(NULL, true, false, NULL);
mWriter = CreateEvent(NULL, true, false, NULL);
#else
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
mSock = socket(AF_UNIX, SOCK_STREAM, 0);
if (connect(mSock, (struct sockaddr *) &addr, sizeof(struct sockaddr_un))) {
throw std::runtime_error("Error connecting to socket");
}
#endif
}
~IPC() {
mStopped = true;
#ifdef _WIN32
CancelIo(mPipe);
CloseHandle(mPipe);
CloseHandle(mReader);
CloseHandle(mWriter);
#else
shutdown(mSock, SHUT_RDWR);
#endif
}
void write(std::string buf) {
#ifdef _WIN32
OVERLAPPED overlapped;
overlapped.hEvent = mWriter;
bool success = WriteFile(
mPipe, // pipe handle
buf.data(), // message
buf.size(), // message length
NULL, // bytes written
&overlapped // overlapped
);
if (mStopped) {
return;
}
if (!success) {
if (GetLastError() != ERROR_IO_PENDING) {
throw std::runtime_error("Write error");
}
}
DWORD written;
success = GetOverlappedResult(mPipe, &overlapped, &written, true);
if (!success) {
throw std::runtime_error("GetOverlappedResult failed");
}
if (written != buf.size()) {
throw std::runtime_error("Wrong number of bytes written");
}
#else
int r = 0;
for (unsigned int i = 0; i != buf.size(); i += r) {
r = ::write(mSock, &buf[i], buf.size() - i);
if (r == -1) {
if (errno == EAGAIN) {
r = 0;
} else if (mStopped) {
return;
} else {
throw std::runtime_error("Write error");
}
}
}
#endif
}
int read(char *buf, size_t len) {
#ifdef _WIN32
OVERLAPPED overlapped;
overlapped.hEvent = mReader;
bool success = ReadFile(
mPipe, // pipe handle
buf, // buffer to receive reply
len, // size of buffer
NULL, // number of bytes read
&overlapped // overlapped
);
if (!success && !mStopped) {
if (GetLastError() != ERROR_IO_PENDING) {
throw std::runtime_error("Read error");
}
}
DWORD read = 0;
success = GetOverlappedResult(mPipe, &overlapped, &read, true);
if (!success && !mStopped) {
throw std::runtime_error("GetOverlappedResult failed");
}
return read;
#else
int r = ::read(mSock, buf, len);
if (r == 0 && !mStopped) {
throw std::runtime_error("Socket ended unexpectedly");
}
if (r < 0) {
if (mStopped) {
return 0;
}
throw std::runtime_error(strerror(errno));
}
return r;
#endif
}
private:
bool mStopped;
#ifdef _WIN32
HANDLE mPipe;
HANDLE mReader;
HANDLE mWriter;
#else
int mSock;
#endif
};
#endif

View File

@ -1,338 +0,0 @@
#include <string>
#include <fstream>
#include <stdlib.h>
#include <algorithm>
#include "../DirTree.hh"
#include "../Event.hh"
#include "./BSER.hh"
#include "./WatchmanBackend.hh"
#ifdef _WIN32
#include "../windows/win_utils.hh"
#define S_ISDIR(mode) ((mode & _S_IFDIR) == _S_IFDIR)
#define popen _popen
#define pclose _pclose
#else
#include <sys/stat.h>
#define normalizePath(dir) dir
#endif
template<typename T>
BSER readBSER(T &&do_read) {
std::stringstream oss;
char buffer[256];
int r;
int64_t len = -1;
do {
// Start by reading a minimal amount of data in order to decode the length.
// After that, attempt to read the remaining length, up to the buffer size.
r = do_read(buffer, len == -1 ? 20 : (len < 256 ? len : 256));
oss << std::string(buffer, r);
if (len == -1) {
uint64_t l = BSER::decodeLength(oss);
len = l + oss.tellg();
}
len -= r;
} while (len > 0);
return BSER(oss);
}
std::string getSockPath() {
auto var = getenv("WATCHMAN_SOCK");
if (var && *var) {
return std::string(var);
}
FILE *fp = popen("watchman --output-encoding=bser get-sockname", "r");
if (fp == NULL || errno == ECHILD) {
throw std::runtime_error("Failed to execute watchman");
}
BSER b = readBSER([fp] (char *buf, size_t len) {
return fread(buf, sizeof(char), len, fp);
});
pclose(fp);
auto objValue = b.objectValue();
auto foundSockname = objValue.find("sockname");
if (foundSockname == objValue.end()) {
throw std::runtime_error("sockname not found");
}
return foundSockname->second.stringValue();
}
std::unique_ptr<IPC> watchmanConnect() {
std::string path = getSockPath();
return std::unique_ptr<IPC>(new IPC(path));
}
BSER watchmanRead(IPC *ipc) {
return readBSER([ipc] (char *buf, size_t len) {
return ipc->read(buf, len);
});
}
BSER::Object WatchmanBackend::watchmanRequest(BSER b) {
std::string cmd = b.encode();
mIPC->write(cmd);
mRequestSignal.notify();
mResponseSignal.wait();
mResponseSignal.reset();
if (!mError.empty()) {
std::runtime_error err = std::runtime_error(mError);
mError = std::string();
throw err;
}
return mResponse;
}
void WatchmanBackend::watchmanWatch(std::string dir) {
std::vector<BSER> cmd;
cmd.push_back("watch");
cmd.push_back(normalizePath(dir));
watchmanRequest(cmd);
}
bool WatchmanBackend::checkAvailable() {
try {
watchmanConnect();
return true;
} catch (std::exception &err) {
return false;
}
}
void handleFiles(WatcherRef watcher, BSER::Object obj) {
auto found = obj.find("files");
if (found == obj.end()) {
throw WatcherError("Error reading changes from watchman", watcher);
}
auto files = found->second.arrayValue();
for (auto it = files.begin(); it != files.end(); it++) {
auto file = it->objectValue();
auto name = file.find("name")->second.stringValue();
#ifdef _WIN32
std::replace(name.begin(), name.end(), '/', '\\');
#endif
auto mode = file.find("mode")->second.intValue();
auto isNew = file.find("new")->second.boolValue();
auto exists = file.find("exists")->second.boolValue();
auto path = watcher->mDir + DIR_SEP + name;
if (watcher->isIgnored(path)) {
continue;
}
if (isNew && exists) {
watcher->mEvents.create(path);
} else if (exists && !S_ISDIR(mode)) {
watcher->mEvents.update(path);
} else if (!isNew && !exists) {
watcher->mEvents.remove(path);
}
}
}
void WatchmanBackend::handleSubscription(BSER::Object obj) {
std::unique_lock<std::mutex> lock(mMutex);
auto subscription = obj.find("subscription")->second.stringValue();
auto it = mSubscriptions.find(subscription);
if (it == mSubscriptions.end()) {
return;
}
auto watcher = it->second;
try {
handleFiles(watcher, obj);
watcher->notify();
} catch (WatcherError &err) {
handleWatcherError(err);
}
}
void WatchmanBackend::start() {
mIPC = watchmanConnect();
notifyStarted();
while (true) {
// If there are no subscriptions we are reading, wait for a request.
if (mSubscriptions.size() == 0) {
mRequestSignal.wait();
mRequestSignal.reset();
}
// Break out of loop if we are stopped.
if (mStopped) {
break;
}
// Attempt to read from the socket.
// If there is an error and we are stopped, break.
BSER b;
try {
b = watchmanRead(&*mIPC);
} catch (std::exception &err) {
if (mStopped) {
break;
} else if (mResponseSignal.isWaiting()) {
mError = err.what();
mResponseSignal.notify();
} else {
// Throwing causes the backend to be destroyed, but we never reach the code below to notify the signal
mEndedSignal.notify();
throw;
}
}
auto obj = b.objectValue();
auto error = obj.find("error");
if (error != obj.end()) {
mError = error->second.stringValue();
mResponseSignal.notify();
continue;
}
// If this message is for a subscription, handle it, otherwise notify the request.
auto subscription = obj.find("subscription");
if (subscription != obj.end()) {
handleSubscription(obj);
} else {
mResponse = obj;
mResponseSignal.notify();
}
}
mEndedSignal.notify();
}
WatchmanBackend::~WatchmanBackend() {
// Mark the watcher as stopped, close the socket, and trigger the lock.
// This will cause the read loop to be broken and the thread to exit.
mStopped = true;
mIPC.reset();
mRequestSignal.notify();
// If not ended yet, wait.
mEndedSignal.wait();
}
std::string WatchmanBackend::clock(WatcherRef watcher) {
BSER::Array cmd;
cmd.push_back("clock");
cmd.push_back(normalizePath(watcher->mDir));
BSER::Object obj = watchmanRequest(cmd);
auto found = obj.find("clock");
if (found == obj.end()) {
throw WatcherError("Error reading clock from watchman", watcher);
}
return found->second.stringValue();
}
void WatchmanBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) {
std::unique_lock<std::mutex> lock(mMutex);
watchmanWatch(watcher->mDir);
std::ofstream ofs(*snapshotPath);
ofs << clock(watcher);
}
void WatchmanBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) {
std::unique_lock<std::mutex> lock(mMutex);
std::ifstream ifs(*snapshotPath);
if (ifs.fail()) {
return;
}
watchmanWatch(watcher->mDir);
std::string clock;
ifs >> clock;
BSER::Array cmd;
cmd.push_back("since");
cmd.push_back(normalizePath(watcher->mDir));
cmd.push_back(clock);
BSER::Object obj = watchmanRequest(cmd);
handleFiles(watcher, obj);
}
std::string getId(WatcherRef watcher) {
std::ostringstream id;
id << "parcel-";
id << static_cast<void*>(watcher.get());
return id.str();
}
// This function is called by Backend::watch which takes a lock on mMutex
void WatchmanBackend::subscribe(WatcherRef watcher) {
watchmanWatch(watcher->mDir);
std::string id = getId(watcher);
BSER::Array cmd;
cmd.push_back("subscribe");
cmd.push_back(normalizePath(watcher->mDir));
cmd.push_back(id);
BSER::Array fields;
fields.push_back("name");
fields.push_back("mode");
fields.push_back("exists");
fields.push_back("new");
BSER::Object opts;
opts.emplace("fields", fields);
opts.emplace("since", clock(watcher));
if (watcher->mIgnorePaths.size() > 0) {
BSER::Array ignore;
BSER::Array anyOf;
anyOf.push_back("anyof");
for (auto it = watcher->mIgnorePaths.begin(); it != watcher->mIgnorePaths.end(); it++) {
std::string pathStart = watcher->mDir + DIR_SEP;
if (it->rfind(pathStart, 0) == 0) {
auto relative = it->substr(pathStart.size());
BSER::Array dirname;
dirname.push_back("dirname");
dirname.push_back(relative);
anyOf.push_back(dirname);
}
}
ignore.push_back("not");
ignore.push_back(anyOf);
opts.emplace("expression", ignore);
}
cmd.push_back(opts);
watchmanRequest(cmd);
mSubscriptions.emplace(id, watcher);
mRequestSignal.notify();
}
// This function is called by Backend::unwatch which takes a lock on mMutex
void WatchmanBackend::unsubscribe(WatcherRef watcher) {
std::string id = getId(watcher);
auto erased = mSubscriptions.erase(id);
if (erased) {
BSER::Array cmd;
cmd.push_back("unsubscribe");
cmd.push_back(normalizePath(watcher->mDir));
cmd.push_back(id);
watchmanRequest(cmd);
}
}

View File

@ -1,35 +0,0 @@
#ifndef WATCHMAN_H
#define WATCHMAN_H
#include "../Backend.hh"
#include "./BSER.hh"
#include "../Signal.hh"
#include "./IPC.hh"
class WatchmanBackend : public Backend {
public:
static bool checkAvailable();
void start() override;
WatchmanBackend() : mStopped(false) {};
~WatchmanBackend();
void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override;
void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override;
void subscribe(WatcherRef watcher) override;
void unsubscribe(WatcherRef watcher) override;
private:
std::unique_ptr<IPC> mIPC;
Signal mRequestSignal;
Signal mResponseSignal;
BSER::Object mResponse;
std::string mError;
std::unordered_map<std::string, WatcherRef> mSubscriptions;
bool mStopped;
Signal mEndedSignal;
std::string clock(WatcherRef watcher);
void watchmanWatch(std::string dir);
BSER::Object watchmanRequest(BSER cmd);
void handleSubscription(BSER::Object obj);
};
#endif

View File

@ -1,282 +0,0 @@
#include <string>
#include <stack>
#include "../DirTree.hh"
#include "../shared/BruteForceBackend.hh"
#include "./WindowsBackend.hh"
#include "./win_utils.hh"
#define DEFAULT_BUF_SIZE 1024 * 1024
#define NETWORK_BUF_SIZE 64 * 1024
#define CONVERT_TIME(ft) ULARGE_INTEGER{ft.dwLowDateTime, ft.dwHighDateTime}.QuadPart
void BruteForceBackend::readTree(WatcherRef watcher, std::shared_ptr<DirTree> tree) {
std::stack<std::string> directories;
directories.push(watcher->mDir);
while (!directories.empty()) {
HANDLE hFind = INVALID_HANDLE_VALUE;
std::string path = directories.top();
std::string spec = path + "\\*";
directories.pop();
WIN32_FIND_DATA ffd;
hFind = FindFirstFile(spec.c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
if (path == watcher->mDir) {
FindClose(hFind);
throw WatcherError("Error opening directory", watcher);
}
tree->remove(path);
continue;
}
do {
if (strcmp(ffd.cFileName, ".") != 0 && strcmp(ffd.cFileName, "..") != 0) {
std::string fullPath = path + "\\" + ffd.cFileName;
if (watcher->isIgnored(fullPath)) {
continue;
}
tree->add(fullPath, CONVERT_TIME(ffd.ftLastWriteTime), ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
directories.push(fullPath);
}
}
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}
}
void WindowsBackend::start() {
mRunning = true;
notifyStarted();
while (mRunning) {
SleepEx(INFINITE, true);
}
}
WindowsBackend::~WindowsBackend() {
// Mark as stopped, and queue a noop function in the thread to break the loop
mRunning = false;
QueueUserAPC([](__in ULONG_PTR) {}, mThread.native_handle(), (ULONG_PTR)this);
}
class Subscription: public WatcherState {
public:
Subscription(WindowsBackend *backend, WatcherRef watcher, std::shared_ptr<DirTree> tree) {
mRunning = true;
mBackend = backend;
mWatcher = watcher;
mTree = tree;
ZeroMemory(&mOverlapped, sizeof(OVERLAPPED));
mOverlapped.hEvent = this;
mReadBuffer.resize(DEFAULT_BUF_SIZE);
mWriteBuffer.resize(DEFAULT_BUF_SIZE);
mDirectoryHandle = CreateFileW(
utf8ToUtf16(watcher->mDir).data(),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
NULL
);
if (mDirectoryHandle == INVALID_HANDLE_VALUE) {
throw WatcherError("Invalid handle", mWatcher);
}
// Ensure that the path is a directory
BY_HANDLE_FILE_INFORMATION info;
bool success = GetFileInformationByHandle(
mDirectoryHandle,
&info
);
if (!success) {
throw WatcherError("Could not get file information", mWatcher);
}
if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
throw WatcherError("Not a directory", mWatcher);
}
}
virtual ~Subscription() {
stop();
}
void run() {
try {
poll();
} catch (WatcherError &err) {
mBackend->handleWatcherError(err);
}
}
void stop() {
if (mRunning) {
mRunning = false;
CancelIo(mDirectoryHandle);
CloseHandle(mDirectoryHandle);
}
}
void poll() {
if (!mRunning) {
return;
}
// Asynchronously wait for changes.
int success = ReadDirectoryChangesW(
mDirectoryHandle,
mWriteBuffer.data(),
static_cast<DWORD>(mWriteBuffer.size()),
TRUE, // recursive
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES
| FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE,
NULL,
&mOverlapped,
[](DWORD errorCode, DWORD numBytes, LPOVERLAPPED overlapped) {
auto subscription = reinterpret_cast<Subscription *>(overlapped->hEvent);
try {
subscription->processEvents(errorCode);
} catch (WatcherError &err) {
subscription->mBackend->handleWatcherError(err);
}
}
);
if (!success) {
throw WatcherError("Failed to read changes", mWatcher);
}
}
void processEvents(DWORD errorCode) {
if (!mRunning) {
return;
}
switch (errorCode) {
case ERROR_OPERATION_ABORTED:
return;
case ERROR_INVALID_PARAMETER:
// resize buffers to network size (64kb), and try again
mReadBuffer.resize(NETWORK_BUF_SIZE);
mWriteBuffer.resize(NETWORK_BUF_SIZE);
poll();
return;
case ERROR_NOTIFY_ENUM_DIR:
throw WatcherError("Buffer overflow. Some events may have been lost.", mWatcher);
case ERROR_ACCESS_DENIED: {
// This can happen if the watched directory is deleted. Check if that is the case,
// and if so emit a delete event. Otherwise, fall through to default error case.
DWORD attrs = GetFileAttributesW(utf8ToUtf16(mWatcher->mDir).data());
bool isDir = attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY);
if (!isDir) {
mWatcher->mEvents.remove(mWatcher->mDir);
mTree->remove(mWatcher->mDir);
mWatcher->notify();
stop();
return;
}
}
default:
if (errorCode != ERROR_SUCCESS) {
throw WatcherError("Unknown error", mWatcher);
}
}
// Swap read and write buffers, and poll again
std::swap(mWriteBuffer, mReadBuffer);
poll();
// Read change events
BYTE *base = mReadBuffer.data();
while (true) {
PFILE_NOTIFY_INFORMATION info = (PFILE_NOTIFY_INFORMATION)base;
processEvent(info);
if (info->NextEntryOffset == 0) {
break;
}
base += info->NextEntryOffset;
}
mWatcher->notify();
}
void processEvent(PFILE_NOTIFY_INFORMATION info) {
std::string path = mWatcher->mDir + "\\" + utf16ToUtf8(info->FileName, info->FileNameLength / sizeof(WCHAR));
if (mWatcher->isIgnored(path)) {
return;
}
switch (info->Action) {
case FILE_ACTION_ADDED:
case FILE_ACTION_RENAMED_NEW_NAME: {
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesExW(utf8ToUtf16(path).data(), GetFileExInfoStandard, &data)) {
mWatcher->mEvents.create(path);
mTree->add(path, CONVERT_TIME(data.ftLastWriteTime), data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
}
break;
}
case FILE_ACTION_MODIFIED: {
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesExW(utf8ToUtf16(path).data(), GetFileExInfoStandard, &data)) {
mTree->update(path, CONVERT_TIME(data.ftLastWriteTime));
if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
mWatcher->mEvents.update(path);
}
}
break;
}
case FILE_ACTION_REMOVED:
case FILE_ACTION_RENAMED_OLD_NAME:
mWatcher->mEvents.remove(path);
mTree->remove(path);
break;
}
}
private:
WindowsBackend *mBackend;
std::shared_ptr<Watcher> mWatcher;
std::shared_ptr<DirTree> mTree;
bool mRunning;
HANDLE mDirectoryHandle;
std::vector<BYTE> mReadBuffer;
std::vector<BYTE> mWriteBuffer;
OVERLAPPED mOverlapped;
};
// This function is called by Backend::watch which takes a lock on mMutex
void WindowsBackend::subscribe(WatcherRef watcher) {
// Create a subscription for this watcher
auto sub = std::make_shared<Subscription>(this, watcher, getTree(watcher, false));
watcher->state = sub;
// Queue polling for this subscription in the correct thread.
bool success = QueueUserAPC([](__in ULONG_PTR ptr) {
Subscription *sub = (Subscription *)ptr;
sub->run();
}, mThread.native_handle(), (ULONG_PTR)sub.get());
if (!success) {
throw std::runtime_error("Unable to queue APC");
}
}
// This function is called by Backend::unwatch which takes a lock on mMutex
void WindowsBackend::unsubscribe(WatcherRef watcher) {
watcher->state = nullptr;
}

View File

@ -1,18 +0,0 @@
#ifndef WINDOWS_H
#define WINDOWS_H
#include <winsock2.h>
#include <windows.h>
#include "../shared/BruteForceBackend.hh"
class WindowsBackend : public BruteForceBackend {
public:
void start() override;
~WindowsBackend();
void subscribe(WatcherRef watcher) override;
void unsubscribe(WatcherRef watcher) override;
private:
bool mRunning;
};
#endif

View File

@ -1,44 +0,0 @@
#include "./win_utils.hh"
std::wstring utf8ToUtf16(std::string input) {
unsigned int len = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, NULL, 0);
WCHAR *output = new WCHAR[len];
MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, output, len);
std::wstring res(output);
delete output;
return res;
}
std::string utf16ToUtf8(const WCHAR *input, size_t length) {
unsigned int len = WideCharToMultiByte(CP_UTF8, 0, input, length, NULL, 0, NULL, NULL);
char *output = new char[len + 1];
WideCharToMultiByte(CP_UTF8, 0, input, length, output, len, NULL, NULL);
output[len] = '\0';
std::string res(output);
delete output;
return res;
}
std::string normalizePath(std::string path) {
// Prevent truncation to MAX_PATH characters by adding the \\?\ prefix
std::wstring p = utf8ToUtf16("\\\\?\\" + path);
// Get the required length for the output
unsigned int len = GetLongPathNameW(p.data(), NULL, 0);
if (!len) {
return path;
}
// Allocate output array and get long path
WCHAR *output = new WCHAR[len];
len = GetLongPathNameW(p.data(), output, len);
if (!len) {
delete output;
return path;
}
// Convert back to utf8
std::string res = utf16ToUtf8(output + 4, len - 4);
delete output;
return res;
}

View File

@ -1,11 +0,0 @@
#ifndef WIN_UTILS_H
#define WIN_UTILS_H
#include <string>
#include <windows.h>
std::wstring utf8ToUtf16(std::string input);
std::string utf16ToUtf8(const WCHAR *input, size_t length);
std::string normalizePath(std::string path);
#endif

View File

@ -1,77 +0,0 @@
const path = require('path');
const micromatch = require('micromatch');
const isGlob = require('is-glob');
function normalizeOptions(dir, opts = {}) {
const { ignore, ...rest } = opts;
if (Array.isArray(ignore)) {
opts = { ...rest };
for (const value of ignore) {
if (isGlob(value)) {
if (!opts.ignoreGlobs) {
opts.ignoreGlobs = [];
}
const regex = micromatch.makeRe(value, {
// We set `dot: true` to workaround an issue with the
// regular expression on Linux where the resulting
// negative lookahead `(?!(\\/|^)` was never matching
// in some cases. See also https://bit.ly/3UZlQDm
dot: true,
// C++ does not support lookbehind regex patterns, they
// were only added later to JavaScript engines
// (https://bit.ly/3V7S6UL)
lookbehinds: false
});
opts.ignoreGlobs.push(regex.source);
} else {
if (!opts.ignorePaths) {
opts.ignorePaths = [];
}
opts.ignorePaths.push(path.resolve(dir, value));
}
}
}
return opts;
}
exports.createWrapper = (binding) => {
return {
writeSnapshot(dir, snapshot, opts) {
return binding.writeSnapshot(
path.resolve(dir),
path.resolve(snapshot),
normalizeOptions(dir, opts),
);
},
getEventsSince(dir, snapshot, opts) {
return binding.getEventsSince(
path.resolve(dir),
path.resolve(snapshot),
normalizeOptions(dir, opts),
);
},
async subscribe(dir, fn, opts) {
dir = path.resolve(dir);
opts = normalizeOptions(dir, opts);
await binding.subscribe(dir, fn, opts);
return {
unsubscribe() {
return binding.unsubscribe(dir, fn, opts);
},
};
},
unsubscribe(dir, fn, opts) {
return binding.unsubscribe(
path.resolve(dir),
fn,
normalizeOptions(dir, opts),
);
}
};
};

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2016 Alex Indigo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,233 +0,0 @@
# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit)
Minimal async jobs utility library, with streams support.
[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit)
[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit)
[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit)
[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master)
[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit)
[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit)
<!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) -->
AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects.
Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method.
It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators.
| compression | size |
| :----------------- | -------: |
| asynckit.js | 12.34 kB |
| asynckit.min.js | 4.11 kB |
| asynckit.min.js.gz | 1.47 kB |
## Install
```sh
$ npm install --save asynckit
```
## Examples
### Parallel Jobs
Runs iterator over provided array in parallel. Stores output in the `result` array,
on the matching positions. In unlikely event of an error from one of the jobs,
will terminate rest of the active jobs (if abort function is provided)
and return error along with salvaged data to the main callback function.
#### Input Array
```javascript
var parallel = require('asynckit').parallel
, assert = require('assert')
;
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
, target = []
;
parallel(source, asyncJob, function(err, result)
{
assert.deepEqual(result, expectedResult);
assert.deepEqual(target, expectedTarget);
});
// async job accepts one element from the array
// and a callback function
function asyncJob(item, cb)
{
// different delays (in ms) per item
var delay = item * 25;
// pretend different jobs take different time to finish
// and not in consequential order
var timeoutId = setTimeout(function() {
target.push(item);
cb(null, item * 2);
}, delay);
// allow to cancel "leftover" jobs upon error
// return function, invoking of which will abort this job
return clearTimeout.bind(null, timeoutId);
}
```
More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js).
#### Input Object
Also it supports named jobs, listed via object.
```javascript
var parallel = require('asynckit/parallel')
, assert = require('assert')
;
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
, expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ]
, target = []
, keys = []
;
parallel(source, asyncJob, function(err, result)
{
assert.deepEqual(result, expectedResult);
assert.deepEqual(target, expectedTarget);
assert.deepEqual(keys, expectedKeys);
});
// supports full value, key, callback (shortcut) interface
function asyncJob(item, key, cb)
{
// different delays (in ms) per item
var delay = item * 25;
// pretend different jobs take different time to finish
// and not in consequential order
var timeoutId = setTimeout(function() {
keys.push(key);
target.push(item);
cb(null, item * 2);
}, delay);
// allow to cancel "leftover" jobs upon error
// return function, invoking of which will abort this job
return clearTimeout.bind(null, timeoutId);
}
```
More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js).
### Serial Jobs
Runs iterator over provided array sequentially. Stores output in the `result` array,
on the matching positions. In unlikely event of an error from one of the jobs,
will not proceed to the rest of the items in the list
and return error along with salvaged data to the main callback function.
#### Input Array
```javascript
var serial = require('asynckit/serial')
, assert = require('assert')
;
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
, target = []
;
serial(source, asyncJob, function(err, result)
{
assert.deepEqual(result, expectedResult);
assert.deepEqual(target, expectedTarget);
});
// extended interface (item, key, callback)
// also supported for arrays
function asyncJob(item, key, cb)
{
target.push(key);
// it will be automatically made async
// even it iterator "returns" in the same event loop
cb(null, item * 2);
}
```
More examples could be found in [test/test-serial-array.js](test/test-serial-array.js).
#### Input Object
Also it supports named jobs, listed via object.
```javascript
var serial = require('asynckit').serial
, assert = require('assert')
;
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
, target = []
;
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
, expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
, target = []
;
serial(source, asyncJob, function(err, result)
{
assert.deepEqual(result, expectedResult);
assert.deepEqual(target, expectedTarget);
});
// shortcut interface (item, callback)
// works for object as well as for the arrays
function asyncJob(item, cb)
{
target.push(item);
// it will be automatically made async
// even it iterator "returns" in the same event loop
cb(null, item * 2);
}
```
More examples could be found in [test/test-serial-object.js](test/test-serial-object.js).
_Note: Since _object_ is an _unordered_ collection of properties,
it may produce unexpected results with sequential iterations.
Whenever order of the jobs' execution is important please use `serialOrdered` method._
### Ordered Serial Iterations
TBD
For example [compare-property](compare-property) package.
### Streaming interface
TBD
## Want to Know More?
More examples can be found in [test folder](test/).
Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions.
## License
AsyncKit is licensed under the MIT license.

View File

@ -1,76 +0,0 @@
/* eslint no-console: "off" */
var asynckit = require('./')
, async = require('async')
, assert = require('assert')
, expected = 0
;
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var source = [];
for (var z = 1; z < 100; z++)
{
source.push(z);
expected += z;
}
suite
// add tests
.add('async.map', function(deferred)
{
var total = 0;
async.map(source,
function(i, cb)
{
setImmediate(function()
{
total += i;
cb(null, total);
});
},
function(err, result)
{
assert.ifError(err);
assert.equal(result[result.length - 1], expected);
deferred.resolve();
});
}, {'defer': true})
.add('asynckit.parallel', function(deferred)
{
var total = 0;
asynckit.parallel(source,
function(i, cb)
{
setImmediate(function()
{
total += i;
cb(null, total);
});
},
function(err, result)
{
assert.ifError(err);
assert.equal(result[result.length - 1], expected);
deferred.resolve();
});
}, {'defer': true})
// add listeners
.on('cycle', function(ev)
{
console.log(String(ev.target));
})
.on('complete', function()
{
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });

View File

@ -1,6 +0,0 @@
module.exports =
{
parallel : require('./parallel.js'),
serial : require('./serial.js'),
serialOrdered : require('./serialOrdered.js')
};

View File

@ -1,29 +0,0 @@
// API
module.exports = abort;
/**
* Aborts leftover active jobs
*
* @param {object} state - current state object
*/
function abort(state)
{
Object.keys(state.jobs).forEach(clean.bind(state));
// reset leftover jobs
state.jobs = {};
}
/**
* Cleans up leftover job by invoking abort function for the provided job id
*
* @this state
* @param {string|number} key - job id to abort
*/
function clean(key)
{
if (typeof this.jobs[key] == 'function')
{
this.jobs[key]();
}
}

View File

@ -1,34 +0,0 @@
var defer = require('./defer.js');
// API
module.exports = async;
/**
* Runs provided callback asynchronously
* even if callback itself is not
*
* @param {function} callback - callback to invoke
* @returns {function} - augmented callback
*/
function async(callback)
{
var isAsync = false;
// check if async happened
defer(function() { isAsync = true; });
return function async_callback(err, result)
{
if (isAsync)
{
callback(err, result);
}
else
{
defer(function nextTick_callback()
{
callback(err, result);
});
}
};
}

View File

@ -1,26 +0,0 @@
module.exports = defer;
/**
* Runs provided function on next iteration of the event loop
*
* @param {function} fn - function to run
*/
function defer(fn)
{
var nextTick = typeof setImmediate == 'function'
? setImmediate
: (
typeof process == 'object' && typeof process.nextTick == 'function'
? process.nextTick
: null
);
if (nextTick)
{
nextTick(fn);
}
else
{
setTimeout(fn, 0);
}
}

View File

@ -1,75 +0,0 @@
var async = require('./async.js')
, abort = require('./abort.js')
;
// API
module.exports = iterate;
/**
* Iterates over each job object
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {object} state - current job status
* @param {function} callback - invoked when all elements processed
*/
function iterate(list, iterator, state, callback)
{
// store current index
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
{
// don't repeat yourself
// skip secondary callbacks
if (!(key in state.jobs))
{
return;
}
// clean up jobs
delete state.jobs[key];
if (error)
{
// don't process rest of the results
// stop still active jobs
// and reset the list
abort(state);
}
else
{
state.results[key] = output;
}
// return salvaged results
callback(error, state.results);
});
}
/**
* Runs iterator over provided job element
*
* @param {function} iterator - iterator to invoke
* @param {string|number} key - key/index of the element in the list of jobs
* @param {mixed} item - job description
* @param {function} callback - invoked after iterator is done with the job
* @returns {function|mixed} - job abort function or something else
*/
function runJob(iterator, key, item, callback)
{
var aborter;
// allow shortcut if iterator expects only two arguments
if (iterator.length == 2)
{
aborter = iterator(item, async(callback));
}
// otherwise go with full three arguments
else
{
aborter = iterator(item, key, async(callback));
}
return aborter;
}

View File

@ -1,91 +0,0 @@
var streamify = require('./streamify.js')
, defer = require('./defer.js')
;
// API
module.exports = ReadableAsyncKit;
/**
* Base constructor for all streams
* used to hold properties/methods
*/
function ReadableAsyncKit()
{
ReadableAsyncKit.super_.apply(this, arguments);
// list of active jobs
this.jobs = {};
// add stream methods
this.destroy = destroy;
this._start = _start;
this._read = _read;
}
/**
* Destroys readable stream,
* by aborting outstanding jobs
*
* @returns {void}
*/
function destroy()
{
if (this.destroyed)
{
return;
}
this.destroyed = true;
if (typeof this.terminator == 'function')
{
this.terminator();
}
}
/**
* Starts provided jobs in async manner
*
* @private
*/
function _start()
{
// first argument runner function
var runner = arguments[0]
// take away first argument
, args = Array.prototype.slice.call(arguments, 1)
// second argument - input data
, input = args[0]
// last argument - result callback
, endCb = streamify.callback.call(this, args[args.length - 1])
;
args[args.length - 1] = endCb;
// third argument - iterator
args[1] = streamify.iterator.call(this, args[1]);
// allow time for proper setup
defer(function()
{
if (!this.destroyed)
{
this.terminator = runner.apply(null, args);
}
else
{
endCb(null, Array.isArray(input) ? [] : {});
}
}.bind(this));
}
/**
* Implement _read to comply with Readable streams
* Doesn't really make sense for flowing object mode
*
* @private
*/
function _read()
{
}

View File

@ -1,25 +0,0 @@
var parallel = require('../parallel.js');
// API
module.exports = ReadableParallel;
/**
* Streaming wrapper to `asynckit.parallel`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableParallel(list, iterator, callback)
{
if (!(this instanceof ReadableParallel))
{
return new ReadableParallel(list, iterator, callback);
}
// turn on object mode
ReadableParallel.super_.call(this, {objectMode: true});
this._start(parallel, list, iterator, callback);
}

View File

@ -1,25 +0,0 @@
var serial = require('../serial.js');
// API
module.exports = ReadableSerial;
/**
* Streaming wrapper to `asynckit.serial`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableSerial(list, iterator, callback)
{
if (!(this instanceof ReadableSerial))
{
return new ReadableSerial(list, iterator, callback);
}
// turn on object mode
ReadableSerial.super_.call(this, {objectMode: true});
this._start(serial, list, iterator, callback);
}

View File

@ -1,29 +0,0 @@
var serialOrdered = require('../serialOrdered.js');
// API
module.exports = ReadableSerialOrdered;
// expose sort helpers
module.exports.ascending = serialOrdered.ascending;
module.exports.descending = serialOrdered.descending;
/**
* Streaming wrapper to `asynckit.serialOrdered`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} sortMethod - custom sort function
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableSerialOrdered(list, iterator, sortMethod, callback)
{
if (!(this instanceof ReadableSerialOrdered))
{
return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
}
// turn on object mode
ReadableSerialOrdered.super_.call(this, {objectMode: true});
this._start(serialOrdered, list, iterator, sortMethod, callback);
}

View File

@ -1,37 +0,0 @@
// API
module.exports = state;
/**
* Creates initial state object
* for iteration over list
*
* @param {array|object} list - list to iterate over
* @param {function|null} sortMethod - function to use for keys sort,
* or `null` to keep them as is
* @returns {object} - initial state object
*/
function state(list, sortMethod)
{
var isNamedList = !Array.isArray(list)
, initState =
{
index : 0,
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
jobs : {},
results : isNamedList ? {} : [],
size : isNamedList ? Object.keys(list).length : list.length
}
;
if (sortMethod)
{
// sort array keys based on it's values
// sort object's keys just on own merit
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
{
return sortMethod(list[a], list[b]);
});
}
return initState;
}

View File

@ -1,141 +0,0 @@
var async = require('./async.js');
// API
module.exports = {
iterator: wrapIterator,
callback: wrapCallback
};
/**
* Wraps iterators with long signature
*
* @this ReadableAsyncKit#
* @param {function} iterator - function to wrap
* @returns {function} - wrapped function
*/
function wrapIterator(iterator)
{
var stream = this;
return function(item, key, cb)
{
var aborter
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
;
stream.jobs[key] = wrappedCb;
// it's either shortcut (item, cb)
if (iterator.length == 2)
{
aborter = iterator(item, wrappedCb);
}
// or long format (item, key, cb)
else
{
aborter = iterator(item, key, wrappedCb);
}
return aborter;
};
}
/**
* Wraps provided callback function
* allowing to execute snitch function before
* real callback
*
* @this ReadableAsyncKit#
* @param {function} callback - function to wrap
* @returns {function} - wrapped function
*/
function wrapCallback(callback)
{
var stream = this;
var wrapped = function(error, result)
{
return finisher.call(stream, error, result, callback);
};
return wrapped;
}
/**
* Wraps provided iterator callback function
* makes sure snitch only called once,
* but passes secondary calls to the original callback
*
* @this ReadableAsyncKit#
* @param {function} callback - callback to wrap
* @param {number|string} key - iteration key
* @returns {function} wrapped callback
*/
function wrapIteratorCallback(callback, key)
{
var stream = this;
return function(error, output)
{
// don't repeat yourself
if (!(key in stream.jobs))
{
callback(error, output);
return;
}
// clean up jobs
delete stream.jobs[key];
return streamer.call(stream, error, {key: key, value: output}, callback);
};
}
/**
* Stream wrapper for iterator callback
*
* @this ReadableAsyncKit#
* @param {mixed} error - error response
* @param {mixed} output - iterator output
* @param {function} callback - callback that expects iterator results
*/
function streamer(error, output, callback)
{
if (error && !this.error)
{
this.error = error;
this.pause();
this.emit('error', error);
// send back value only, as expected
callback(error, output && output.value);
return;
}
// stream stuff
this.push(output);
// back to original track
// send back value only, as expected
callback(error, output && output.value);
}
/**
* Stream wrapper for finishing callback
*
* @this ReadableAsyncKit#
* @param {mixed} error - error response
* @param {mixed} output - iterator output
* @param {function} callback - callback that expects final results
*/
function finisher(error, output, callback)
{
// signal end of the stream
// only for successfully finished streams
if (!error)
{
this.push(null);
}
// back to original track
callback(error, output);
}

View File

@ -1,29 +0,0 @@
var abort = require('./abort.js')
, async = require('./async.js')
;
// API
module.exports = terminator;
/**
* Terminates jobs in the attached state context
*
* @this AsyncKitState#
* @param {function} callback - final callback to invoke after termination
*/
function terminator(callback)
{
if (!Object.keys(this.jobs).length)
{
return;
}
// fast forward iteration index
this.index = this.size;
// abort jobs
abort(this);
// send back results we have so far
async(callback)(null, this.results);
}

View File

@ -1,63 +0,0 @@
{
"name": "asynckit",
"version": "0.4.0",
"description": "Minimal async jobs utility library, with streams support",
"main": "index.js",
"scripts": {
"clean": "rimraf coverage",
"lint": "eslint *.js lib/*.js test/*.js",
"test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec",
"win-test": "tape test/test-*.js",
"browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec",
"report": "istanbul report",
"size": "browserify index.js | size-table asynckit",
"debug": "tape test/test-*.js"
},
"pre-commit": [
"clean",
"lint",
"test",
"browser",
"report",
"size"
],
"repository": {
"type": "git",
"url": "git+https://github.com/alexindigo/asynckit.git"
},
"keywords": [
"async",
"jobs",
"parallel",
"serial",
"iterator",
"array",
"object",
"stream",
"destroy",
"terminate",
"abort"
],
"author": "Alex Indigo <iam@alexindigo.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/alexindigo/asynckit/issues"
},
"homepage": "https://github.com/alexindigo/asynckit#readme",
"devDependencies": {
"browserify": "^13.0.0",
"browserify-istanbul": "^2.0.0",
"coveralls": "^2.11.9",
"eslint": "^2.9.0",
"istanbul": "^0.4.3",
"obake": "^0.1.2",
"phantomjs-prebuilt": "^2.1.7",
"pre-commit": "^1.1.3",
"reamde": "^1.1.0",
"rimraf": "^2.5.2",
"size-table": "^0.2.0",
"tap-spec": "^4.1.1",
"tape": "^4.5.1"
},
"dependencies": {}
}

View File

@ -1,43 +0,0 @@
var iterate = require('./lib/iterate.js')
, initState = require('./lib/state.js')
, terminator = require('./lib/terminator.js')
;
// Public API
module.exports = parallel;
/**
* Runs iterator over provided array elements in parallel
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function parallel(list, iterator, callback)
{
var state = initState(list);
while (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, function(error, result)
{
if (error)
{
callback(error, result);
return;
}
// looks like it's the last one
if (Object.keys(state.jobs).length === 0)
{
callback(null, state.results);
return;
}
});
state.index++;
}
return terminator.bind(state, callback);
}

View File

@ -1,17 +0,0 @@
var serialOrdered = require('./serialOrdered.js');
// Public API
module.exports = serial;
/**
* Runs iterator over provided array elements in series
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function serial(list, iterator, callback)
{
return serialOrdered(list, iterator, null, callback);
}

View File

@ -1,75 +0,0 @@
var iterate = require('./lib/iterate.js')
, initState = require('./lib/state.js')
, terminator = require('./lib/terminator.js')
;
// Public API
module.exports = serialOrdered;
// sorting helpers
module.exports.ascending = ascending;
module.exports.descending = descending;
/**
* Runs iterator over provided sorted array elements in series
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} sortMethod - custom sort function
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function serialOrdered(list, iterator, sortMethod, callback)
{
var state = initState(list, sortMethod);
iterate(list, iterator, state, function iteratorHandler(error, result)
{
if (error)
{
callback(error, result);
return;
}
state.index++;
// are we there yet?
if (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, iteratorHandler);
return;
}
// done here
callback(null, state.results);
});
return terminator.bind(state, callback);
}
/*
* -- Sort methods
*/
/**
* sort helper to sort array elements in ascending order
*
* @param {mixed} a - an item to compare
* @param {mixed} b - an item to compare
* @returns {number} - comparison result
*/
function ascending(a, b)
{
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* sort helper to sort array elements in descending order
*
* @param {mixed} a - an item to compare
* @param {mixed} b - an item to compare
* @returns {number} - comparison result
*/
function descending(a, b)
{
return -1 * ascending(a, b);
}

View File

@ -1,21 +0,0 @@
var inherits = require('util').inherits
, Readable = require('stream').Readable
, ReadableAsyncKit = require('./lib/readable_asynckit.js')
, ReadableParallel = require('./lib/readable_parallel.js')
, ReadableSerial = require('./lib/readable_serial.js')
, ReadableSerialOrdered = require('./lib/readable_serial_ordered.js')
;
// API
module.exports =
{
parallel : ReadableParallel,
serial : ReadableSerial,
serialOrdered : ReadableSerialOrdered,
};
inherits(ReadableAsyncKit, Readable);
inherits(ReadableParallel, ReadableAsyncKit);
inherits(ReadableSerial, ReadableAsyncKit);
inherits(ReadableSerialOrdered, ReadableAsyncKit);

View File

@ -1,943 +0,0 @@
# Changelog
### 0.27.2 (April 27, 2022)
Fixes and Functionality:
- Fixed FormData posting in browser environment by reverting #3785 ([#4640](https://github.com/axios/axios/pull/4640))
- Enhanced protocol parsing implementation ([#4639](https://github.com/axios/axios/pull/4639))
- Fixed bundle size
### 0.27.1 (April 26, 2022)
Fixes and Functionality:
- Removed import of url module in browser build due to huge size overhead and builds being broken ([#4594](https://github.com/axios/axios/pull/4594))
- Bumped follow-redirects to ^1.14.9 ([#4615](https://github.com/axios/axios/pull/4615))
### 0.27.0 (April 25, 2022)
Breaking changes:
- New toFormData helper function that allows the implementor to pass an object and allow axios to convert it to FormData ([#3757](https://github.com/axios/axios/pull/3757))
- Removed functionality that removed the the `Content-Type` request header when passing FormData ([#3785](https://github.com/axios/axios/pull/3785))
- **(*)** Refactored error handling implementing AxiosError as a constructor, this is a large change to error handling on the whole ([#3645](https://github.com/axios/axios/pull/3645))
- Separated responsibility for FormData instantiation between `transformRequest` and `toFormData` ([#4470](https://github.com/axios/axios/pull/4470))
- **(*)** Improved and fixed multiple issues with FormData support ([#4448](https://github.com/axios/axios/pull/4448))
QOL and DevX improvements:
- Added a multipart/form-data testing playground allowing contributors to debug changes easily ([#4465](https://github.com/axios/axios/pull/4465))
Fixes and Functionality:
- Refactored project file structure to avoid circular imports ([#4515](https://github.com/axios/axios/pull/4516)) & ([#4516](https://github.com/axios/axios/pull/4516))
- Bumped follow-redirects to ^1.14.9 ([#4562](https://github.com/axios/axios/pull/4562))
Internal and Tests:
- Updated dev dependencies to latest version
Documentation:
- Fixing incorrect link in changelog ([#4551](https://github.com/axios/axios/pull/4551))
Notes:
- **(*)** Please read these pull requests before updating, these changes are very impactful and far reaching.
### 0.26.1 (March 9, 2022)
Fixes and Functionality:
- Refactored project file structure to avoid circular imports ([#4220](https://github.com/axios/axios/pull/4220))
### 0.26.0 (February 13, 2022)
Fixes and Functionality:
- Fixed The timeoutErrorMessage property in config not work with Node.js ([#3581](https://github.com/axios/axios/pull/3581))
- Added errors to be displayed when the query parsing process itself fails ([#3961](https://github.com/axios/axios/pull/3961))
- Fix/remove url required ([#4426](https://github.com/axios/axios/pull/4426))
- Update follow-redirects dependency due to Vulnerability ([#4462](https://github.com/axios/axios/pull/4462))
- Bump karma from 6.3.11 to 6.3.14 ([#4461](https://github.com/axios/axios/pull/4461))
- Bump follow-redirects from 1.14.7 to 1.14.8 ([#4473](https://github.com/axios/axios/pull/4473))
### 0.25.0 (January 18, 2022)
Breaking changes:
- Fixing maxBodyLength enforcement ([#3786](https://github.com/axios/axios/pull/3786))
- Don't rely on strict mode behavior for arguments ([#3470](https://github.com/axios/axios/pull/3470))
- Adding error handling when missing url ([#3791](https://github.com/axios/axios/pull/3791))
- Update isAbsoluteURL.js removing escaping of non-special characters ([#3809](https://github.com/axios/axios/pull/3809))
- Use native Array.isArray() in utils.js ([#3836](https://github.com/axios/axios/pull/3836))
- Adding error handling inside stream end callback ([#3967](https://github.com/axios/axios/pull/3967))
Fixes and Functionality:
- Added aborted even handler ([#3916](https://github.com/axios/axios/pull/3916))
- Header types expanded allowing `boolean` and `number` types ([#4144](https://github.com/axios/axios/pull/4144))
- Fix cancel signature allowing cancel message to be `undefined` ([#3153](https://github.com/axios/axios/pull/3153))
- Updated type checks to be formulated better ([#3342](https://github.com/axios/axios/pull/3342))
- Avoid unnecessary buffer allocations ([#3321](https://github.com/axios/axios/pull/3321))
- Adding a socket handler to keep TCP connection live when processing long living requests ([#3422](https://github.com/axios/axios/pull/3422))
- Added toFormData helper function ([#3757](https://github.com/axios/axios/pull/3757))
- Adding responseEncoding prop type in AxiosRequestConfig ([#3918](https://github.com/axios/axios/pull/3918))
Internal and Tests:
- Adding axios-test-instance to ecosystem ([#3496](https://github.com/axios/axios/pull/3496))
- Optimize the logic of isAxiosError ([#3546](https://github.com/axios/axios/pull/3546))
- Add tests and documentation to display how multiple inceptors work ([#3564](https://github.com/axios/axios/pull/3564))
- Updating follow-redirects to version 1.14.7 ([#4379](https://github.com/axios/axios/pull/4379))
Documentation:
- Fixing changelog to show correct pull request ([#4219](https://github.com/axios/axios/pull/4219))
- Update upgrade guide for https proxy setting ([#3604](https://github.com/axios/axios/pull/3604))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- [Jay](mailto:jasonsaayman@gmail.com)
- [Rijk van Zanten](https://github.com/rijkvanzanten)
- [Kohta Ito](https://github.com/koh110)
- [Brandon Faulkner](https://github.com/bfaulk96)
- [Stefano Magni](https://github.com/NoriSte)
- [enofan](https://github.com/fanguangyi)
- [Andrey Pechkurov](https://github.com/puzpuzpuz)
- [Doowonee](https://github.com/doowonee)
- [Emil Broman](https://github.com/emilbroman-eqt)
- [Remco Haszing](https://github.com/remcohaszing)
- [Black-Hole](https://github.com/BlackHole1)
- [Wolfram Kriesing](https://github.com/wolframkriesing)
- [Andrew Ovens](https://github.com/repl-andrew-ovens)
- [Paulo Renato](https://github.com/PauloRSF)
- [Ben Carp](https://github.com/carpben)
- [Hirotaka Tagawa](https://github.com/wafuwafu13)
- [狼族小狈](https://github.com/lzxb)
- [C. Lewis](https://github.com/ctjlewis)
- [Felipe Carvalho](https://github.com/FCarvalhoVII)
- [Daniel](https://github.com/djs113)
- [Gustavo Sales](https://github.com/gussalesdev)
### 0.24.0 (October 25, 2021)
Breaking changes:
- Revert: change type of AxiosResponse to any, please read lengthy discussion here: ([#4141](https://github.com/axios/axios/issues/4141)) pull request: ([#4186](https://github.com/axios/axios/pull/4186))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- [Jay](mailto:jasonsaayman@gmail.com)
- [Rodry](https://github.com/ImRodry)
- [Remco Haszing](https://github.com/remcohaszing)
- [Isaiah Thomason](https://github.com/ITenthusiasm)
### 0.23.0 (October 12, 2021)
Breaking changes:
- Distinguish request and response data types ([#4116](https://github.com/axios/axios/pull/4116))
- Change never type to unknown ([#4142](https://github.com/axios/axios/pull/4142))
- Fixed TransitionalOptions typings ([#4147](https://github.com/axios/axios/pull/4147))
Fixes and Functionality:
- Adding globalObject: 'this' to webpack config ([#3176](https://github.com/axios/axios/pull/3176))
- Adding insecureHTTPParser type to AxiosRequestConfig ([#4066](https://github.com/axios/axios/pull/4066))
- Fix missing semicolon in typings ([#4115](https://github.com/axios/axios/pull/4115))
- Fix response headers types ([#4136](https://github.com/axios/axios/pull/4136))
Internal and Tests:
- Improve timeout error when timeout is browser default ([#3209](https://github.com/axios/axios/pull/3209))
- Fix node version on CI ([#4069](https://github.com/axios/axios/pull/4069))
- Added testing to TypeScript portion of project ([#4140](https://github.com/axios/axios/pull/4140))
Documentation:
- Rename Angular to AngularJS ([#4114](https://github.com/axios/axios/pull/4114))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- [Jay](mailto:jasonsaayman@gmail.com)
- [Evan-Finkelstein](https://github.com/Evan-Finkelstein)
- [Paweł Szymański](https://github.com/Jezorko)
- [Dobes Vandermeer](https://github.com/dobesv)
- [Claas Augner](https://github.com/caugner)
- [Remco Haszing](https://github.com/remcohaszing)
- [Evgeniy](https://github.com/egmen)
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
### 0.22.0 (October 01, 2021)
Fixes and Functionality:
- Caseless header comparing in HTTP adapter ([#2880](https://github.com/axios/axios/pull/2880))
- Avoid package.json import fixing issues and warnings related to this ([#4041](https://github.com/axios/axios/pull/4041)), ([#4065](https://github.com/axios/axios/pull/4065))
- Fixed cancelToken leakage and added AbortController support ([#3305](https://github.com/axios/axios/pull/3305))
- Updating CI to run on release branches
- Bump follow redirects version
- Fixed default transitional config for custom Axios instance; ([#4052](https://github.com/axios/axios/pull/4052))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- [Jay](mailto:jasonsaayman@gmail.com)
- [Matt R. Wilson](https://github.com/mastermatt)
- [Xianming Zhong](https://github.com/chinesedfan)
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
### 0.21.4 (September 6, 2021)
Fixes and Functionality:
- Fixing JSON transform when data is stringified. Providing backward compatibility and complying to the JSON RFC standard ([#4020](https://github.com/axios/axios/pull/4020))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- [Jay](mailto:jasonsaayman@gmail.com)
- [Guillaume Fortaine](https://github.com/gfortaine)
- [Yusuke Kawasaki](https://github.com/kawanet)
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
### 0.21.3 (September 4, 2021)
Fixes and Functionality:
- Fixing response interceptor not being called when request interceptor is attached ([#4013](https://github.com/axios/axios/pull/4013))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- [Jay](mailto:jasonsaayman@gmail.com)
- [Julian Hollmann](https://github.com/nerdbeere)
### 0.21.2 (September 4, 2021)
Fixes and Functionality:
- Updating axios requests to be delayed by pre-emptive promise creation ([#2702](https://github.com/axios/axios/pull/2702))
- Adding "synchronous" and "runWhen" options to interceptors api ([#2702](https://github.com/axios/axios/pull/2702))
- Updating of transformResponse ([#3377](https://github.com/axios/axios/pull/3377))
- Adding ability to omit User-Agent header ([#3703](https://github.com/axios/axios/pull/3703))
- Adding multiple JSON improvements ([#3688](https://github.com/axios/axios/pull/3688), [#3763](https://github.com/axios/axios/pull/3763))
- Fixing quadratic runtime and extra memory usage when setting a maxContentLength ([#3738](https://github.com/axios/axios/pull/3738))
- Adding parseInt to config.timeout ([#3781](https://github.com/axios/axios/pull/3781))
- Adding custom return type support to interceptor ([#3783](https://github.com/axios/axios/pull/3783))
- Adding security fix for ReDoS vulnerability ([#3980](https://github.com/axios/axios/pull/3980))
Internal and Tests:
- Updating build dev dependencies ([#3401](https://github.com/axios/axios/pull/3401))
- Fixing builds running on Travis CI ([#3538](https://github.com/axios/axios/pull/3538))
- Updating follow redirect version ([#3694](https://github.com/axios/axios/pull/3694), [#3771](https://github.com/axios/axios/pull/3771))
- Updating karma sauce launcher to fix failing sauce tests ([#3712](https://github.com/axios/axios/pull/3712), [#3717](https://github.com/axios/axios/pull/3717))
- Updating content-type header for application/json to not contain charset field, according do RFC 8259 ([#2154](https://github.com/axios/axios/pull/2154))
- Fixing tests by bumping karma-sauce-launcher version ([#3813](https://github.com/axios/axios/pull/3813))
- Changing testing process from Travis CI to GitHub Actions ([#3938](https://github.com/axios/axios/pull/3938))
Documentation:
- Updating documentation around the use of `AUTH_TOKEN` with multiple domain endpoints ([#3539](https://github.com/axios/axios/pull/3539))
- Remove duplication of item in changelog ([#3523](https://github.com/axios/axios/pull/3523))
- Fixing grammatical errors ([#2642](https://github.com/axios/axios/pull/2642))
- Fixing spelling error ([#3567](https://github.com/axios/axios/pull/3567))
- Moving gitpod mention ([#2637](https://github.com/axios/axios/pull/2637))
- Adding new axios documentation website link ([#3681](https://github.com/axios/axios/pull/3681), [#3707](https://github.com/axios/axios/pull/3707))
- Updating documentation around dispatching requests ([#3772](https://github.com/axios/axios/pull/3772))
- Adding documentation for the type guard isAxiosError ([#3767](https://github.com/axios/axios/pull/3767))
- Adding explanation of cancel token ([#3803](https://github.com/axios/axios/pull/3803))
- Updating CI status badge ([#3953](https://github.com/axios/axios/pull/3953))
- Fixing errors with JSON documentation ([#3936](https://github.com/axios/axios/pull/3936))
- Fixing README typo under Request Config ([#3825](https://github.com/axios/axios/pull/3825))
- Adding axios-multi-api to the ecosystem file ([#3817](https://github.com/axios/axios/pull/3817))
- Adding SECURITY.md to properly disclose security vulnerabilities ([#3981](https://github.com/axios/axios/pull/3981))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- [Jay](mailto:jasonsaayman@gmail.com)
- [Sasha Korotkov](https://github.com/SashaKoro)
- [Daniel Lopretto](https://github.com/timemachine3030)
- [Mike Bishop](https://github.com/MikeBishop)
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
- [Mark](https://github.com/bimbiltu)
- [Philipe Gouveia Paixão](https://github.com/piiih)
- [hippo](https://github.com/hippo2cat)
- [ready-research](https://github.com/ready-research)
- [Xianming Zhong](https://github.com/chinesedfan)
- [Christopher Chrapka](https://github.com/OJezu)
- [Brian Anglin](https://github.com/anglinb)
- [Kohta Ito](https://github.com/koh110)
- [Ali Clark](https://github.com/aliclark)
- [caikan](https://github.com/caikan)
- [Elina Gorshkova](https://github.com/elinagorshkova)
- [Ryota Ikezawa](https://github.com/paveg)
- [Nisar Hassan Naqvi](https://github.com/nisarhassan12)
- [Jake](https://github.com/codemaster138)
- [TagawaHirotaka](https://github.com/wafuwafu13)
- [Johannes Jarbratt](https://github.com/johachi)
- [Mo Sattler](https://github.com/MoSattler)
- [Sam Carlton](https://github.com/ThatGuySam)
- [Matt Czapliński](https://github.com/MattCCC)
- [Ziding Zhang](https://github.com/zidingz)
### 0.21.1 (December 21, 2020)
Fixes and Functionality:
- Hotfix: Prevent SSRF ([#3410](https://github.com/axios/axios/pull/3410))
- Protocol not parsed when setting proxy config from env vars ([#3070](https://github.com/axios/axios/pull/3070))
- Updating axios in types to be lower case ([#2797](https://github.com/axios/axios/pull/2797))
- Adding a type guard for `AxiosError` ([#2949](https://github.com/axios/axios/pull/2949))
Internal and Tests:
- Remove the skipping of the `socket` http test ([#3364](https://github.com/axios/axios/pull/3364))
- Use different socket for Win32 test ([#3375](https://github.com/axios/axios/pull/3375))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- Daniel Lopretto <timemachine3030@users.noreply.github.com>
- Jason Kwok <JasonHK@users.noreply.github.com>
- Jay <jasonsaayman@gmail.com>
- Jonathan Foster <jonathan@jonathanfoster.io>
- Remco Haszing <remcohaszing@gmail.com>
- Xianming Zhong <chinesedfan@qq.com>
### 0.21.0 (October 23, 2020)
Fixes and Functionality:
- Fixing requestHeaders.Authorization ([#3287](https://github.com/axios/axios/pull/3287))
- Fixing node types ([#3237](https://github.com/axios/axios/pull/3237))
- Fixing axios.delete ignores config.data ([#3282](https://github.com/axios/axios/pull/3282))
- Revert "Fixing overwrite Blob/File type as Content-Type in browser. (#1773)" ([#3289](https://github.com/axios/axios/pull/3289))
- Fixing an issue that type 'null' and 'undefined' is not assignable to validateStatus when typescript strict option is enabled ([#3200](https://github.com/axios/axios/pull/3200))
Internal and Tests:
- Lock travis to not use node v15 ([#3361](https://github.com/axios/axios/pull/3361))
Documentation:
- Fixing simple typo, existent -> existent ([#3252](https://github.com/axios/axios/pull/3252))
- Fixing typos ([#3309](https://github.com/axios/axios/pull/3309))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- Allan Cruz <57270969+Allanbcruz@users.noreply.github.com>
- George Cheng <Gerhut@GMail.com>
- Jay <jasonsaayman@gmail.com>
- Kevin Kirsche <Kev.Kirsche+GitHub@gmail.com>
- Remco Haszing <remcohaszing@gmail.com>
- Taemin Shin <cprayer13@gmail.com>
- Tim Gates <tim.gates@iress.com>
- Xianming Zhong <chinesedfan@qq.com>
### 0.20.0 (August 20, 2020)
Release of 0.20.0-pre as a full release with no other changes.
### 0.20.0-pre (July 15, 2020)
Fixes and Functionality:
- Fixing response with utf-8 BOM can not parse to json ([#2419](https://github.com/axios/axios/pull/2419))
- fix: remove byte order marker (UTF-8 BOM) when transform response
- fix: remove BOM only utf-8
- test: utf-8 BOM
- fix: incorrect param name
- Refactor mergeConfig without utils.deepMerge ([#2844](https://github.com/axios/axios/pull/2844))
- Adding failing test
- Fixing #2587 default custom config persisting
- Adding Concat keys and filter duplicates
- Fixed value from CPE
- update for review feedbacks
- no deepMerge
- only merge between plain objects
- fix rename
- always merge config by mergeConfig
- extract function mergeDeepProperties
- refactor mergeConfig with all keys, and add special logic for validateStatus
- add test for resetting headers
- add lots of tests and fix a bug
- should not inherit `data`
- use simple toString
- Fixing overwrite Blob/File type as Content-Type in browser. ([#1773](https://github.com/axios/axios/pull/1773))
- Fixing an issue that type 'null' is not assignable to validateStatus ([#2773](https://github.com/axios/axios/pull/2773))
- Fixing special char encoding ([#1671](https://github.com/axios/axios/pull/1671))
- removing @ character from replacement list since it is a reserved character
- Updating buildURL test to not include the @ character
- Removing console logs
- Fixing password encoding with special characters in basic authentication ([#1492](https://github.com/axios/axios/pull/1492))
- Fixing password encoding with special characters in basic authentication
- Adding test to check if password with non-Latin1 characters pass
- Fixing 'Network Error' in react native android ([#1487](https://github.com/axios/axios/pull/1487))
There is a bug in react native Android platform when using get method. It will trigger a 'Network Error' when passing the requestData which is an empty string to request.send function. So if the requestData is an empty string we can set it to null as well to fix the bug.
- Fixing Cookie Helper with Async Components ([#1105](https://github.com/axios/axios/pull/1105)) ([#1107](https://github.com/axios/axios/pull/1107))
- Fixing 'progressEvent' type ([#2851](https://github.com/axios/axios/pull/2851))
- Fix 'progressEvent' type
- Update axios.ts
- Fixing getting local files (file://) failed ([#2470](https://github.com/axios/axios/pull/2470))
- fix issue #2416, #2396
- fix Eslint warn
- Modify judgment conditions
- add unit test
- update unit test
- update unit test
- Allow PURGE method in typings ([#2191](https://github.com/axios/axios/pull/2191))
- Adding option to disable automatic decompression ([#2661](https://github.com/axios/axios/pull/2661))
- Adding ability to disable auto decompression
- Updating decompress documentation in README
- Fixing test\unit\adapters\http.js lint errors
- Adding test for disabling auto decompression
- Removing changes that fixed lint errors in tests
- Removing formatting change to unit test
- Add independent `maxBodyLength` option ([#2781](https://github.com/axios/axios/pull/2781))
- Add independent option to set the maximum size of the request body
- Remove maxBodyLength check
- Update README
- Assert for error code and message
- Adding responseEncoding to mergeConfig ([#1745](https://github.com/axios/axios/pull/1745))
- Compatible with follow-redirect aborts the request ([#2689](https://github.com/axios/axios/pull/2689))
- Compatible with follow-redirect aborts the request
- Use the error code
- Fix merging of params ([#2656](https://github.com/axios/axios/pull/2656))
- Name function to avoid ESLint func-names warning
- Switch params config to merge list and update tests
- Restore testing of both false and null
- Restore test cases for keys without defaults
- Include test for non-object values that aren't false-y.
- Revert `finally` as `then` ([#2683](https://github.com/axios/axios/pull/2683))
Internal and Tests:
- Fix stale bot config ([#3049](https://github.com/axios/axios/pull/3049))
- fix stale bot config
- fix multiple lines
- Add days and change name to work ([#3035](https://github.com/axios/axios/pull/3035))
- Update close-issues.yml ([#3031](https://github.com/axios/axios/pull/3031))
- Update close-issues.yml
Update close message to read better 😄
- Fix use of quotations
Use single quotes as per other .yml files
- Remove user name form message
- Add GitHub actions to close stale issues/prs ([#3029](https://github.com/axios/axios/pull/3029))
- prepare stale actions
- update messages
- Add exempt labels and lighten up comments
- Add GitHub actions to close invalid issues ([#3022](https://github.com/axios/axios/pull/3022))
- add close actions
- fix with checkout
- update issue templates
- add reminder
- update close message
- Add test with Node.js 12 ([#2860](https://github.com/axios/axios/pull/2860))
- test with Node.js 12
- test with latest
- Adding console log on sandbox server startup ([#2210](https://github.com/axios/axios/pull/2210))
- Adding console log on sandbox server startup
- Update server.js
Add server error handling
- Update server.js
Better error message, remove retry.
- Adding tests for method `options` type definitions ([#1996](https://github.com/axios/axios/pull/1996))
Update tests.
- Add test for redirecting with too large response ([#2695](https://github.com/axios/axios/pull/2695))
- Fixing unit test failure in Windows OS ([#2601](https://github.com/axios/axios/pull/2601))
- Fixing issue for HEAD method and gzipped response ([#2666](https://github.com/axios/axios/pull/2666))
- Fix tests in browsers ([#2748](https://github.com/axios/axios/pull/2748))
- chore: add `jsdelivr` and `unpkg` support ([#2443](https://github.com/axios/axios/pull/2443))
Documentation:
- Adding support for URLSearchParams in node ([#1900](https://github.com/axios/axios/pull/1900))
- Adding support for URLSearchParams in node
- Remove un-needed code
- Update utils.js
- Make changes as suggested
- Adding table of content (preview) ([#3050](https://github.com/axios/axios/pull/3050))
- add toc (preview)
- remove toc in toc
Signed-off-by: Moni <usmoni@gmail.com>
- fix sublinks
- fix indentation
- remove redundant table links
- update caps and indent
- remove axios
- Replace 'blacklist' with 'blocklist' ([#3006](https://github.com/axios/axios/pull/3006))
- docs(): Detailed config options environment. ([#2088](https://github.com/axios/axios/pull/2088))
- docs(): Detailed config options environment.
- Update README.md
- Include axios-data-unpacker in ECOSYSTEM.md ([#2080](https://github.com/axios/axios/pull/2080))
- Allow opening examples in Gitpod ([#1958](https://github.com/axios/axios/pull/1958))
- Remove axios.all() and axios.spread() from Readme.md ([#2727](https://github.com/axios/axios/pull/2727))
- remove axios.all(), axios.spread()
- replace example
- axios.all() -> Promise.all()
- axios.spread(function (acct, perms)) -> function (acct, perms)
- add deprecated mark
- Update README.md ([#2887](https://github.com/axios/axios/pull/2887))
Small change to the data attribute doc of the config. A request body can also be set for DELETE methods but this wasn't mentioned in the documentation (it only mentioned POST, PUT and PATCH). Took my some 10-20 minutes until I realized that I don't need to manipulate the request body with transformRequest in the case of DELETE.
- Include swagger-taxos-codegen in ECOSYSTEM.md ([#2162](https://github.com/axios/axios/pull/2162))
- Add CDNJS version badge in README.md ([#878](https://github.com/axios/axios/pull/878))
This badge will show the version on CDNJS!
- Documentation update to clear up ambiguity in code examples ([#2928](https://github.com/axios/axios/pull/2928))
- Made an adjustment to the documentation to clear up any ambiguity around the use of "fs". This should help clear up that the code examples with "fs" cannot be used on the client side.
- Update README.md about validateStatus ([#2912](https://github.com/axios/axios/pull/2912))
Rewrote the comment from "Reject only if the status code is greater than or equal to 500" to "Resolve only if the status code is less than 500"
- Updating documentation for usage form-data ([#2805](https://github.com/axios/axios/pull/2805))
Closes #2049
- Fixing CHANGELOG.md issue link ([#2784](https://github.com/axios/axios/pull/2784))
- Include axios-hooks in ECOSYSTEM.md ([#2003](https://github.com/axios/axios/pull/2003))
- Added Response header access instructions ([#1901](https://github.com/axios/axios/pull/1901))
- Added Response header access instructions
- Added note about using bracket notation
- Add `onUploadProgress` and `onDownloadProgress` are browser only ([#2763](https://github.com/axios/axios/pull/2763))
Saw in #928 and #1966 that `onUploadProgress` and `onDownloadProgress` only work in the browser and was missing that from the README.
- Update ' sign to ` in proxy spec ([#2778](https://github.com/axios/axios/pull/2778))
- Adding jsDelivr link in README ([#1110](https://github.com/axios/axios/pull/1110))
- Adding jsDelivr link
- Add SRI
- Remove SRI
Huge thanks to everyone who contributed to this release via code (authors listed
below) or via reviews and triaging on GitHub:
- Alan Wang <wp_scut@163.com>
- Alexandru Ungureanu <khakcarot@gmail.com>
- Anubhav Srivastava <anubhav.srivastava00@gmail.com>
- Benny Neugebauer <bn@bennyn.de>
- Cr <631807682@qq.com>
- David <cygnidavid@gmail.com>
- David Ko <david.ko@pvtmethod.com>
- David Tanner <david.tanner@lifeomic.com>
- Emily Morehouse <emilyemorehouse@gmail.com>
- Felipe Martins <felipewmartins@gmail.com>
- Fonger <5862369+Fonger@users.noreply.github.com>
- Frostack <soulburn007@gmail.com>
- George Cheng <Gerhut@GMail.com>
- grumblerchester <grumblerchester@users.noreply.github.com>
- Gustavo López <gualopezb@gmail.com>
- hexaez <45806662+hexaez@users.noreply.github.com>
- huangzuizui <huangzuizui@gmail.com>
- Ian Wijma <ian@wij.ma>
- Jay <jasonsaayman@gmail.com>
- jeffjing <zgayjjf@qq.com>
- jennynju <46782518+jennynju@users.noreply.github.com>
- Jimmy Liao <52391190+jimmy-liao-gogoro@users.noreply.github.com>
- Jonathan Sharpe <j.r.sharpe@gmail.com>
- JounQin <admin@1stg.me>
- Justin Beckwith <justin.beckwith@gmail.com>
- Kamil Posiadała <3dcreator.pl@gmail.com>
- Lukas Drgon <lukas.drgon@gmail.com>
- marcinx <mail@marcinx.com>
- Martti Laine <martti@codeclown.net>
- Michał Zarach <michal.m.zarach@gmail.com>
- Moni <usmoni@gmail.com>
- Motonori Iwata <121048+iwata@users.noreply.github.com>
- Nikita Galkin <nikita@galk.in>
- Petr Mares <petr@mares.tw>
- Philippe Recto <precto1285@gmal.com>
- Remco Haszing <remcohaszing@gmail.com>
- rockcs1992 <chengshi1219@gmail.com>
- Ryan Bown <rbown@niftee.com.au>
- Samina Fu <sufuf3@gmail.com>
- Simone Busoli <simone.busoli@gmail.com>
- Spencer von der Ohe <s.vonderohe40@gmail.com>
- Sven Efftinge <sven.efftinge@typefox.io>
- Taegyeoung Oh <otk1090@naver.com>
- Taemin Shin <cprayer13@gmail.com>
- Thibault Ehrhart <1208424+ehrhart@users.noreply.github.com>
- Xianming Zhong <chinesedfan@qq.com>
- Yasu Flores <carlosyasu91@gmail.com>
- Zac Delventhal <delventhalz@gmail.com>
### 0.19.2 (Jan 20, 2020)
- Remove unnecessary XSS check ([#2679](https://github.com/axios/axios/pull/2679)) (see ([#2646](https://github.com/axios/axios/issues/2646)) for discussion)
### 0.19.1 (Jan 7, 2020)
Fixes and Functionality:
- Fixing invalid agent issue ([#1904](https://github.com/axios/axios/pull/1904))
- Fix ignore set withCredentials false ([#2582](https://github.com/axios/axios/pull/2582))
- Delete useless default to hash ([#2458](https://github.com/axios/axios/pull/2458))
- Fix HTTP/HTTPs agents passing to follow-redirect ([#1904](https://github.com/axios/axios/pull/1904))
- Fix ignore set withCredentials false ([#2582](https://github.com/axios/axios/pull/2582))
- Fix CI build failure ([#2570](https://github.com/axios/axios/pull/2570))
- Remove dependency on is-buffer from package.json ([#1816](https://github.com/axios/axios/pull/1816))
- Adding options typings ([#2341](https://github.com/axios/axios/pull/2341))
- Adding Typescript HTTP method definition for LINK and UNLINK. ([#2444](https://github.com/axios/axios/pull/2444))
- Update dist with newest changes, fixes Custom Attributes issue
- Change syntax to see if build passes ([#2488](https://github.com/axios/axios/pull/2488))
- Update Webpack + deps, remove now unnecessary polyfills ([#2410](https://github.com/axios/axios/pull/2410))
- Fix to prevent XSS, throw an error when the URL contains a JS script ([#2464](https://github.com/axios/axios/pull/2464))
- Add custom timeout error copy in config ([#2275](https://github.com/axios/axios/pull/2275))
- Add error toJSON example ([#2466](https://github.com/axios/axios/pull/2466))
- Fixing Vulnerability A Fortify Scan finds a critical Cross-Site Scrip… ([#2451](https://github.com/axios/axios/pull/2451))
- Fixing subdomain handling on no_proxy ([#2442](https://github.com/axios/axios/pull/2442))
- Make redirection from HTTP to HTTPS work ([#2426](https://github.com/axios/axios/pull/2426)) and ([#2547](https://github.com/axios/axios/pull/2547))
- Add toJSON property to AxiosError type ([#2427](https://github.com/axios/axios/pull/2427))
- Fixing socket hang up error on node side for slow response. ([#1752](https://github.com/axios/axios/pull/1752))
- Alternative syntax to send data into the body ([#2317](https://github.com/axios/axios/pull/2317))
- Fixing custom config options ([#2207](https://github.com/axios/axios/pull/2207))
- Fixing set `config.method` after mergeConfig for Axios.prototype.request ([#2383](https://github.com/axios/axios/pull/2383))
- Axios create url bug ([#2290](https://github.com/axios/axios/pull/2290))
- Do not modify config.url when using a relative baseURL (resolves [#1628](https://github.com/axios/axios/issues/1098)) ([#2391](https://github.com/axios/axios/pull/2391))
Internal:
- Revert "Update Webpack + deps, remove now unnecessary polyfills" ([#2479](https://github.com/axios/axios/pull/2479))
- Order of if/else blocks is causing unit tests mocking XHR. ([#2201](https://github.com/axios/axios/pull/2201))
- Add license badge ([#2446](https://github.com/axios/axios/pull/2446))
- Fix travis CI build [#2386](https://github.com/axios/axios/pull/2386)
- Fix cancellation error on build master. #2290 #2207 ([#2407](https://github.com/axios/axios/pull/2407))
Documentation:
- Fixing typo in CHANGELOG.md: s/Functionallity/Functionality ([#2639](https://github.com/axios/axios/pull/2639))
- Fix badge, use master branch ([#2538](https://github.com/axios/axios/pull/2538))
- Fix typo in changelog [#2193](https://github.com/axios/axios/pull/2193)
- Document fix ([#2514](https://github.com/axios/axios/pull/2514))
- Update docs with no_proxy change, issue #2484 ([#2513](https://github.com/axios/axios/pull/2513))
- Fixing missing words in docs template ([#2259](https://github.com/axios/axios/pull/2259))
- 🐛Fix request finally documentation in README ([#2189](https://github.com/axios/axios/pull/2189))
- updating spelling and adding link to docs ([#2212](https://github.com/axios/axios/pull/2212))
- docs: minor tweak ([#2404](https://github.com/axios/axios/pull/2404))
- Update response interceptor docs ([#2399](https://github.com/axios/axios/pull/2399))
- Update README.md ([#2504](https://github.com/axios/axios/pull/2504))
- Fix word 'sintaxe' to 'syntax' in README.md ([#2432](https://github.com/axios/axios/pull/2432))
- updating README: notes on CommonJS autocomplete ([#2256](https://github.com/axios/axios/pull/2256))
- Fix grammar in README.md ([#2271](https://github.com/axios/axios/pull/2271))
- Doc fixes, minor examples cleanup ([#2198](https://github.com/axios/axios/pull/2198))
### 0.19.0 (May 30, 2019)
Fixes and Functionality:
- Added support for no_proxy env variable ([#1693](https://github.com/axios/axios/pull/1693/files)) - Chance Dickson
- Unzip response body only for statuses != 204 ([#1129](https://github.com/axios/axios/pull/1129)) - drawski
- Destroy stream on exceeding maxContentLength (fixes [#1098](https://github.com/axios/axios/issues/1098)) ([#1485](https://github.com/axios/axios/pull/1485)) - Gadzhi Gadzhiev
- Makes Axios error generic to use AxiosResponse ([#1738](https://github.com/axios/axios/pull/1738)) - Suman Lama
- Fixing Mocha tests by locking follow-redirects version to 1.5.10 ([#1993](https://github.com/axios/axios/pull/1993)) - grumblerchester
- Allow uppercase methods in typings. ([#1781](https://github.com/axios/axios/pull/1781)) - Ken Powers
- Fixing building url with hash mark ([#1771](https://github.com/axios/axios/pull/1771)) - Anatoly Ryabov
- This commit fix building url with hash map (fragment identifier) when parameters are present: they must not be added after `#`, because client cut everything after `#`
- Preserve HTTP method when following redirect ([#1758](https://github.com/axios/axios/pull/1758)) - Rikki Gibson
- Add `getUri` signature to TypeScript definition. ([#1736](https://github.com/axios/axios/pull/1736)) - Alexander Trauzzi
- Adding isAxiosError flag to errors thrown by axios ([#1419](https://github.com/axios/axios/pull/1419)) - Ayush Gupta
Internal:
- Fixing .eslintrc without extension ([#1789](https://github.com/axios/axios/pull/1789)) - Manoel
- Fix failing SauceLabs tests by updating configuration - Emily Morehouse
- Add issue templates - Emily Morehouse
Documentation:
- Consistent coding style in README ([#1787](https://github.com/axios/axios/pull/1787)) - Ali Servet Donmez
- Add information about auth parameter to README ([#2166](https://github.com/axios/axios/pull/2166)) - xlaguna
- Add DELETE to list of methods that allow data as a config option ([#2169](https://github.com/axios/axios/pull/2169)) - Daniela Borges Matos de Carvalho
- Update ECOSYSTEM.md - Add Axios Endpoints ([#2176](https://github.com/axios/axios/pull/2176)) - Renan
- Add r2curl in ECOSYSTEM ([#2141](https://github.com/axios/axios/pull/2141)) - 유용우 / CX
- Update README.md - Add instructions for installing with yarn ([#2036](https://github.com/axios/axios/pull/2036)) - Victor Hermes
- Fixing spacing for README.md ([#2066](https://github.com/axios/axios/pull/2066)) - Josh McCarty
- Update README.md. - Change `.then` to `.finally` in example code ([#2090](https://github.com/axios/axios/pull/2090)) - Omar Cai
- Clarify what values responseType can have in Node ([#2121](https://github.com/axios/axios/pull/2121)) - Tyler Breisacher
- docs(ECOSYSTEM): add axios-api-versioning ([#2020](https://github.com/axios/axios/pull/2020)) - Weffe
- It seems that `responseType: 'blob'` doesn't actually work in Node (when I tried using it, response.data was a string, not a Blob, since Node doesn't have Blobs), so this clarifies that this option should only be used in the browser
- Update README.md. - Add Querystring library note ([#1896](https://github.com/axios/axios/pull/1896)) - Dmitriy Eroshenko
- Add react-hooks-axios to Libraries section of ECOSYSTEM.md ([#1925](https://github.com/axios/axios/pull/1925)) - Cody Chan
- Clarify in README that default timeout is 0 (no timeout) ([#1750](https://github.com/axios/axios/pull/1750)) - Ben Standefer
### 0.19.0-beta.1 (Aug 9, 2018)
**NOTE:** This is a beta version of this release. There may be functionality that is broken in
certain browsers, though we suspect that builds are hanging and not erroring. See
https://saucelabs.com/u/axios for the most up-to-date information.
New Functionality:
- Add getUri method ([#1712](https://github.com/axios/axios/issues/1712))
- Add support for no_proxy env variable ([#1693](https://github.com/axios/axios/issues/1693))
- Add toJSON to decorated Axios errors to facilitate serialization ([#1625](https://github.com/axios/axios/issues/1625))
- Add second then on axios call ([#1623](https://github.com/axios/axios/issues/1623))
- Typings: allow custom return types
- Add option to specify character set in responses (with http adapter)
Fixes:
- Fix Keep defaults local to instance ([#385](https://github.com/axios/axios/issues/385))
- Correctly catch exception in http test ([#1475](https://github.com/axios/axios/issues/1475))
- Fix accept header normalization ([#1698](https://github.com/axios/axios/issues/1698))
- Fix http adapter to allow HTTPS connections via HTTP ([#959](https://github.com/axios/axios/issues/959))
- Fix Removes usage of deprecated Buffer constructor. ([#1555](https://github.com/axios/axios/issues/1555), [#1622](https://github.com/axios/axios/issues/1622))
- Fix defaults to use httpAdapter if available ([#1285](https://github.com/axios/axios/issues/1285))
- Fixing defaults to use httpAdapter if available
- Use a safer, cross-platform method to detect the Node environment
- Fix Reject promise if request is cancelled by the browser ([#537](https://github.com/axios/axios/issues/537))
- [Typescript] Fix missing type parameters on delete/head methods
- [NS]: Send `false` flag isStandardBrowserEnv for Nativescript
- Fix missing type parameters on delete/head
- Fix Default method for an instance always overwritten by get
- Fix type error when socketPath option in AxiosRequestConfig
- Capture errors on request data streams
- Decorate resolve and reject to clear timeout in all cases
Huge thanks to everyone who contributed to this release via code (authors listed
below) or via reviews and triaging on GitHub:
- Andrew Scott <ascott18@gmail.com>
- Anthony Gauthier <antho325@hotmail.com>
- arpit <arpit2438735@gmail.com>
- ascott18
- Benedikt Rötsch <axe312ger@users.noreply.github.com>
- Chance Dickson <me@chancedickson.com>
- Dave Stewart <info@davestewart.co.uk>
- Deric Cain <deric.cain@gmail.com>
- Guillaume Briday <guillaumebriday@gmail.com>
- Jacob Wejendorp <jacob@wejendorp.dk>
- Jim Lynch <mrdotjim@gmail.com>
- johntron
- Justin Beckwith <beckwith@google.com>
- Justin Beckwith <justin.beckwith@gmail.com>
- Khaled Garbaya <khaledgarbaya@gmail.com>
- Lim Jing Rong <jjingrong@users.noreply.github.com>
- Mark van den Broek <mvdnbrk@gmail.com>
- Martti Laine <martti@codeclown.net>
- mattridley
- mattridley <matt.r@joinblink.com>
- Nicolas Del Valle <nicolas.delvalle@gmail.com>
- Nilegfx
- pbarbiero
- Rikki Gibson <rikkigibson@gmail.com>
- Sako Hartounian <sakohartounian@yahoo.com>
- Shane Fitzpatrick <fitzpasd@gmail.com>
- Stephan Schneider <stephanschndr@gmail.com>
- Steven <steven@ceriously.com>
- Tim Garthwaite <tim.garthwaite@jibo.com>
- Tim Johns <timjohns@yahoo.com>
- Yutaro Miyazaki <yutaro@studio-rubbish.com>
### 0.18.0 (Feb 19, 2018)
- Adding support for UNIX Sockets when running with Node.js ([#1070](https://github.com/axios/axios/pull/1070))
- Fixing typings ([#1177](https://github.com/axios/axios/pull/1177)):
- AxiosRequestConfig.proxy: allows type false
- AxiosProxyConfig: added auth field
- Adding function signature in AxiosInstance interface so AxiosInstance can be invoked ([#1192](https://github.com/axios/axios/pull/1192), [#1254](https://github.com/axios/axios/pull/1254))
- Allowing maxContentLength to pass through to redirected calls as maxBodyLength in follow-redirects config ([#1287](https://github.com/axios/axios/pull/1287))
- Fixing configuration when using an instance - method can now be set ([#1342](https://github.com/axios/axios/pull/1342))
### 0.17.1 (Nov 11, 2017)
- Fixing issue with web workers ([#1160](https://github.com/axios/axios/pull/1160))
- Allowing overriding transport ([#1080](https://github.com/axios/axios/pull/1080))
- Updating TypeScript typings ([#1165](https://github.com/axios/axios/pull/1165), [#1125](https://github.com/axios/axios/pull/1125), [#1131](https://github.com/axios/axios/pull/1131))
### 0.17.0 (Oct 21, 2017)
- **BREAKING** Fixing issue with `baseURL` and interceptors ([#950](https://github.com/axios/axios/pull/950))
- **BREAKING** Improving handing of duplicate headers ([#874](https://github.com/axios/axios/pull/874))
- Adding support for disabling proxies ([#691](https://github.com/axios/axios/pull/691))
- Updating TypeScript typings with generic type parameters ([#1061](https://github.com/axios/axios/pull/1061))
### 0.16.2 (Jun 3, 2017)
- Fixing issue with including `buffer` in bundle ([#887](https://github.com/axios/axios/pull/887))
- Including underlying request in errors ([#830](https://github.com/axios/axios/pull/830))
- Convert `method` to lowercase ([#930](https://github.com/axios/axios/pull/930))
### 0.16.1 (Apr 8, 2017)
- Improving HTTP adapter to return last request in case of redirects ([#828](https://github.com/axios/axios/pull/828))
- Updating `follow-redirects` dependency ([#829](https://github.com/axios/axios/pull/829))
- Adding support for passing `Buffer` in node ([#773](https://github.com/axios/axios/pull/773))
### 0.16.0 (Mar 31, 2017)
- **BREAKING** Removing `Promise` from axios typings in favor of built-in type declarations ([#480](https://github.com/axios/axios/issues/480))
- Adding `options` shortcut method ([#461](https://github.com/axios/axios/pull/461))
- Fixing issue with using `responseType: 'json'` in browsers incompatible with XHR Level 2 ([#654](https://github.com/axios/axios/pull/654))
- Improving React Native detection ([#731](https://github.com/axios/axios/pull/731))
- Fixing `combineURLs` to support empty `relativeURL` ([#581](https://github.com/axios/axios/pull/581))
- Removing `PROTECTION_PREFIX` support ([#561](https://github.com/axios/axios/pull/561))
### 0.15.3 (Nov 27, 2016)
- Fixing issue with custom instances and global defaults ([#443](https://github.com/axios/axios/issues/443))
- Renaming `axios.d.ts` to `index.d.ts` ([#519](https://github.com/axios/axios/issues/519))
- Adding `get`, `head`, and `delete` to `defaults.headers` ([#509](https://github.com/axios/axios/issues/509))
- Fixing issue with `btoa` and IE ([#507](https://github.com/axios/axios/issues/507))
- Adding support for proxy authentication ([#483](https://github.com/axios/axios/pull/483))
- Improving HTTP adapter to use `http` protocol by default ([#493](https://github.com/axios/axios/pull/493))
- Fixing proxy issues ([#491](https://github.com/axios/axios/pull/491))
### 0.15.2 (Oct 17, 2016)
- Fixing issue with calling `cancel` after response has been received ([#482](https://github.com/axios/axios/issues/482))
### 0.15.1 (Oct 14, 2016)
- Fixing issue with UMD ([#485](https://github.com/axios/axios/issues/485))
### 0.15.0 (Oct 10, 2016)
- Adding cancellation support ([#452](https://github.com/axios/axios/pull/452))
- Moving default adapter to global defaults ([#437](https://github.com/axios/axios/pull/437))
- Fixing issue with `file` URI scheme ([#440](https://github.com/axios/axios/pull/440))
- Fixing issue with `params` objects that have no prototype ([#445](https://github.com/axios/axios/pull/445))
### 0.14.0 (Aug 27, 2016)
- **BREAKING** Updating TypeScript definitions ([#419](https://github.com/axios/axios/pull/419))
- **BREAKING** Replacing `agent` option with `httpAgent` and `httpsAgent` ([#387](https://github.com/axios/axios/pull/387))
- **BREAKING** Splitting `progress` event handlers into `onUploadProgress` and `onDownloadProgress` ([#423](https://github.com/axios/axios/pull/423))
- Adding support for `http_proxy` and `https_proxy` environment variables ([#366](https://github.com/axios/axios/pull/366))
- Fixing issue with `auth` config option and `Authorization` header ([#397](https://github.com/axios/axios/pull/397))
- Don't set XSRF header if `xsrfCookieName` is `null` ([#406](https://github.com/axios/axios/pull/406))
### 0.13.1 (Jul 16, 2016)
- Fixing issue with response data not being transformed on error ([#378](https://github.com/axios/axios/issues/378))
### 0.13.0 (Jul 13, 2016)
- **BREAKING** Improved error handling ([#345](https://github.com/axios/axios/pull/345))
- **BREAKING** Response transformer now invoked in dispatcher not adapter ([10eb238](https://github.com/axios/axios/commit/10eb23865101f9347570552c04e9d6211376e25e))
- **BREAKING** Request adapters now return a `Promise` ([157efd5](https://github.com/axios/axios/commit/157efd5615890301824e3121cc6c9d2f9b21f94a))
- Fixing issue with `withCredentials` not being overwritten ([#343](https://github.com/axios/axios/issues/343))
- Fixing regression with request transformer being called before request interceptor ([#352](https://github.com/axios/axios/issues/352))
- Fixing custom instance defaults ([#341](https://github.com/axios/axios/issues/341))
- Fixing instances created from `axios.create` to have same API as default axios ([#217](https://github.com/axios/axios/issues/217))
### 0.12.0 (May 31, 2016)
- Adding support for `URLSearchParams` ([#317](https://github.com/axios/axios/pull/317))
- Adding `maxRedirects` option ([#307](https://github.com/axios/axios/pull/307))
### 0.11.1 (May 17, 2016)
- Fixing IE CORS support ([#313](https://github.com/axios/axios/pull/313))
- Fixing detection of `FormData` ([#325](https://github.com/axios/axios/pull/325))
- Adding `Axios` class to exports ([#321](https://github.com/axios/axios/pull/321))
### 0.11.0 (Apr 26, 2016)
- Adding support for Stream with HTTP adapter ([#296](https://github.com/axios/axios/pull/296))
- Adding support for custom HTTP status code error ranges ([#308](https://github.com/axios/axios/pull/308))
- Fixing issue with ArrayBuffer ([#299](https://github.com/axios/axios/pull/299))
### 0.10.0 (Apr 20, 2016)
- Fixing issue with some requests sending `undefined` instead of `null` ([#250](https://github.com/axios/axios/pull/250))
- Fixing basic auth for HTTP adapter ([#252](https://github.com/axios/axios/pull/252))
- Fixing request timeout for XHR adapter ([#227](https://github.com/axios/axios/pull/227))
- Fixing IE8 support by using `onreadystatechange` instead of `onload` ([#249](https://github.com/axios/axios/pull/249))
- Fixing IE9 cross domain requests ([#251](https://github.com/axios/axios/pull/251))
- Adding `maxContentLength` option ([#275](https://github.com/axios/axios/pull/275))
- Fixing XHR support for WebWorker environment ([#279](https://github.com/axios/axios/pull/279))
- Adding request instance to response ([#200](https://github.com/axios/axios/pull/200))
### 0.9.1 (Jan 24, 2016)
- Improving handling of request timeout in node ([#124](https://github.com/axios/axios/issues/124))
- Fixing network errors not rejecting ([#205](https://github.com/axios/axios/pull/205))
- Fixing issue with IE rejecting on HTTP 204 ([#201](https://github.com/axios/axios/issues/201))
- Fixing host/port when following redirects ([#198](https://github.com/axios/axios/pull/198))
### 0.9.0 (Jan 18, 2016)
- Adding support for custom adapters
- Fixing Content-Type header being removed when data is false ([#195](https://github.com/axios/axios/pull/195))
- Improving XDomainRequest implementation ([#185](https://github.com/axios/axios/pull/185))
- Improving config merging and order of precedence ([#183](https://github.com/axios/axios/pull/183))
- Fixing XDomainRequest support for only <= IE9 ([#182](https://github.com/axios/axios/pull/182))
### 0.8.1 (Dec 14, 2015)
- Adding support for passing XSRF token for cross domain requests when using `withCredentials` ([#168](https://github.com/axios/axios/pull/168))
- Fixing error with format of basic auth header ([#178](https://github.com/axios/axios/pull/173))
- Fixing error with JSON payloads throwing `InvalidStateError` in some cases ([#174](https://github.com/axios/axios/pull/174))
### 0.8.0 (Dec 11, 2015)
- Adding support for creating instances of axios ([#123](https://github.com/axios/axios/pull/123))
- Fixing http adapter to use `Buffer` instead of `String` in case of `responseType === 'arraybuffer'` ([#128](https://github.com/axios/axios/pull/128))
- Adding support for using custom parameter serializer with `paramsSerializer` option ([#121](https://github.com/axios/axios/pull/121))
- Fixing issue in IE8 caused by `forEach` on `arguments` ([#127](https://github.com/axios/axios/pull/127))
- Adding support for following redirects in node ([#146](https://github.com/axios/axios/pull/146))
- Adding support for transparent decompression if `content-encoding` is set ([#149](https://github.com/axios/axios/pull/149))
- Adding support for transparent XDomainRequest to handle cross domain requests in IE9 ([#140](https://github.com/axios/axios/pull/140))
- Adding support for HTTP basic auth via Authorization header ([#167](https://github.com/axios/axios/pull/167))
- Adding support for baseURL option ([#160](https://github.com/axios/axios/pull/160))
### 0.7.0 (Sep 29, 2015)
- Fixing issue with minified bundle in IE8 ([#87](https://github.com/axios/axios/pull/87))
- Adding support for passing agent in node ([#102](https://github.com/axios/axios/pull/102))
- Adding support for returning result from `axios.spread` for chaining ([#106](https://github.com/axios/axios/pull/106))
- Fixing typescript definition ([#105](https://github.com/axios/axios/pull/105))
- Fixing default timeout config for node ([#112](https://github.com/axios/axios/pull/112))
- Adding support for use in web workers, and react-native ([#70](https://github.com/axios/axios/issue/70)), ([#98](https://github.com/axios/axios/pull/98))
- Adding support for fetch like API `axios(url[, config])` ([#116](https://github.com/axios/axios/issues/116))
### 0.6.0 (Sep 21, 2015)
- Removing deprecated success/error aliases
- Fixing issue with array params not being properly encoded ([#49](https://github.com/axios/axios/pull/49))
- Fixing issue with User-Agent getting overridden ([#69](https://github.com/axios/axios/issues/69))
- Adding support for timeout config ([#56](https://github.com/axios/axios/issues/56))
- Removing es6-promise dependency
- Fixing issue preventing `length` to be used as a parameter ([#91](https://github.com/axios/axios/pull/91))
- Fixing issue with IE8 ([#85](https://github.com/axios/axios/pull/85))
- Converting build to UMD
### 0.5.4 (Apr 08, 2015)
- Fixing issue with FormData not being sent ([#53](https://github.com/axios/axios/issues/53))
### 0.5.3 (Apr 07, 2015)
- Using JSON.parse unconditionally when transforming response string ([#55](https://github.com/axios/axios/issues/55))
### 0.5.2 (Mar 13, 2015)
- Adding support for `statusText` in response ([#46](https://github.com/axios/axios/issues/46))
### 0.5.1 (Mar 10, 2015)
- Fixing issue using strict mode ([#45](https://github.com/axios/axios/issues/45))
- Fixing issue with standalone build ([#47](https://github.com/axios/axios/issues/47))
### 0.5.0 (Jan 23, 2015)
- Adding support for intercepetors ([#14](https://github.com/axios/axios/issues/14))
- Updating es6-promise dependency
### 0.4.2 (Dec 10, 2014)
- Fixing issue with `Content-Type` when using `FormData` ([#22](https://github.com/axios/axios/issues/22))
- Adding support for TypeScript ([#25](https://github.com/axios/axios/issues/25))
- Fixing issue with standalone build ([#29](https://github.com/axios/axios/issues/29))
- Fixing issue with verbs needing to be capitalized in some browsers ([#30](https://github.com/axios/axios/issues/30))
### 0.4.1 (Oct 15, 2014)
- Adding error handling to request for node.js ([#18](https://github.com/axios/axios/issues/18))
### 0.4.0 (Oct 03, 2014)
- Adding support for `ArrayBuffer` and `ArrayBufferView` ([#10](https://github.com/axios/axios/issues/10))
- Adding support for utf-8 for node.js ([#13](https://github.com/axios/axios/issues/13))
- Adding support for SSL for node.js ([#12](https://github.com/axios/axios/issues/12))
- Fixing incorrect `Content-Type` header ([#9](https://github.com/axios/axios/issues/9))
- Adding standalone build without bundled es6-promise ([#11](https://github.com/axios/axios/issues/11))
- Deprecating `success`/`error` in favor of `then`/`catch`
### 0.3.1 (Sep 16, 2014)
- Fixing missing post body when using node.js ([#3](https://github.com/axios/axios/issues/3))
### 0.3.0 (Sep 16, 2014)
- Fixing `success` and `error` to properly receive response data as individual arguments ([#8](https://github.com/axios/axios/issues/8))
- Updating `then` and `catch` to receive response data as a single object ([#6](https://github.com/axios/axios/issues/6))
- Fixing issue with `all` not working ([#7](https://github.com/axios/axios/issues/7))
### 0.2.2 (Sep 14, 2014)
- Fixing bundling with browserify ([#4](https://github.com/axios/axios/issues/4))
### 0.2.1 (Sep 12, 2014)
- Fixing build problem causing ridiculous file sizes
### 0.2.0 (Sep 12, 2014)
- Adding support for `all` and `spread`
- Adding support for node.js ([#1](https://github.com/axios/axios/issues/1))
### 0.1.0 (Aug 29, 2014)
- Initial release

View File

@ -1,19 +0,0 @@
Copyright (c) 2014-present Matt Zabriskie
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,991 +0,0 @@
# axios
[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
[![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios)
![Build status](https://github.com/axios/axios/actions/workflows/ci.yml/badge.svg)
[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/axios/axios)
[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)
[![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios)
[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios)
[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
[![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios)
Promise based HTTP client for the browser and node.js
> New axios docs website: [click here](https://axios-http.com/)
## Table of Contents
- [Features](#features)
- [Browser Support](#browser-support)
- [Installing](#installing)
- [Example](#example)
- [Axios API](#axios-api)
- [Request method aliases](#request-method-aliases)
- [Concurrency 👎](#concurrency-deprecated)
- [Creating an instance](#creating-an-instance)
- [Instance methods](#instance-methods)
- [Request Config](#request-config)
- [Response Schema](#response-schema)
- [Config Defaults](#config-defaults)
- [Global axios defaults](#global-axios-defaults)
- [Custom instance defaults](#custom-instance-defaults)
- [Config order of precedence](#config-order-of-precedence)
- [Interceptors](#interceptors)
- [Multiple Interceptors](#multiple-interceptors)
- [Handling Errors](#handling-errors)
- [Cancellation](#cancellation)
- [AbortController](#abortcontroller)
- [CancelToken 👎](#canceltoken-deprecated)
- [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
- [Browser](#browser)
- [Node.js](#nodejs)
- [Query string](#query-string)
- [Form data](#form-data)
- [Automatic serialization](#-automatic-serialization)
- [Manual FormData passing](#manual-formdata-passing)
- [Semver](#semver)
- [Promises](#promises)
- [TypeScript](#typescript)
- [Resources](#resources)
- [Credits](#credits)
- [License](#license)
## Features
- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
- Make [http](http://nodejs.org/api/http.html) requests from node.js
- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
## Browser Support
![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) |
--- | --- | --- | --- | --- | --- |
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)
## Installing
Using npm:
```bash
$ npm install axios
```
Using bower:
```bash
$ bower install axios
```
Using yarn:
```bash
$ yarn add axios
```
Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```
## Example
### note: CommonJS usage
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
```js
const axios = require('axios').default;
// axios.<method> will now provide autocomplete and parameter typings
```
Performing a `GET` request
```js
const axios = require('axios').default;
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
```
> **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet
> Explorer and older browsers, so use with caution.
Performing a `POST` request
```js
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
Performing multiple concurrent requests
```js
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});
```
## axios API
Requests can be made by passing the relevant config to `axios`.
##### axios(config)
```js
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
```
```js
// GET request for remote image in node.js
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
```
##### axios(url[, config])
```js
// Send a GET request (default method)
axios('/user/12345');
```
### Request method aliases
For convenience, aliases have been provided for all common request methods.
##### axios.request(config)
##### axios.get(url[, config])
##### axios.delete(url[, config])
##### axios.head(url[, config])
##### axios.options(url[, config])
##### axios.post(url[, data[, config]])
##### axios.put(url[, data[, config]])
##### axios.patch(url[, data[, config]])
###### NOTE
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
### Concurrency (Deprecated)
Please use `Promise.all` to replace the below functions.
Helper functions for dealing with concurrent requests.
axios.all(iterable)
axios.spread(callback)
### Creating an instance
You can create a new instance of axios with a custom config.
##### axios.create([config])
```js
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
```
### Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.
##### axios#request(config)
##### axios#get(url[, config])
##### axios#delete(url[, config])
##### axios#head(url[, config])
##### axios#options(url[, config])
##### axios#post(url[, data[, config]])
##### axios#put(url[, data[, config]])
##### axios#patch(url[, data[, config]])
##### axios#getUri([config])
## Request Config
These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
```js
{
// `url` is the server URL that will be used for the request
url: '/user',
// `method` is the request method to be used when making the request
method: 'get', // default
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL: 'https://some-domain.com/api/',
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data
return data;
}],
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
ID: 12345
},
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
// `timeout` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, the request will be aborted.
timeout: 1000, // default is `0` (no timeout)
// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentials
withCredentials: false, // default
// `adapter` allows custom handling of requests which makes testing easier.
// Return a promise and supply a valid response (see lib/adapters/README.md).
adapter: function (config) {
/* ... */
},
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
// Please note that only HTTP Basic auth is configurable through this parameter.
// For Bearer tokens and such, use `Authorization` custom headers instead.
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
// browser only: 'blob'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` allows handling of progress events for uploads
// browser only
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` allows handling of progress events for downloads
// browser only
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
maxContentLength: 2000,
// `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
maxBodyLength: 2000,
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
// If set to 0, no redirects will be followed.
maxRedirects: 21, // default
// `beforeRedirect` defines a function that will be called before redirect.
// Use this to adjust the request options upon redirecting,
// to inspect the latest response headers,
// or to cancel the request by throwing an error
// If maxRedirects is set to 0, `beforeRedirect` is not used.
beforeRedirect: (options, { headers }) => {
if (options.hostname === "example.com") {
options.auth = "user:password";
}
};
// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null, // default
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` defines the hostname, port, and protocol of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment
// variable as a comma-separated list of domains that should not be proxied.
// Use `false` to disable proxies, ignoring environment variables.
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
// supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`.
// If the proxy server uses HTTPS, then you must set the protocol to `https`.
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` specifies a cancel token that can be used to cancel the request
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
}),
// an alternative way to cancel Axios requests using AbortController
signal: new AbortController().signal,
// `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// - Node only (XHR cannot turn off decompression)
decompress: true // default
// `insecureHTTPParser` boolean.
// Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
// This may allow interoperability with non-conformant HTTP implementations.
// Using the insecure parser should be avoided.
// see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
// see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
insecureHTTPParser: undefined // default
// transitional options for backward compatibility that may be removed in the newer versions
transitional: {
// silent JSON parsing mode
// `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
// `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
silentJSONParsing: true, // default value for the current Axios version
// try to parse the response string as JSON even if `responseType` is not 'json'
forcedJSONParsing: true,
// throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
clarifyTimeoutError: false,
},
env: {
// The FormData class to be used to automatically serialize the payload into a FormData object
FormData: window?.FormData || global?.FormData
}
}
```
## Response Schema
The response for a request contains the following information.
```js
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the HTTP headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}
```
When using `then`, you will receive the response as follows:
```js
axios.get('/user/12345')
.then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
```
When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section.
## Config Defaults
You can specify config defaults that will be applied to every request.
### Global axios defaults
```js
axios.defaults.baseURL = 'https://api.example.com';
// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
// See below for an example using Custom instance defaults instead.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
```
### Custom instance defaults
```js
// Set config defaults when creating the instance
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
```
### Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.
```js
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();
// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;
// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
timeout: 5000
});
```
## Interceptors
You can intercept requests or responses before they are handled by `then` or `catch`.
```js
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
```
If you need to remove an interceptor later you can.
```js
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
```
You can add interceptors to a custom instance of axios.
```js
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
```
When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag
to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
```js
axios.interceptors.request.use(function (config) {
config.headers.test = 'I am only a header!';
return config;
}, null, { synchronous: true });
```
If you want to execute a particular interceptor based on a runtime check,
you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return
of `runWhen` is `false`. The function will be called with the config
object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
asynchronous request interceptor that only needs to run at certain times.
```js
function onGetCall(config) {
return config.method === 'get';
}
axios.interceptors.request.use(function (config) {
config.headers.test = 'special get headers';
return config;
}, null, { runWhen: onGetCall });
```
### Multiple Interceptors
Given you add multiple response interceptors
and when the response was fulfilled
- then each interceptor is executed
- then they are executed in the order they were added
- then only the last interceptor's result is returned
- then every interceptor receives the result of it's predecessor
- and when the fulfillment-interceptor throws
- then the following fulfillment-interceptor is not called
- then the following rejection-interceptor is called
- once caught, another following fulfill-interceptor is called again (just like in a promise chain).
Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code.
## Handling Errors
```js
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
```
Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error.
```js
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Resolve only if the status code is less than 500
}
})
```
Using `toJSON` you get an object with more information about the HTTP error.
```js
axios.get('/user/12345')
.catch(function (error) {
console.log(error.toJSON());
});
```
## Cancellation
### AbortController
Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way:
```js
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()
```
### CancelToken `👎deprecated`
You can also cancel a request using a *CancelToken*.
> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
> This API is deprecated since v0.22.0 and shouldn't be used in new projects
You can create a cancel token using the `CancelToken.source` factory as shown below:
```js
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
```
You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
```js
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
```
> Note: you can cancel several requests with the same cancel token/abort controller.
> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make real request.
> During the transition period, you can use both cancellation APIs, even for the same request:
## Using application/x-www-form-urlencoded format
By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options.
### Browser
In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:
```js
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
```
> Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
```js
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
```
Or in another way (ES6),
```js
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
```
### Node.js
#### Query string
In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
```js
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
```
or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows:
```js
const url = require('url');
const params = new url.URLSearchParams({ foo: 'bar' });
axios.post('http://something.com/', params.toString());
```
You can also use the [`qs`](https://github.com/ljharb/qs) library.
> NOTE:
> The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case.
#### Form data
##### 🆕 Automatic serialization
Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`
header is set to `multipart/form-data`.
The following request will submit the data in a FormData format (Browser & Node.js):
```js
import axios from 'axios';
axios.post('https://httpbin.org/post', {x: 1}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data})=> console.log(data));
```
In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.
You can overload the FormData class by setting the `env.FormData` config variable,
but you probably won't need it in most cases:
```js
const axios= require('axios');
var FormData = require('form-data');
axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data})=> console.log(data));
```
Axios FormData serializer supports some special endings to perform the following operations:
- `{}` - serialize the value with JSON.stringify
- `[]` - unwrap the array like object as separate fields with the same key
```js
const axios= require('axios');
axios.post('https://httpbin.org/post', {
'myObj{}': {x: 1, s: "foo"},
'files[]': document.querySelector('#fileInput').files
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data})=> console.log(data));
```
Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
which are just the corresponding http methods with a header preset: `Content-Type`: `multipart/form-data`.
FileList object can be passed directly:
```js
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
```
All files will be sent with the same field names: `files[]`;
##### Manual FormData passing
In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
```js
const FormData = require('form-data');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form)
```
## Semver
Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
## Promises
axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
## TypeScript
axios includes [TypeScript](http://typescriptlang.org) definitions and a type guard for axios errors.
```typescript
let user: User = null;
try {
const { data } = await axios.get('/user?ID=12345');
user = data.userDetails;
} catch (error) {
if (axios.isAxiosError(error)) {
handleAxiosError(error);
} else {
handleUnexpectedError(error);
}
}
```
## Online one-click setup
You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online.
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/master/examples/server.js)
## Resources
* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)
## Credits
axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [AngularJS](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of AngularJS.
## License
[MIT](LICENSE)

View File

@ -1,5 +0,0 @@
# Security Policy
## Reporting a Vulnerability
Please report security issues to jasonsaayman@gmail.com

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,254 +0,0 @@
// TypeScript Version: 3.0
export type AxiosRequestHeaders = Record<string, string | number | boolean>;
export type AxiosResponseHeaders = Record<string, string> & {
"set-cookie"?: string[]
};
export interface AxiosRequestTransformer {
(data: any, headers?: AxiosRequestHeaders): any;
}
export interface AxiosResponseTransformer {
(data: any, headers?: AxiosResponseHeaders): any;
}
export interface AxiosAdapter {
(config: AxiosRequestConfig): AxiosPromise;
}
export interface AxiosBasicCredentials {
username: string;
password: string;
}
export interface AxiosProxyConfig {
host: string;
port: number;
auth?: {
username: string;
password: string;
};
protocol?: string;
}
export type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK';
export type ResponseType =
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
| 'stream';
export type responseEncoding =
| 'ascii' | 'ASCII'
| 'ansi' | 'ANSI'
| 'binary' | 'BINARY'
| 'base64' | 'BASE64'
| 'base64url' | 'BASE64URL'
| 'hex' | 'HEX'
| 'latin1' | 'LATIN1'
| 'ucs-2' | 'UCS-2'
| 'ucs2' | 'UCS2'
| 'utf-8' | 'UTF-8'
| 'utf8' | 'UTF8'
| 'utf16le' | 'UTF16LE';
export interface TransitionalOptions {
silentJSONParsing?: boolean;
forcedJSONParsing?: boolean;
clarifyTimeoutError?: boolean;
}
export interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: AxiosRequestHeaders;
params?: any;
paramsSerializer?: (params: any) => string;
data?: D;
timeout?: number;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: AbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
};
}
export interface HeadersDefaults {
common: AxiosRequestHeaders;
delete: AxiosRequestHeaders;
get: AxiosRequestHeaders;
head: AxiosRequestHeaders;
post: AxiosRequestHeaders;
put: AxiosRequestHeaders;
patch: AxiosRequestHeaders;
options?: AxiosRequestHeaders;
purge?: AxiosRequestHeaders;
link?: AxiosRequestHeaders;
unlink?: AxiosRequestHeaders;
}
export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers: HeadersDefaults;
}
export interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: AxiosResponseHeaders;
config: AxiosRequestConfig<D>;
request?: any;
}
export class AxiosError<T = unknown, D = any> extends Error {
constructor(
message?: string,
code?: string,
config?: AxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>
);
config: AxiosRequestConfig<D>;
code?: string;
request?: any;
response?: AxiosResponse<T, D>;
isAxiosError: boolean;
status?: string;
toJSON: () => object;
static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
static readonly ERR_NETWORK = "ERR_NETWORK";
static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
static readonly ERR_CANCELED = "ERR_CANCELED";
static readonly ECONNABORTED = "ECONNABORTED";
static readonly ETIMEDOUT = "ETIMEDOUT";
}
export class CanceledError<T> extends AxiosError<T> {
}
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
}
export interface CancelStatic {
new (message?: string): Cancel;
}
export interface Cancel {
message: string | undefined;
}
export interface Canceler {
(message?: string): void;
}
export interface CancelTokenStatic {
new (executor: (cancel: Canceler) => void): CancelToken;
source(): CancelTokenSource;
}
export interface CancelToken {
promise: Promise<Cancel>;
reason?: Cancel;
throwIfRequested(): void;
}
export interface CancelTokenSource {
token: CancelToken;
cancel: Canceler;
}
export interface AxiosInterceptorOptions {
synchronous?: boolean;
runWhen?: (config: AxiosRequestConfig) => boolean;
}
export interface AxiosInterceptorManager<V> {
use<T = V>(onFulfilled?: (value: V) => T | Promise<T>, onRejected?: (error: any) => any, options?: AxiosInterceptorOptions): number;
eject(id: number): void;
}
export class Axios {
constructor(config?: AxiosRequestConfig);
defaults: AxiosDefaults;
interceptors: {
request: AxiosInterceptorManager<AxiosRequestConfig>;
response: AxiosInterceptorManager<AxiosResponse>;
};
getUri(config?: AxiosRequestConfig): string;
request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
head<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
options<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
postForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
putForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
patchForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
}
export interface AxiosInstance extends Axios {
(config: AxiosRequestConfig): AxiosPromise;
(url: string, config?: AxiosRequestConfig): AxiosPromise;
}
export interface AxiosStatic extends AxiosInstance {
create(config?: AxiosRequestConfig): AxiosInstance;
Cancel: CancelStatic;
CancelToken: CancelTokenStatic;
Axios: typeof Axios;
readonly VERSION: string;
isCancel(value: any): boolean;
all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
isAxiosError(payload: any): payload is AxiosError;
}
declare const axios: AxiosStatic;
export default axios;

View File

@ -1 +0,0 @@
module.exports = require('./lib/axios');

View File

@ -1,37 +0,0 @@
# axios // adapters
The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.
## Example
```js
var settle = require('./../core/settle');
module.exports = function myAdapter(config) {
// At this point:
// - config has been merged with defaults
// - request transformers have already run
// - request interceptors have already run
// Make the request using config provided
// Upon response settle the Promise
return new Promise(function(resolve, reject) {
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// From here:
// - response transformers will run
// - response interceptors will run
});
}
```

View File

@ -1,424 +0,0 @@
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var buildFullPath = require('../core/buildFullPath');
var buildURL = require('./../helpers/buildURL');
var http = require('http');
var https = require('https');
var httpFollow = require('follow-redirects').http;
var httpsFollow = require('follow-redirects').https;
var url = require('url');
var zlib = require('zlib');
var VERSION = require('./../env/data').version;
var transitionalDefaults = require('../defaults/transitional');
var AxiosError = require('../core/AxiosError');
var CanceledError = require('../cancel/CanceledError');
var isHttps = /https:?/;
var supportedProtocols = [ 'http:', 'https:', 'file:' ];
/**
*
* @param {http.ClientRequestArgs} options
* @param {AxiosProxyConfig} proxy
* @param {string} location
*/
function setProxy(options, proxy, location) {
options.hostname = proxy.host;
options.host = proxy.host;
options.port = proxy.port;
options.path = location;
// Basic proxy authorization
if (proxy.auth) {
var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
}
// If a proxy is used, any redirects must also pass through the proxy
options.beforeRedirect = function beforeRedirect(redirection) {
redirection.headers.host = redirection.host;
setProxy(redirection, proxy, redirection.href);
};
}
/*eslint consistent-return:0*/
module.exports = function httpAdapter(config) {
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
var onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
var resolve = function resolve(value) {
done();
resolvePromise(value);
};
var rejected = false;
var reject = function reject(value) {
done();
rejected = true;
rejectPromise(value);
};
var data = config.data;
var headers = config.headers;
var headerNames = {};
Object.keys(headers).forEach(function storeLowerName(name) {
headerNames[name.toLowerCase()] = name;
});
// Set User-Agent (required by some servers)
// See https://github.com/axios/axios/issues/69
if ('user-agent' in headerNames) {
// User-Agent is specified; handle case where no UA header is desired
if (!headers[headerNames['user-agent']]) {
delete headers[headerNames['user-agent']];
}
// Otherwise, use specified value
} else {
// Only set header if it hasn't been set in config
headers['User-Agent'] = 'axios/' + VERSION;
}
// support for https://www.npmjs.com/package/form-data api
if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
Object.assign(headers, data.getHeaders());
} else if (data && !utils.isStream(data)) {
if (Buffer.isBuffer(data)) {
// Nothing to do...
} else if (utils.isArrayBuffer(data)) {
data = Buffer.from(new Uint8Array(data));
} else if (utils.isString(data)) {
data = Buffer.from(data, 'utf-8');
} else {
return reject(new AxiosError(
'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
AxiosError.ERR_BAD_REQUEST,
config
));
}
if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
return reject(new AxiosError(
'Request body larger than maxBodyLength limit',
AxiosError.ERR_BAD_REQUEST,
config
));
}
// Add Content-Length header if data exists
if (!headerNames['content-length']) {
headers['Content-Length'] = data.length;
}
}
// HTTP basic authentication
var auth = undefined;
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
auth = username + ':' + password;
}
// Parse url
var fullPath = buildFullPath(config.baseURL, config.url);
var parsed = url.parse(fullPath);
var protocol = parsed.protocol || supportedProtocols[0];
if (supportedProtocols.indexOf(protocol) === -1) {
return reject(new AxiosError(
'Unsupported protocol ' + protocol,
AxiosError.ERR_BAD_REQUEST,
config
));
}
if (!auth && parsed.auth) {
var urlAuth = parsed.auth.split(':');
var urlUsername = urlAuth[0] || '';
var urlPassword = urlAuth[1] || '';
auth = urlUsername + ':' + urlPassword;
}
if (auth && headerNames.authorization) {
delete headers[headerNames.authorization];
}
var isHttpsRequest = isHttps.test(protocol);
var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
try {
buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, '');
} catch (err) {
var customErr = new Error(err.message);
customErr.config = config;
customErr.url = config.url;
customErr.exists = true;
reject(customErr);
}
var options = {
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
method: config.method.toUpperCase(),
headers: headers,
agent: agent,
agents: { http: config.httpAgent, https: config.httpsAgent },
auth: auth
};
if (config.socketPath) {
options.socketPath = config.socketPath;
} else {
options.hostname = parsed.hostname;
options.port = parsed.port;
}
var proxy = config.proxy;
if (!proxy && proxy !== false) {
var proxyEnv = protocol.slice(0, -1) + '_proxy';
var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
if (proxyUrl) {
var parsedProxyUrl = url.parse(proxyUrl);
var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;
var shouldProxy = true;
if (noProxyEnv) {
var noProxy = noProxyEnv.split(',').map(function trim(s) {
return s.trim();
});
shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {
if (!proxyElement) {
return false;
}
if (proxyElement === '*') {
return true;
}
if (proxyElement[0] === '.' &&
parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {
return true;
}
return parsed.hostname === proxyElement;
});
}
if (shouldProxy) {
proxy = {
host: parsedProxyUrl.hostname,
port: parsedProxyUrl.port,
protocol: parsedProxyUrl.protocol
};
if (parsedProxyUrl.auth) {
var proxyUrlAuth = parsedProxyUrl.auth.split(':');
proxy.auth = {
username: proxyUrlAuth[0],
password: proxyUrlAuth[1]
};
}
}
}
}
if (proxy) {
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
}
var transport;
var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
if (config.transport) {
transport = config.transport;
} else if (config.maxRedirects === 0) {
transport = isHttpsProxy ? https : http;
} else {
if (config.maxRedirects) {
options.maxRedirects = config.maxRedirects;
}
if (config.beforeRedirect) {
options.beforeRedirect = config.beforeRedirect;
}
transport = isHttpsProxy ? httpsFollow : httpFollow;
}
if (config.maxBodyLength > -1) {
options.maxBodyLength = config.maxBodyLength;
}
if (config.insecureHTTPParser) {
options.insecureHTTPParser = config.insecureHTTPParser;
}
// Create the request
var req = transport.request(options, function handleResponse(res) {
if (req.aborted) return;
// uncompress the response body transparently if required
var stream = res;
// return the last request in case of redirects
var lastRequest = res.req || req;
// if no content, is HEAD request or decompress disabled we should not decompress
if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {
switch (res.headers['content-encoding']) {
/*eslint default-case:0*/
case 'gzip':
case 'compress':
case 'deflate':
// add the unzipper to the body stream processing pipeline
stream = stream.pipe(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
}
}
var response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
config: config,
request: lastRequest
};
if (config.responseType === 'stream') {
response.data = stream;
settle(resolve, reject, response);
} else {
var responseBuffer = [];
var totalResponseBytes = 0;
stream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
totalResponseBytes += chunk.length;
// make sure the content length is not over the maxContentLength if specified
if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
// stream.destoy() emit aborted event before calling reject() on Node.js v16
rejected = true;
stream.destroy();
reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
}
});
stream.on('aborted', function handlerStreamAborted() {
if (rejected) {
return;
}
stream.destroy();
reject(new AxiosError(
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
lastRequest
));
});
stream.on('error', function handleStreamError(err) {
if (req.aborted) return;
reject(AxiosError.from(err, null, config, lastRequest));
});
stream.on('end', function handleStreamEnd() {
try {
var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
if (config.responseType !== 'arraybuffer') {
responseData = responseData.toString(config.responseEncoding);
if (!config.responseEncoding || config.responseEncoding === 'utf8') {
responseData = utils.stripBOM(responseData);
}
}
response.data = responseData;
} catch (err) {
reject(AxiosError.from(err, null, config, response.request, response));
}
settle(resolve, reject, response);
});
}
});
// Handle errors
req.on('error', function handleRequestError(err) {
// @todo remove
// if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
reject(AxiosError.from(err, null, config, req));
});
// set tcp keep alive to prevent drop connection by peer
req.on('socket', function handleRequestSocket(socket) {
// default interval of sending ack packet is 1 minute
socket.setKeepAlive(true, 1000 * 60);
});
// Handle request timeout
if (config.timeout) {
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
var timeout = parseInt(config.timeout, 10);
if (isNaN(timeout)) {
reject(new AxiosError(
'error trying to parse `config.timeout` to int',
AxiosError.ERR_BAD_OPTION_VALUE,
config,
req
));
return;
}
// Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
// And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
// At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
// And then these socket which be hang up will devoring CPU little by little.
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
req.setTimeout(timeout, function handleRequestTimeout() {
req.abort();
var transitional = config.transitional || transitionalDefaults;
reject(new AxiosError(
'timeout of ' + timeout + 'ms exceeded',
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
req
));
});
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
if (req.aborted) return;
req.abort();
reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
// Send the request
if (utils.isStream(data)) {
data.on('error', function handleStreamError(err) {
reject(AxiosError.from(err, config, null, req));
}).pipe(req);
} else {
req.end(data);
}
});
};

View File

@ -1,222 +0,0 @@
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var cookies = require('./../helpers/cookies');
var buildURL = require('./../helpers/buildURL');
var buildFullPath = require('../core/buildFullPath');
var parseHeaders = require('./../helpers/parseHeaders');
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
var transitionalDefaults = require('../defaults/transitional');
var AxiosError = require('../core/AxiosError');
var CanceledError = require('../cancel/CanceledError');
var parseProtocol = require('../helpers/parseProtocol');
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
var onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = config.responseType;
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
if (!request) {
return;
}
reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);
request.abort();
request = null;
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
if (!requestData) {
requestData = null;
}
var protocol = parseProtocol(fullPath);
if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
return;
}
// Send the request
request.send(requestData);
});
};

View File

@ -1,64 +0,0 @@
'use strict';
var utils = require('./utils');
var bind = require('./helpers/bind');
var Axios = require('./core/Axios');
var mergeConfig = require('./core/mergeConfig');
var defaults = require('./defaults');
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = require('./cancel/CanceledError');
axios.CancelToken = require('./cancel/CancelToken');
axios.isCancel = require('./cancel/isCancel');
axios.VERSION = require('./env/data').version;
axios.toFormData = require('./helpers/toFormData');
// Expose AxiosError class
axios.AxiosError = require('../lib/core/AxiosError');
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = require('./helpers/spread');
// Expose isAxiosError
axios.isAxiosError = require('./helpers/isAxiosError');
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;

View File

@ -1,119 +0,0 @@
'use strict';
var CanceledError = require('./CanceledError');
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
// eslint-disable-next-line func-names
this.promise.then(function(cancel) {
if (!token._listeners) return;
var i;
var l = token._listeners.length;
for (i = 0; i < l; i++) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = function(onfulfilled) {
var _resolve;
// eslint-disable-next-line func-names
var promise = new Promise(function(resolve) {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Subscribe to the cancel signal
*/
CancelToken.prototype.subscribe = function subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
};
/**
* Unsubscribe from the cancel signal
*/
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
if (!this._listeners) {
return;
}
var index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;

View File

@ -1,22 +0,0 @@
'use strict';
var AxiosError = require('../core/AxiosError');
var utils = require('../utils');
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function CanceledError(message) {
// eslint-disable-next-line no-eq-null,eqeqeq
AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED);
this.name = 'CanceledError';
}
utils.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
module.exports = CanceledError;

View File

@ -1,5 +0,0 @@
'use strict';
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};

View File

@ -1,160 +0,0 @@
'use strict';
var utils = require('./../utils');
var buildURL = require('../helpers/buildURL');
var InterceptorManager = require('./InterceptorManager');
var dispatchRequest = require('./dispatchRequest');
var mergeConfig = require('./mergeConfig');
var buildFullPath = require('./buildFullPath');
var validator = require('../helpers/validator');
var validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
var transitional = config.transitional;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
var promise;
if (!synchronousRequestInterceptors) {
var chain = [dispatchRequest, undefined];
Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain = chain.concat(responseInterceptorChain);
promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
var newConfig = config;
while (requestInterceptorChain.length) {
var onFulfilled = requestInterceptorChain.shift();
var onRejected = requestInterceptorChain.shift();
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected(error);
break;
}
}
try {
promise = dispatchRequest(newConfig);
} catch (error) {
return Promise.reject(error);
}
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
var fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: (config || {}).data
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method: method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url: url,
data: data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});
module.exports = Axios;

View File

@ -1,86 +0,0 @@
'use strict';
var utils = require('../utils');
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
function AxiosError(message, code, config, request, response) {
Error.call(this);
this.message = message;
this.name = 'AxiosError';
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
response && (this.response = response);
}
utils.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
}
});
var prototype = AxiosError.prototype;
var descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
'ERR_BAD_OPTION',
'ECONNABORTED',
'ETIMEDOUT',
'ERR_NETWORK',
'ERR_FR_TOO_MANY_REDIRECTS',
'ERR_DEPRECATED',
'ERR_BAD_RESPONSE',
'ERR_BAD_REQUEST',
'ERR_CANCELED'
// eslint-disable-next-line func-names
].forEach(function(code) {
descriptors[code] = {value: code};
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype, 'isAxiosError', {value: true});
// eslint-disable-next-line func-names
AxiosError.from = function(error, code, config, request, response, customProps) {
var axiosError = Object.create(prototype);
utils.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
});
AxiosError.call(axiosError, error.message, code, config, request, response);
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
module.exports = AxiosError;

View File

@ -1,54 +0,0 @@
'use strict';
var utils = require('./../utils');
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;

View File

@ -1,8 +0,0 @@
# axios // core
The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are:
- Dispatching requests
- Requests sent via `adapters/` (see lib/adapters/README.md)
- Managing interceptors
- Handling config

View File

@ -1,20 +0,0 @@
'use strict';
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};

View File

@ -1,87 +0,0 @@
'use strict';
var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');
var CanceledError = require('../cancel/CanceledError');
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};

View File

@ -1,100 +0,0 @@
'use strict';
var utils = require('../utils');
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(prop) {
if (prop in config2) {
return getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
return getMergedValue(undefined, config1[prop]);
}
}
var mergeMap = {
'url': valueFromConfig2,
'method': valueFromConfig2,
'data': valueFromConfig2,
'baseURL': defaultToConfig2,
'transformRequest': defaultToConfig2,
'transformResponse': defaultToConfig2,
'paramsSerializer': defaultToConfig2,
'timeout': defaultToConfig2,
'timeoutMessage': defaultToConfig2,
'withCredentials': defaultToConfig2,
'adapter': defaultToConfig2,
'responseType': defaultToConfig2,
'xsrfCookieName': defaultToConfig2,
'xsrfHeaderName': defaultToConfig2,
'onUploadProgress': defaultToConfig2,
'onDownloadProgress': defaultToConfig2,
'decompress': defaultToConfig2,
'maxContentLength': defaultToConfig2,
'maxBodyLength': defaultToConfig2,
'beforeRedirect': defaultToConfig2,
'transport': defaultToConfig2,
'httpAgent': defaultToConfig2,
'httpsAgent': defaultToConfig2,
'cancelToken': defaultToConfig2,
'socketPath': defaultToConfig2,
'responseEncoding': defaultToConfig2,
'validateStatus': mergeDirectKeys
};
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
var merge = mergeMap[prop] || mergeDeepProperties;
var configValue = merge(prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
};

View File

@ -1,25 +0,0 @@
'use strict';
var AxiosError = require('./AxiosError');
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
'Request failed with status code ' + response.status,
[AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
response.request,
response
));
}
};

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