Compare commits

..

No commits in common. '09c327ec698dd6f6e5abd168e7f7035fc0de67f1' and '7dd9f5d0b5ee9e454486b1cdb0788f034408d266' have entirely different histories.

  1. 20
      docker-compose.yml
  2. 8
      frontend/src/App.js
  3. 1005
      frontend/src/setupProxy.js
  4. 1
      server/.dockerignore
  5. 98
      server/Dockerfile
  6. 89
      server/Dockerfile_old
  7. 41
      server/app.js
  8. BIN
      server/files/JPOrbsP4S.png
  9. BIN
      server/files/SigTerm.txt
  10. 1
      server/files/leaderboard
  11. 1
      server/files/leaderboardinfo
  12. 1
      server/files/leaderboardinfo.1
  13. 72
      server/node_modules/assert-options/README.md
  14. 33
      server/node_modules/assert-options/dist/index.js
  15. 4
      server/node_modules/assert-options/dist/src/index.d.ts
  16. 34
      server/node_modules/assert-options/dist/src/index.js
  17. 76
      server/node_modules/assert-options/package.json
  18. 278
      server/node_modules/axios/CHANGELOG.md
  19. 0
      server/node_modules/axios/LICENSE
  20. 129
      server/node_modules/axios/README.md
  21. 2
      server/node_modules/axios/UPGRADE_GUIDE.md
  22. 321
      server/node_modules/axios/dist/axios.js
  23. 2
      server/node_modules/axios/dist/axios.map
  24. 4
      server/node_modules/axios/dist/axios.min.js
  25. 2
      server/node_modules/axios/dist/axios.min.map
  26. 22
      server/node_modules/axios/index.d.ts
  27. 0
      server/node_modules/axios/index.js
  28. 0
      server/node_modules/axios/lib/adapters/README.md
  29. 78
      server/node_modules/axios/lib/adapters/http.js
  30. 7
      server/node_modules/axios/lib/adapters/xhr.js
  31. 3
      server/node_modules/axios/lib/axios.js
  32. 0
      server/node_modules/axios/lib/cancel/Cancel.js
  33. 0
      server/node_modules/axios/lib/cancel/CancelToken.js
  34. 0
      server/node_modules/axios/lib/cancel/isCancel.js
  35. 7
      server/node_modules/axios/lib/core/Axios.js
  36. 0
      server/node_modules/axios/lib/core/InterceptorManager.js
  37. 0
      server/node_modules/axios/lib/core/README.md
  38. 0
      server/node_modules/axios/lib/core/buildFullPath.js
  39. 0
      server/node_modules/axios/lib/core/createError.js
  40. 0
      server/node_modules/axios/lib/core/dispatchRequest.js
  41. 2
      server/node_modules/axios/lib/core/enhanceError.js
  42. 78
      server/node_modules/axios/lib/core/mergeConfig.js
  43. 2
      server/node_modules/axios/lib/core/settle.js
  44. 0
      server/node_modules/axios/lib/core/transformData.js
  45. 1
      server/node_modules/axios/lib/defaults.js
  46. 0
      server/node_modules/axios/lib/helpers/README.md
  47. 0
      server/node_modules/axios/lib/helpers/bind.js
  48. 1
      server/node_modules/axios/lib/helpers/buildURL.js
  49. 0
      server/node_modules/axios/lib/helpers/combineURLs.js
  50. 0
      server/node_modules/axios/lib/helpers/cookies.js
  51. 0
      server/node_modules/axios/lib/helpers/deprecatedMethod.js
  52. 0
      server/node_modules/axios/lib/helpers/isAbsoluteURL.js
  53. 11
      server/node_modules/axios/lib/helpers/isAxiosError.js
  54. 0
      server/node_modules/axios/lib/helpers/isURLSameOrigin.js
  55. 0
      server/node_modules/axios/lib/helpers/normalizeHeaderName.js
  56. 0
      server/node_modules/axios/lib/helpers/parseHeaders.js
  57. 0
      server/node_modules/axios/lib/helpers/spread.js
  58. 65
      server/node_modules/axios/lib/utils.js
  59. 18
      server/node_modules/axios/node_modules/follow-redirects/LICENSE
  60. 148
      server/node_modules/axios/node_modules/follow-redirects/README.md
  61. 14
      server/node_modules/axios/node_modules/follow-redirects/debug.js
  62. 1
      server/node_modules/axios/node_modules/follow-redirects/http.js
  63. 1
      server/node_modules/axios/node_modules/follow-redirects/https.js
  64. 504
      server/node_modules/axios/node_modules/follow-redirects/index.js
  65. 98
      server/node_modules/axios/node_modules/follow-redirects/package.json
  66. 34
      server/node_modules/axios/package.json
  67. 2
      server/node_modules/bluebird/LICENSE
  68. 10
      server/node_modules/bluebird/README.md
  69. 0
      server/node_modules/bluebird/changelog.md
  70. 475
      server/node_modules/bluebird/js/browser/bluebird.core.js
  71. 8
      server/node_modules/bluebird/js/browser/bluebird.core.min.js
  72. 527
      server/node_modules/bluebird/js/browser/bluebird.js
  73. 10
      server/node_modules/bluebird/js/browser/bluebird.min.js
  74. 0
      server/node_modules/bluebird/js/release/any.js
  75. 0
      server/node_modules/bluebird/js/release/assert.js
  76. 71
      server/node_modules/bluebird/js/release/async.js
  77. 0
      server/node_modules/bluebird/js/release/bind.js
  78. 0
      server/node_modules/bluebird/js/release/bluebird.js
  79. 0
      server/node_modules/bluebird/js/release/call_get.js
  80. 0
      server/node_modules/bluebird/js/release/cancel.js
  81. 0
      server/node_modules/bluebird/js/release/catch_filter.js
  82. 0
      server/node_modules/bluebird/js/release/context.js
  83. 143
      server/node_modules/bluebird/js/release/debuggability.js
  84. 0
      server/node_modules/bluebird/js/release/direct_resolve.js
  85. 0
      server/node_modules/bluebird/js/release/each.js
  86. 0
      server/node_modules/bluebird/js/release/errors.js
  87. 0
      server/node_modules/bluebird/js/release/es5.js
  88. 0
      server/node_modules/bluebird/js/release/filter.js
  89. 39
      server/node_modules/bluebird/js/release/finally.js
  90. 2
      server/node_modules/bluebird/js/release/generators.js
  91. 11
      server/node_modules/bluebird/js/release/join.js
  92. 13
      server/node_modules/bluebird/js/release/map.js
  93. 0
      server/node_modules/bluebird/js/release/method.js
  94. 0
      server/node_modules/bluebird/js/release/nodeback.js
  95. 0
      server/node_modules/bluebird/js/release/nodeify.js
  96. 132
      server/node_modules/bluebird/js/release/promise.js
  97. 2
      server/node_modules/bluebird/js/release/promise_array.js
  98. 0
      server/node_modules/bluebird/js/release/promisify.js
  99. 2
      server/node_modules/bluebird/js/release/props.js
  100. 0
      server/node_modules/bluebird/js/release/queue.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -24,7 +24,7 @@ services:
depends_on: depends_on:
- postgres - postgres
ports: ports:
- "443:443" - "4504:4504"
working_dir: /server2 working_dir: /server2
volumes: volumes:
- ./server2:/server2 - ./server2:/server2
@ -51,6 +51,20 @@ services:
max-size: "1m" max-size: "1m"
max-file: "3" max-file: "3"
imgparser:
build: imgparser
restart: always
ports:
- "4503:4503"
volumes:
- ./imgparser:/imgparser
working_dir: /imgparser/projectDivaImgParser
logging:
options:
max-size: "1m"
max-file: "3"
postgres: postgres:
image: postgres:10.4 image: postgres:10.4
restart: always restart: always
@ -76,7 +90,7 @@ services:
- postgres - postgres
- server - server
ports: ports:
- "4500:3000" - "80:3000"
environment: environment:
- CHOKIDAR_USEPOLLING=true - CHOKIDAR_USEPOLLING=true
stdin_open: true stdin_open: true
@ -121,4 +135,4 @@ services:
# context: frontend # context: frontend
# dockerfile: Dockerfile.prod # dockerfile: Dockerfile.prod
# ports: # ports:
# - '3004:80' # - '3004:80'

@ -842,7 +842,7 @@ function BestPlaysPanel(p) {
var [update,setUpdate] = useState(false) var [update,setUpdate] = useState(false)
useEffect(()=>{ useEffect(()=>{
axios.get("http://projectdivar.com/bestplays/"+p.username+"?fails=false&limit=5&offset=0") axios.get("http://www.projectdivar.com/bestplays/"+p.username+"?fails=false&limit=5&offset=0")
.then((data)=>{setBestPlays(data.data);}) .then((data)=>{setBestPlays(data.data);})
},[p.profileUpdate,update,p.username]) },[p.profileUpdate,update,p.username])
@ -851,7 +851,7 @@ function BestPlaysPanel(p) {
{bestPlays.map((play,i)=>{return <li key={i} className={"list-group-item list-group-item-action "+(i%2==0?"background-list-1":"background-list-2")}> {bestPlays.map((play,i)=>{return <li key={i} className={"list-group-item list-group-item-action "+(i%2==0?"background-list-1":"background-list-2")}>
<Play setModalSrc={p.setModalSrc} setModalVisible={p.setModalVisible} index={i} play={play} song={p.songs[play.songid]}/> <Play setModalSrc={p.setModalSrc} setModalVisible={p.setModalVisible} index={i} play={play} song={p.songs[play.songid]}/>
</li>})} </li>})}
<LoadMore username={p.username} profileUpdate={p.profileUpdate} listItem={true} url={"http://projectdivar.com/bestplays/"+p.username} params={{fails:false,limit:15,offset:5}} value={bestPlays} setValue={setBestPlays}/> <LoadMore username={p.username} profileUpdate={p.profileUpdate} listItem={true} url={"http://www.projectdivar.com/bestplays/"+p.username} params={{fails:false,limit:15,offset:5}} value={bestPlays} setValue={setBestPlays}/>
</ul> </ul>
</div> </div>
@ -948,7 +948,7 @@ function PlayData(p) {
<h5>Individual Plays for {p.song.name} from {p.username}</h5> <h5>Individual Plays for {p.song.name} from {p.username}</h5>
<div className="border rounded"> <div className="border rounded">
{data.map((play,i)=><Play setModalSrc={p.setModalSrc} setModalVisible={p.setModalVisible} key={i} play={play} mini={true} song={p.song}/>)} {data.map((play,i)=><Play setModalSrc={p.setModalSrc} setModalVisible={p.setModalVisible} key={i} play={play} mini={true} song={p.song}/>)}
<LoadMore profileUpdate={p.profileUpdate} username={p.username} url={"http://projectdivar.com/plays/"+p.username+"/"+p.song.id} params={{limit:15,offset:5}} value={data} setValue={setData}/> <LoadMore profileUpdate={p.profileUpdate} username={p.username} url={"http://www.projectdivar.com/plays/"+p.username+"/"+p.song.id} params={{limit:15,offset:5}} value={data} setValue={setData}/>
</div> </div>
</div> </div>
</> </>
@ -2407,7 +2407,7 @@ function Website() {
const [userSettings,setUserSettings] = useState({}) const [userSettings,setUserSettings] = useState({})
useEffect(()=>{ useEffect(()=>{
axios.get("http://.projectdivar.com/songs") axios.get("http://www.projectdivar.com/songs")
.then((data)=>{ .then((data)=>{
setSongs(data.data) setSongs(data.data)
}) })

File diff suppressed because it is too large Load Diff

@ -1 +0,0 @@
/node_modules

@ -1,37 +1,89 @@
from node:16-alpine FROM phusion/baseimage:bionic-1.0.0
RUN apk update CMD ["/sbin/my_init"]
RUN apk add --no-cache \ ENV JAVA_MAJOR_VERSION=11
sudo \
curl \
build-base \
g++ \
libpng \
libpng-dev \
jpeg-dev \
pango-dev \
cairo-dev \
giflib-dev \
python3
RUN apk add --no-cache tini RUN mkdir -p /src/app
RUN apt-get update \
&& apt-get install -y --no-install-recommends tzdata curl ca-certificates fontconfig locales \
&& echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen \
&& locale-gen en_US.UTF-8 \
&& rm -rf /var/lib/apt/lists/*
RUN apk add ffmpeg ENV JAVA_VERSION jdk-11.0.8+10
RUN yarn global add nodemon RUN set -eux; \
ARCH="$(dpkg --print-architecture)"; \
case "${ARCH}" in \
aarch64|arm64) \
ESUM='286c869dbaefda9b470ae71d1250fdecf9f06d8da97c0f7df9021d381d749106'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_aarch64_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
armhf|armv7l) \
ESUM='ffa627b2d0c6001448bb8f1f24f7c9921dad37e67637f6ed0a9a479e680a3393'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_arm_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
ppc64el|ppc64le) \
ESUM='89231e1667d7cc4202d1a401497bb287d4eb12281c90c17e2570211cc4e901a3'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_ppc64le_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
s390x) \
ESUM='dc0e715c17abcb12bedf77c638e58e67d828d3c4bf24a898f0d4b053caaeb25f'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_s390x_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
amd64|x86_64) \
ESUM='98615b1b369509965a612232622d39b5cefe117d6189179cbad4dcef2ee2f4e1'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_x64_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
*) \
echo "Unsupported arch: ${ARCH}"; \
exit 1; \
;; \
esac; \
curl -LfsSo /tmp/openjdk.tar.gz ${BINARY_URL}; \
echo "${ESUM} */tmp/openjdk.tar.gz" | sha256sum -c -; \
mkdir -p /opt/java/openjdk; \
cd /opt/java/openjdk; \
tar -xf /tmp/openjdk.tar.gz --strip-components=1; \
rm -rf /tmp/openjdk.tar.gz;
WORKDIR /src/app ENV JAVA_HOME=/opt/java/openjdk \
PATH="/opt/java/openjdk/bin:$PATH"
RUN apt-get update && \
apt-get install -y ffmpeg && \
apt-get clean;
COPY ./package.json ./package-lock.json /src/app/ RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && \
apt-get install -y yarn;
RUN npm install
WORKDIR /src/app
COPY . /src/app COPY . /src/app
EXPOSE 3005 RUN yarn global add nodemon
# update
RUN apt-get update
# install curl
RUN apt-get install -y curl
# get install script and pass it to execute:
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash
# and install node
RUN apt-get install -y nodejs
# confirm that it was successful
RUN node -v
# npm installs automatically
RUN npm -v
ENTRYPOINT ["/sbin/tini", "--"] ENV TINI_VERSION v0.19.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini
RUN chmod +x /tini
ENTRYPOINT ["/tini", "--"]
CMD [ "nodemon", "app.js" ] EXPOSE 3005
CMD [ "nodemon", "app.js" ]

@ -1,89 +0,0 @@
FROM phusion/baseimage:bionic-1.0.0
CMD ["/sbin/my_init"]
ENV JAVA_MAJOR_VERSION=11
RUN mkdir -p /src/app
RUN apt-get update \
&& apt-get install -y --no-install-recommends tzdata curl ca-certificates fontconfig locales \
&& echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen \
&& locale-gen en_US.UTF-8 \
&& rm -rf /var/lib/apt/lists/*
ENV JAVA_VERSION jdk-11.0.8+10
RUN set -eux; \
ARCH="$(dpkg --print-architecture)"; \
case "${ARCH}" in \
aarch64|arm64) \
ESUM='286c869dbaefda9b470ae71d1250fdecf9f06d8da97c0f7df9021d381d749106'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_aarch64_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
armhf|armv7l) \
ESUM='ffa627b2d0c6001448bb8f1f24f7c9921dad37e67637f6ed0a9a479e680a3393'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_arm_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
ppc64el|ppc64le) \
ESUM='89231e1667d7cc4202d1a401497bb287d4eb12281c90c17e2570211cc4e901a3'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_ppc64le_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
s390x) \
ESUM='dc0e715c17abcb12bedf77c638e58e67d828d3c4bf24a898f0d4b053caaeb25f'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_s390x_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
amd64|x86_64) \
ESUM='98615b1b369509965a612232622d39b5cefe117d6189179cbad4dcef2ee2f4e1'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_x64_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
*) \
echo "Unsupported arch: ${ARCH}"; \
exit 1; \
;; \
esac; \
curl -LfsSo /tmp/openjdk.tar.gz ${BINARY_URL}; \
echo "${ESUM} */tmp/openjdk.tar.gz" | sha256sum -c -; \
mkdir -p /opt/java/openjdk; \
cd /opt/java/openjdk; \
tar -xf /tmp/openjdk.tar.gz --strip-components=1; \
rm -rf /tmp/openjdk.tar.gz;
ENV JAVA_HOME=/opt/java/openjdk \
PATH="/opt/java/openjdk/bin:$PATH"
RUN apt-get update && \
apt-get install -y ffmpeg && \
apt-get clean;
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && \
apt-get install -y yarn;
WORKDIR /src/app
COPY . /src/app
RUN yarn global add nodemon
# update
RUN apt-get update
# install curl
RUN apt-get install -y curl
# get install script and pass it to execute:
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash
# and install node
RUN apt-get install -y nodejs
# confirm that it was successful
RUN node -v
# npm installs automatically
RUN npm -v
ENV TINI_VERSION v0.19.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini
RUN chmod +x /tini
ENTRYPOINT ["/tini", "--"]
EXPOSE 3005
CMD [ "nodemon", "app.js" ]

@ -6,13 +6,12 @@ const app = express();
const port = 4501; const port = 4501;
const { json, urlencoded } = require("body-parser"); const { json, urlencoded } = require("body-parser");
const Pool = require("pg").Pool; const Pool = require("pg").Pool;
app.use(json({limit:"300kb"})); app.use(json());
app.use( app.use(
urlencoded({ urlencoded({
extended: true, extended: true,
}) })
); );
app.use(express.json({limit:"300kb"}))
const nodemailer = require("nodemailer"); const nodemailer = require("nodemailer");
const fileUpload = require("express-fileupload"); const fileUpload = require("express-fileupload");
const unzipper = require("unzipper"); const unzipper = require("unzipper");
@ -55,8 +54,12 @@ const db2 = new Pool({
port: 5432, port: 5432,
}); });
app.use((req, _, next) => {
req.db = db;
next()
})
exports.app = app; exports.app = app;
exports.db = db;
require("./routes/d4dj-routes"); require("./routes/d4dj-routes");
@ -2731,31 +2734,6 @@ app.post("/cans", function (req, res) {
} }
}); });
inventoryData=[]
inventoryLastUpdate = new Date().getTime();
app.post("/inventoryData",(req,res)=>{
if (req.body){
inventoryData=req.body
inventoryLastUpdate=new Date().getTime();
res.status(200).send("Done!");
} else {
res.status(400).send("Invalid credentials!");
}
});
app.get("/inventoryData",(req,res)=>{
if (req.query.lastUpdate){
if (req.query.lastUpdate>inventoryLastUpdate){
res.status(200).send("")
} else {
res.status(200).json(inventoryData)
}
} else {
res.status(200).json(inventoryData)
}
})
app.post("/streamkill/:id", function (req, res) { app.post("/streamkill/:id", function (req, res) {
if (req.body && req.body.username && req.body.authentication_token) { if (req.body && req.body.username && req.body.authentication_token) {
GetUserLoginAllowed( GetUserLoginAllowed(
@ -2885,12 +2863,9 @@ function Process(data, ind) {
app.use( app.use(
"/files", "/files",
express.static("files" express.static("files", {
/*,
{
maxAge: 86400000 * 30, maxAge: 86400000 * 30,
}*/ })
)
); );
/* /*

Binary file not shown.

Before

Width:  |  Height:  |  Size: 690 KiB

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -1,72 +0,0 @@
# assert-options
Smart `options` handling, with one line of code:
* throw detailed error on invalid options
* set default values for missing options
Strongly-typed, built with TypeScript 4.x `strict` mode, for JavaScript clients.
[![Build Status](https://travis-ci.org/vitaly-t/assert-options.svg?branch=master)](https://travis-ci.org/vitaly-t/assert-options)
[![Coverage Status](https://coveralls.io/repos/vitaly-t/assert-options/badge.svg?branch=master)](https://coveralls.io/r/vitaly-t/assert-options?branch=master)
## Rationale
* Passing in invalid or misspelled option names is one of the most common errors in JavaScript.
* Assigning defaults is the most common operation for methods that take options.
This module automates proper options handling - parsing and setting defaults where needed.
Although this library is implemented in TypeScript, its objective is mainly to help JavaScript clients,
because TypeScript itself can handle invalid options and defaults natively.
## Installation
```
$ npm i assert-options
```
## Usage
```js
const { assertOptions } = require('assert-options');
function functionWithOptions(options) {
options = assertOptions(options, {first: 123, second: null});
// options is a safe object here, with all missing defaults set.
}
```
When default values are not needed, you can just use an array of strings:
```js
function functionWithOptions(options) {
options = assertOptions(options, ['first', 'second']);
// the result is exactly the same as using the following:
// options = assertOptions(options, {first: undefined, second: undefined});
// options is a safe object here, without defaults.
}
```
## API
### `assertOptions(options, defaults) => {}`
* When `options` is `null`/`undefined`, new `{}` is returned, applying `defaults` as specified.
* When `options` contains an unknown property, [Error] `Option "name" is not recognized.` is thrown.
* When a property in `options` is missing or `undefined`, its value is set from the `defaults`,
provided it is available and its value is not `undefined`.
* When `options` is not `null`/`undefined`, it must be of type `object`, or else [TypeError] is thrown:
`Invalid "options" parameter: value`.
* Parameter `defaults` is required, as a non-`null` object or an array of strings, or else [TypeError]
is thrown: `Invalid "defaults" parameter: value`.
[Error]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
[TypeError]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError

@ -1,33 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function assertOptions(options, defaults) {
if (options !== null && options !== undefined && typeof options !== 'object') {
throw new TypeError('Invalid "options" parameter: ' + JSON.stringify(options));
}
var isArray = Array.isArray(defaults);
if (!isArray && (!defaults || typeof defaults !== 'object')) {
throw new TypeError('Invalid "defaults" parameter: ' + JSON.stringify(defaults));
}
if (options) {
for (var _i = 0, _a = Object.keys(options); _i < _a.length; _i++) {
var a = _a[_i];
if ((isArray && defaults.indexOf(a) === -1) || (!isArray && !(a in defaults))) {
throw new Error('Option "' + a + '" is not recognized.');
}
}
}
else {
options = {};
}
if (!isArray) {
var defs = defaults;
for (var _b = 0, _c = Object.keys(defs); _b < _c.length; _b++) {
var d = _c[_b];
if (options[d] === undefined && defs[d] !== undefined) {
options[d] = defs[d];
}
}
}
return options;
}
exports.assertOptions = assertOptions;

@ -1,4 +0,0 @@
export declare type NamedValues = {
[name: string]: any;
};
export declare function assertOptions(options: NamedValues | null | undefined, defaults: NamedValues | string[]): NamedValues;

@ -1,34 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertOptions = void 0;
function assertOptions(options, defaults) {
if (options !== null && options !== undefined && typeof options !== 'object') {
throw new TypeError('Invalid "options" parameter: ' + JSON.stringify(options));
}
var isArray = Array.isArray(defaults);
if (!isArray && (!defaults || typeof defaults !== 'object')) {
throw new TypeError('Invalid "defaults" parameter: ' + JSON.stringify(defaults));
}
if (options) {
for (var _i = 0, _a = Object.keys(options); _i < _a.length; _i++) {
var a = _a[_i];
if ((isArray && defaults.indexOf(a) === -1) || (!isArray && !(a in defaults))) {
throw new Error('Option "' + a + '" is not recognized.');
}
}
}
else {
options = {};
}
if (!isArray) {
var defs = defaults;
for (var _b = 0, _c = Object.keys(defs); _b < _c.length; _b++) {
var d = _c[_b];
if (options[d] === undefined && defs[d] !== undefined) {
options[d] = defs[d];
}
}
}
return options;
}
exports.assertOptions = assertOptions;

@ -1,76 +0,0 @@
{
"_from": "assert-options@0.7.0",
"_id": "assert-options@0.7.0",
"_inBundle": false,
"_integrity": "sha512-7q9uNH/Dh8gFgpIIb9ja8PJEWA5AQy3xnBC8jtKs8K/gNVCr1K6kIvlm59HUyYgvM7oEDoLzGgPcGd9FqhtXEQ==",
"_location": "/assert-options",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "assert-options@0.7.0",
"name": "assert-options",
"escapedName": "assert-options",
"rawSpec": "0.7.0",
"saveSpec": null,
"fetchSpec": "0.7.0"
},
"_requiredBy": [
"/pg-promise"
],
"_resolved": "https://registry.npmjs.org/assert-options/-/assert-options-0.7.0.tgz",
"_shasum": "82c27618d9c0baa5e9da8ef607ee261a44ed6e5e",
"_spec": "assert-options@0.7.0",
"_where": "/home/sigonasr2/divar/server/node_modules/pg-promise",
"author": {
"name": "Vitaly Tomilov",
"email": "vitaly.tomilov@gmail.com"
},
"bugs": {
"url": "https://github.com/vitaly-t/assert-options/issues",
"email": "vitaly.tomilov@gmail.com"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Generic options parameter handling.",
"devDependencies": {
"@types/chai": "4.2.14",
"@types/mocha": "8.2.0",
"@types/node": "14.14.14",
"chai": "4.2.0",
"coveralls": "3.1.0",
"mocha": "8.2.1",
"mocha-lcov-reporter": "1.3.0",
"nyc": "15.1.0",
"ts-node": "9.1.1",
"tslint": "6.1.3",
"typescript": "4.1.3"
},
"engines": {
"node": ">=8.0.0"
},
"files": [
"dist/src",
"dist/index.js"
],
"homepage": "https://github.com/vitaly-t/assert-options",
"keywords": [
"assert",
"options"
],
"license": "MIT",
"main": "dist/src/index.js",
"name": "assert-options",
"repository": {
"type": "git",
"url": "git+https://github.com/vitaly-t/assert-options.git"
},
"scripts": {
"all": "tsc && npm test && npm run lint",
"lint": "tslint --fix ./src/**/*.ts ./test/**/*.ts",
"test": "nyc mocha -r ts-node/register test/**/*.spec.ts",
"travis": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
},
"types": "dist/src/index.d.ts",
"version": "0.7.0"
}

@ -1,277 +1,5 @@
# Changelog # Changelog
### 0.21.1 (December 21, 2020)
Fixes and Functionality:
- Hotfix: Prevent SSRF (#3410)
- Protocol not parsed when setting proxy config from env vars (#3070)
- Updating axios in types to be lower case (#2797)
- Adding a type guard for `AxiosError` (#2949)
Internal and Tests:
- Remove the skipping of the `socket` http test (#3364)
- Use different socket for Win32 test (#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, existant -> 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 Asyc 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) ### 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) - Remove unnecessary XSS check ([#2679](https://github.com/axios/axios/pull/2679)) (see ([#2646](https://github.com/axios/axios/issues/2646)) for discussion)
@ -297,7 +25,7 @@ Fixes and Functionality:
- Add error toJSON example ([#2466](https://github.com/axios/axios/pull/2466)) - 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 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)) - 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)) - 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)) - 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)) - 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)) - Alternative syntax to send data into the body ([#2317](https://github.com/axios/axios/pull/2317))
@ -329,7 +57,7 @@ Documentation:
- Update response interceptor docs ([#2399](https://github.com/axios/axios/pull/2399)) - Update response interceptor docs ([#2399](https://github.com/axios/axios/pull/2399))
- Update README.md ([#2504](https://github.com/axios/axios/pull/2504)) - 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)) - 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)) - upadating 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)) - 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)) - Doc fixes, minor examples cleanup ([#2198](https://github.com/axios/axios/pull/2198))
@ -382,7 +110,7 @@ New Functionality:
- Add getUri method ([#1712](https://github.com/axios/axios/issues/1712)) - 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 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 toJSON to decorated Axios errors to faciliate serialization ([#1625](https://github.com/axios/axios/issues/1625))
- Add second then on axios call ([#1623](https://github.com/axios/axios/issues/1623)) - Add second then on axios call ([#1623](https://github.com/axios/axios/issues/1623))
- Typings: allow custom return types - Typings: allow custom return types
- Add option to specify character set in responses (with http adapter) - Add option to specify character set in responses (with http adapter)

129
server/node_modules/axios/README.md generated vendored

@ -1,7 +1,6 @@
# axios # axios
[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/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://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios) [![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios)
[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/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) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios)
@ -10,37 +9,6 @@
[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
Promise based HTTP client for the browser and node.js Promise based HTTP client for the browser and node.js
## Table of Contents
- [Features](#features)
- [Browser Support](#browser-support)
- [Installing](#installing)
- [Example](#example)
- [Axios API](#axios-api)
- [Request method aliases](#request-method-aliases)
- [Concurrency (Deprecated)](#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)
- [Handling Errors](#handling-errors)
- [Cancellation](#cancellation)
- [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)
- [Semver](#semver)
- [Promises](#promises)
- [TypeScript](#typescript)
- [Resources](#resources)
- [Credits](#credits)
- [License](#license)
## Features ## Features
@ -81,13 +49,7 @@ Using yarn:
$ yarn add axios $ yarn add axios
``` ```
Using jsDelivr CDN: Using cdn:
```html
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
```
Using unpkg CDN:
```html ```html
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
@ -119,7 +81,7 @@ axios.get('/user?ID=12345')
// handle error // handle error
console.log(error); console.log(error);
}) })
.then(function () { .finally(function () {
// always executed // always executed
}); });
@ -135,7 +97,7 @@ axios.get('/user', {
.catch(function (error) { .catch(function (error) {
console.log(error); console.log(error);
}) })
.then(function () { .finally(function () {
// always executed // always executed
}); });
@ -179,11 +141,10 @@ function getUserPermissions() {
return axios.get('/user/12345/permissions'); return axios.get('/user/12345/permissions');
} }
Promise.all([getUserAccount(), getUserPermissions()]) axios.all([getUserAccount(), getUserPermissions()])
.then(function (results) { .then(axios.spread(function (acct, perms) {
const acct = results[0]; // Both requests are now complete
const perm = results[1]; }));
});
``` ```
## axios API ## axios API
@ -205,7 +166,7 @@ axios({
``` ```
```js ```js
// GET request for remote image in node.js // GET request for remote image
axios({ axios({
method: 'get', method: 'get',
url: 'http://bit.ly/2mTM3nY', url: 'http://bit.ly/2mTM3nY',
@ -239,13 +200,12 @@ For convenience aliases have been provided for all supported request methods.
###### NOTE ###### NOTE
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
### Concurrency (Deprecated) ### Concurrency
Please use `Promise.all` to replace the below functions.
Helper functions for dealing with concurrent requests. Helper functions for dealing with concurrent requests.
axios.all(iterable) ##### axios.all(iterable)
axios.spread(callback) ##### axios.spread(callback)
### Creating an instance ### Creating an instance
@ -327,7 +287,7 @@ These are the available config options for making requests. Only the `url` is re
}, },
// `data` is the data to be sent as the request body // `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types: // When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob // - Browser only: FormData, File, Blob
@ -370,7 +330,7 @@ These are the available config options for making requests. Only the `url` is re
// browser only: 'blob' // browser only: 'blob'
responseType: 'json', // default responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses (Node.js only) // `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests // Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default responseEncoding: 'utf8', // default
@ -381,23 +341,18 @@ These are the available config options for making requests. Only the `url` is re
xsrfHeaderName: 'X-XSRF-TOKEN', // default xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` allows handling of progress events for uploads // `onUploadProgress` allows handling of progress events for uploads
// browser only
onUploadProgress: function (progressEvent) { onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event // Do whatever you want with the native progress event
}, },
// `onDownloadProgress` allows handling of progress events for downloads // `onDownloadProgress` allows handling of progress events for downloads
// browser only
onDownloadProgress: function (progressEvent) { onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event // 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` defines the max size of the http response content in bytes allowed
maxContentLength: 2000, 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 // `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` // 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 // or `undefined`), the promise will be resolved; otherwise, the promise will be
@ -422,7 +377,7 @@ These are the available config options for making requests. Only the `url` is re
httpAgent: new http.Agent({ keepAlive: true }), httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` defines the hostname, port, and protocol of the proxy server. // 'proxy' defines the hostname and port of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and // You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables // `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment // for your proxy configuration, you can also define a `no_proxy` environment
@ -432,9 +387,7 @@ These are the available config options for making requests. Only the `url` is re
// supplies credentials. // supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing // This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`. // `Proxy-Authorization` custom headers you have set using `headers`.
// If the proxy server uses HTTPS, then you must set the protocol to `https`.
proxy: { proxy: {
protocol: 'https',
host: '127.0.0.1', host: '127.0.0.1',
port: 9000, port: 9000,
auth: { auth: {
@ -446,14 +399,7 @@ These are the available config options for making requests. Only the `url` is re
// `cancelToken` specifies a cancel token that can be used to cancel the request // `cancelToken` specifies a cancel token that can be used to cancel the request
// (see Cancellation section below for details) // (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) { cancelToken: new CancelToken(function (cancel) {
}), })
// `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
} }
``` ```
@ -472,9 +418,8 @@ The response for a request contains the following information.
// `statusText` is the HTTP status message from the server response // `statusText` is the HTTP status message from the server response
statusText: 'OK', statusText: 'OK',
// `headers` the HTTP headers that the server responded with // `headers` the headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation. // All header names are lower cased
// Example: `response.headers['content-type']`
headers: {}, headers: {},
// `config` is the config that was provided to `axios` for the request // `config` is the config that was provided to `axios` for the request
@ -614,7 +559,7 @@ Using the `validateStatus` config option, you can define HTTP code(s) that shoul
```js ```js
axios.get('/user/12345', { axios.get('/user/12345', {
validateStatus: function (status) { validateStatus: function (status) {
return status < 500; // Resolve only if the status code is less than 500 return status < 500; // Reject only if the status code is greater than or equal to 500
} }
}) })
``` ```
@ -719,8 +664,6 @@ axios(options);
### Node.js ### Node.js
#### Query string
In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
```js ```js
@ -728,45 +671,11 @@ const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); 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. You can also use the [`qs`](https://github.com/ljharb/qs) library.
###### NOTE ###### NOTE
The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665). The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).
#### Form data
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, { headers: form.getHeaders() })
```
Alternatively, use an interceptor:
```js
axios.interceptors.request.use(config => {
if (config.data instanceof FormData) {
Object.assign(config.headers, config.data.getHeaders());
}
return config;
});
```
## Semver ## 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. 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.

@ -135,7 +135,7 @@ This will polyfill the global environment, and only needs to be done once.
#### `axios.success`/`axios.error` #### `axios.success`/`axios.error`
The `success`, and `error` aliases were deprecated in [0.4.0](https://github.com/axios/axios/blob/master/CHANGELOG.md#040-oct-03-2014). As of this release they have been removed entirely. Instead please use `axios.then`, and `axios.catch` respectively. The `success`, and `error` aliases were deprectated in [0.4.0](https://github.com/axios/axios/blob/master/CHANGELOG.md#040-oct-03-2014). As of this release they have been removed entirely. Instead please use `axios.then`, and `axios.catch` respectively.
```js ```js
axios.get('some/url') axios.get('some/url')

@ -1,4 +1,4 @@
/* axios v0.21.1 | (c) 2020 by Matt Zabriskie */ /* axios v0.19.2 | (c) 2020 by Matt Zabriskie */
(function webpackUniversalModuleDefinition(root, factory) { (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object') if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(); module.exports = factory();
@ -110,9 +110,6 @@ return /******/ (function(modules) { // webpackBootstrap
}; };
axios.spread = __webpack_require__(25); axios.spread = __webpack_require__(25);
// Expose isAxiosError
axios.isAxiosError = __webpack_require__(26);
module.exports = axios; module.exports = axios;
// Allow use of default import syntax in TypeScript // Allow use of default import syntax in TypeScript
@ -230,21 +227,6 @@ return /******/ (function(modules) { // webpackBootstrap
return val !== null && typeof val === 'object'; return val !== null && typeof val === 'object';
} }
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (toString.call(val) !== '[object Object]') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/** /**
* Determine if a value is a Date * Determine if a value is a Date
* *
@ -401,12 +383,34 @@ return /******/ (function(modules) { // webpackBootstrap
function merge(/* obj1, obj2, obj3, ... */) { function merge(/* obj1, obj2, obj3, ... */) {
var result = {}; var result = {};
function assignValue(val, key) { function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) { if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val); result[key] = merge(result[key], val);
} else if (isPlainObject(val)) { } else {
result[key] = merge({}, val); result[key] = val;
} else if (isArray(val)) { }
result[key] = val.slice(); }
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else { } else {
result[key] = val; result[key] = val;
} }
@ -437,19 +441,6 @@ return /******/ (function(modules) { // webpackBootstrap
return a; return a;
} }
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
module.exports = { module.exports = {
isArray: isArray, isArray: isArray,
isArrayBuffer: isArrayBuffer, isArrayBuffer: isArrayBuffer,
@ -459,7 +450,6 @@ return /******/ (function(modules) { // webpackBootstrap
isString: isString, isString: isString,
isNumber: isNumber, isNumber: isNumber,
isObject: isObject, isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined, isUndefined: isUndefined,
isDate: isDate, isDate: isDate,
isFile: isFile, isFile: isFile,
@ -470,9 +460,9 @@ return /******/ (function(modules) { // webpackBootstrap
isStandardBrowserEnv: isStandardBrowserEnv, isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach, forEach: forEach,
merge: merge, merge: merge,
deepMerge: deepMerge,
extend: extend, extend: extend,
trim: trim, trim: trim
stripBOM: stripBOM
}; };
@ -572,10 +562,9 @@ return /******/ (function(modules) { // webpackBootstrap
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/ /*eslint func-names:0*/
Axios.prototype[method] = function(url, config) { Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, { return this.request(utils.merge(config || {}, {
method: method, method: method,
url: url, url: url
data: (config || {}).data
})); }));
}; };
}); });
@ -583,7 +572,7 @@ return /******/ (function(modules) { // webpackBootstrap
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/ /*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) { Axios.prototype[method] = function(url, data, config) {
return this.request(mergeConfig(config || {}, { return this.request(utils.merge(config || {}, {
method: method, method: method,
url: url, url: url,
data: data data: data
@ -604,6 +593,7 @@ return /******/ (function(modules) { // webpackBootstrap
function encode(val) { function encode(val) {
return encodeURIComponent(val). return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':'). replace(/%3A/gi, ':').
replace(/%24/g, '$'). replace(/%24/g, '$').
replace(/%2C/gi, ','). replace(/%2C/gi, ',').
@ -930,7 +920,6 @@ return /******/ (function(modules) { // webpackBootstrap
xsrfHeaderName: 'X-XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1, maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) { validateStatus: function validateStatus(status) {
return status >= 200 && status < 300; return status >= 200 && status < 300;
@ -980,11 +969,10 @@ return /******/ (function(modules) { // webpackBootstrap
var utils = __webpack_require__(2); var utils = __webpack_require__(2);
var settle = __webpack_require__(13); var settle = __webpack_require__(13);
var cookies = __webpack_require__(16);
var buildURL = __webpack_require__(5); var buildURL = __webpack_require__(5);
var buildFullPath = __webpack_require__(17); var buildFullPath = __webpack_require__(16);
var parseHeaders = __webpack_require__(20); var parseHeaders = __webpack_require__(19);
var isURLSameOrigin = __webpack_require__(21); var isURLSameOrigin = __webpack_require__(20);
var createError = __webpack_require__(14); var createError = __webpack_require__(14);
module.exports = function xhrAdapter(config) { module.exports = function xhrAdapter(config) {
@ -1001,7 +989,7 @@ return /******/ (function(modules) { // webpackBootstrap
// HTTP basic authentication // HTTP basic authentication
if (config.auth) { if (config.auth) {
var username = config.auth.username || ''; var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
} }
@ -1082,6 +1070,8 @@ return /******/ (function(modules) { // webpackBootstrap
// This is only done if running in a standard browser environment. // This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native. // Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) { if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(21);
// Add xsrf header // Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) : cookies.read(config.xsrfCookieName) :
@ -1147,7 +1137,7 @@ return /******/ (function(modules) { // webpackBootstrap
}); });
} }
if (!requestData) { if (requestData === undefined) {
requestData = null; requestData = null;
} }
@ -1174,7 +1164,7 @@ return /******/ (function(modules) { // webpackBootstrap
*/ */
module.exports = function settle(resolve, reject, response) { module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus; var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) { if (!validateStatus || validateStatus(response.status)) {
resolve(response); resolve(response);
} else { } else {
reject(createError( reject(createError(
@ -1238,7 +1228,7 @@ return /******/ (function(modules) { // webpackBootstrap
error.response = response; error.response = response;
error.isAxiosError = true; error.isAxiosError = true;
error.toJSON = function toJSON() { error.toJSON = function() {
return { return {
// Standard // Standard
message: this.message, message: this.message,
@ -1266,67 +1256,8 @@ return /******/ (function(modules) { // webpackBootstrap
'use strict'; 'use strict';
var utils = __webpack_require__(2); var isAbsoluteURL = __webpack_require__(17);
var combineURLs = __webpack_require__(18);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var isAbsoluteURL = __webpack_require__(18);
var combineURLs = __webpack_require__(19);
/** /**
* Creates a new URL by combining the baseURL with the requestedURL, * Creates a new URL by combining the baseURL with the requestedURL,
@ -1346,7 +1277,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }), /***/ }),
/* 18 */ /* 17 */
/***/ (function(module, exports) { /***/ (function(module, exports) {
'use strict'; 'use strict';
@ -1366,7 +1297,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }), /***/ }),
/* 19 */ /* 18 */
/***/ (function(module, exports) { /***/ (function(module, exports) {
'use strict'; 'use strict';
@ -1386,7 +1317,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }), /***/ }),
/* 20 */ /* 19 */
/***/ (function(module, exports, __webpack_require__) { /***/ (function(module, exports, __webpack_require__) {
'use strict'; 'use strict';
@ -1445,7 +1376,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }), /***/ }),
/* 21 */ /* 20 */
/***/ (function(module, exports, __webpack_require__) { /***/ (function(module, exports, __webpack_require__) {
'use strict'; 'use strict';
@ -1518,6 +1449,65 @@ return /******/ (function(modules) { // webpackBootstrap
); );
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }), /***/ }),
/* 22 */ /* 22 */
/***/ (function(module, exports, __webpack_require__) { /***/ (function(module, exports, __webpack_require__) {
@ -1539,73 +1529,59 @@ return /******/ (function(modules) { // webpackBootstrap
config2 = config2 || {}; config2 = config2 || {};
var config = {}; var config = {};
var valueFromConfig2Keys = ['url', 'method', 'data']; var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
var defaultToConfig2Keys = [ var defaultToConfig2Keys = [
'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' 'httpsAgent', 'cancelToken', 'socketPath'
]; ];
var directMergeKeys = ['validateStatus'];
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;
}
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
}
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) { if (typeof config2[prop] !== 'undefined') {
config[prop] = getMergedValue(undefined, config2[prop]); config[prop] = config2[prop];
} }
}); });
utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { config[prop] = utils.deepMerge(config1[prop], config2[prop]);
if (!utils.isUndefined(config2[prop])) { } else if (typeof config2[prop] !== 'undefined') {
config[prop] = getMergedValue(undefined, config2[prop]); config[prop] = config2[prop];
} else if (!utils.isUndefined(config1[prop])) { } else if (utils.isObject(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]); config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
} }
}); });
utils.forEach(directMergeKeys, function merge(prop) { utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (prop in config2) { if (typeof config2[prop] !== 'undefined') {
config[prop] = getMergedValue(config1[prop], config2[prop]); config[prop] = config2[prop];
} else if (prop in config1) { } else if (typeof config1[prop] !== 'undefined') {
config[prop] = getMergedValue(undefined, config1[prop]); config[prop] = config1[prop];
} }
}); });
var axiosKeys = valueFromConfig2Keys var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys) .concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys) .concat(defaultToConfig2Keys);
.concat(directMergeKeys);
var otherKeys = Object var otherKeys = Object
.keys(config1) .keys(config2)
.concat(Object.keys(config2))
.filter(function filterAxiosKeys(key) { .filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1; return axiosKeys.indexOf(key) === -1;
}); });
utils.forEach(otherKeys, mergeDeepProperties); utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
return config; return config;
}; };
@ -1732,23 +1708,6 @@ return /******/ (function(modules) { // webpackBootstrap
}; };
/***/ }),
/* 26 */
/***/ (function(module, exports) {
'use strict';
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
return (typeof payload === 'object') && (payload.isAxiosError === true);
};
/***/ }) /***/ })
/******/ ]) /******/ ])
}); });

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -29,16 +29,15 @@ export type Method =
| 'post' | 'POST' | 'post' | 'POST'
| 'put' | 'PUT' | 'put' | 'PUT'
| 'patch' | 'PATCH' | 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK' | 'link' | 'LINK'
| 'unlink' | 'UNLINK' | 'unlink' | 'UNLINK'
export type ResponseType = export type ResponseType =
| 'arraybuffer' | 'arraybuffer'
| 'blob' | 'blob'
| 'document' | 'document'
| 'json' | 'json'
| 'text' | 'text'
| 'stream' | 'stream'
export interface AxiosRequestConfig { export interface AxiosRequestConfig {
@ -62,15 +61,13 @@ export interface AxiosRequestConfig {
onUploadProgress?: (progressEvent: any) => void; onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void; onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number; maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null; validateStatus?: (status: number) => boolean;
maxBodyLength?: number;
maxRedirects?: number; maxRedirects?: number;
socketPath?: string | null; socketPath?: string | null;
httpAgent?: any; httpAgent?: any;
httpsAgent?: any; httpsAgent?: any;
proxy?: AxiosProxyConfig | false; proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken; cancelToken?: CancelToken;
decompress?: boolean;
} }
export interface AxiosResponse<T = any> { export interface AxiosResponse<T = any> {
@ -153,9 +150,8 @@ export interface AxiosStatic extends AxiosInstance {
isCancel(value: any): boolean; isCancel(value: any): boolean;
all<T>(values: (T | Promise<T>)[]): Promise<T[]>; all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R; spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
isAxiosError(payload: any): payload is AxiosError;
} }
declare const axios: AxiosStatic; declare const Axios: AxiosStatic;
export default axios; export default Axios;

@ -16,31 +16,6 @@ var enhanceError = require('../core/enhanceError');
var isHttps = /https:?/; var isHttps = /https:?/;
/**
*
* @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*/ /*eslint consistent-return:0*/
module.exports = function httpAdapter(config) { module.exports = function httpAdapter(config) {
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
@ -151,11 +126,11 @@ module.exports = function httpAdapter(config) {
}); });
} }
if (shouldProxy) { if (shouldProxy) {
proxy = { proxy = {
host: parsedProxyUrl.hostname, host: parsedProxyUrl.hostname,
port: parsedProxyUrl.port, port: parsedProxyUrl.port
protocol: parsedProxyUrl.protocol
}; };
if (parsedProxyUrl.auth) { if (parsedProxyUrl.auth) {
@ -170,8 +145,17 @@ module.exports = function httpAdapter(config) {
} }
if (proxy) { if (proxy) {
options.hostname = proxy.host;
options.host = proxy.host;
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); options.port = proxy.port;
options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path;
// 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;
}
} }
var transport; var transport;
@ -187,8 +171,8 @@ module.exports = function httpAdapter(config) {
transport = isHttpsProxy ? httpsFollow : httpFollow; transport = isHttpsProxy ? httpsFollow : httpFollow;
} }
if (config.maxBodyLength > -1) { if (config.maxContentLength && config.maxContentLength > -1) {
options.maxBodyLength = config.maxBodyLength; options.maxBodyLength = config.maxContentLength;
} }
// Create the request // Create the request
@ -197,27 +181,22 @@ module.exports = function httpAdapter(config) {
// uncompress the response body transparently if required // uncompress the response body transparently if required
var stream = res; var stream = res;
switch (res.headers['content-encoding']) {
// return the last request in case of redirects /*eslint default-case:0*/
var lastRequest = res.req || req; case 'gzip':
case 'compress':
case 'deflate':
// 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 // add the unzipper to the body stream processing pipeline
stream = stream.pipe(zlib.createUnzip()); stream = (res.statusCode === 204) ? stream : stream.pipe(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations // remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding']; delete res.headers['content-encoding'];
break; break;
}
} }
// return the last request in case of redirects
var lastRequest = res.req || req;
var response = { var response = {
status: res.statusCode, status: res.statusCode,
statusText: res.statusMessage, statusText: res.statusMessage,
@ -251,9 +230,6 @@ module.exports = function httpAdapter(config) {
var responseData = Buffer.concat(responseBuffer); var responseData = Buffer.concat(responseBuffer);
if (config.responseType !== 'arraybuffer') { if (config.responseType !== 'arraybuffer') {
responseData = responseData.toString(config.responseEncoding); responseData = responseData.toString(config.responseEncoding);
if (!config.responseEncoding || config.responseEncoding === 'utf8') {
responseData = utils.stripBOM(responseData);
}
} }
response.data = responseData; response.data = responseData;
@ -264,7 +240,7 @@ module.exports = function httpAdapter(config) {
// Handle errors // Handle errors
req.on('error', function handleRequestError(err) { req.on('error', function handleRequestError(err) {
if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return; if (req.aborted) return;
reject(enhanceError(err, config, null, req)); reject(enhanceError(err, config, null, req));
}); });

@ -2,7 +2,6 @@
var utils = require('./../utils'); var utils = require('./../utils');
var settle = require('./../core/settle'); var settle = require('./../core/settle');
var cookies = require('./../helpers/cookies');
var buildURL = require('./../helpers/buildURL'); var buildURL = require('./../helpers/buildURL');
var buildFullPath = require('../core/buildFullPath'); var buildFullPath = require('../core/buildFullPath');
var parseHeaders = require('./../helpers/parseHeaders'); var parseHeaders = require('./../helpers/parseHeaders');
@ -23,7 +22,7 @@ module.exports = function xhrAdapter(config) {
// HTTP basic authentication // HTTP basic authentication
if (config.auth) { if (config.auth) {
var username = config.auth.username || ''; var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
} }
@ -104,6 +103,8 @@ module.exports = function xhrAdapter(config) {
// This is only done if running in a standard browser environment. // This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native. // Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) { if (utils.isStandardBrowserEnv()) {
var cookies = require('./../helpers/cookies');
// Add xsrf header // Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) : cookies.read(config.xsrfCookieName) :
@ -169,7 +170,7 @@ module.exports = function xhrAdapter(config) {
}); });
} }
if (!requestData) { if (requestData === undefined) {
requestData = null; requestData = null;
} }

@ -47,9 +47,6 @@ axios.all = function all(promises) {
}; };
axios.spread = require('./helpers/spread'); axios.spread = require('./helpers/spread');
// Expose isAxiosError
axios.isAxiosError = require('./helpers/isAxiosError');
module.exports = axios; module.exports = axios;
// Allow use of default import syntax in TypeScript // Allow use of default import syntax in TypeScript

@ -73,10 +73,9 @@ Axios.prototype.getUri = function getUri(config) {
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/ /*eslint func-names:0*/
Axios.prototype[method] = function(url, config) { Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, { return this.request(utils.merge(config || {}, {
method: method, method: method,
url: url, url: url
data: (config || {}).data
})); }));
}; };
}); });
@ -84,7 +83,7 @@ utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/ /*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) { Axios.prototype[method] = function(url, data, config) {
return this.request(mergeConfig(config || {}, { return this.request(utils.merge(config || {}, {
method: method, method: method,
url: url, url: url,
data: data data: data

@ -20,7 +20,7 @@ module.exports = function enhanceError(error, config, code, request, response) {
error.response = response; error.response = response;
error.isAxiosError = true; error.isAxiosError = true;
error.toJSON = function toJSON() { error.toJSON = function() {
return { return {
// Standard // Standard
message: this.message, message: this.message,

@ -15,73 +15,59 @@ module.exports = function mergeConfig(config1, config2) {
config2 = config2 || {}; config2 = config2 || {};
var config = {}; var config = {};
var valueFromConfig2Keys = ['url', 'method', 'data']; var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
var defaultToConfig2Keys = [ var defaultToConfig2Keys = [
'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' 'httpsAgent', 'cancelToken', 'socketPath'
]; ];
var directMergeKeys = ['validateStatus'];
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;
}
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
}
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) { if (typeof config2[prop] !== 'undefined') {
config[prop] = getMergedValue(undefined, config2[prop]); config[prop] = config2[prop];
} }
}); });
utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { config[prop] = utils.deepMerge(config1[prop], config2[prop]);
if (!utils.isUndefined(config2[prop])) { } else if (typeof config2[prop] !== 'undefined') {
config[prop] = getMergedValue(undefined, config2[prop]); config[prop] = config2[prop];
} else if (!utils.isUndefined(config1[prop])) { } else if (utils.isObject(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]); config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
} }
}); });
utils.forEach(directMergeKeys, function merge(prop) { utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (prop in config2) { if (typeof config2[prop] !== 'undefined') {
config[prop] = getMergedValue(config1[prop], config2[prop]); config[prop] = config2[prop];
} else if (prop in config1) { } else if (typeof config1[prop] !== 'undefined') {
config[prop] = getMergedValue(undefined, config1[prop]); config[prop] = config1[prop];
} }
}); });
var axiosKeys = valueFromConfig2Keys var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys) .concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys) .concat(defaultToConfig2Keys);
.concat(directMergeKeys);
var otherKeys = Object var otherKeys = Object
.keys(config1) .keys(config2)
.concat(Object.keys(config2))
.filter(function filterAxiosKeys(key) { .filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1; return axiosKeys.indexOf(key) === -1;
}); });
utils.forEach(otherKeys, mergeDeepProperties); utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
return config; return config;
}; };

@ -11,7 +11,7 @@ var createError = require('./createError');
*/ */
module.exports = function settle(resolve, reject, response) { module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus; var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) { if (!validateStatus || validateStatus(response.status)) {
resolve(response); resolve(response);
} else { } else {
reject(createError( reject(createError(

@ -74,7 +74,6 @@ var defaults = {
xsrfHeaderName: 'X-XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1, maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) { validateStatus: function validateStatus(status) {
return status >= 200 && status < 300; return status >= 200 && status < 300;

@ -4,6 +4,7 @@ var utils = require('./../utils');
function encode(val) { function encode(val) {
return encodeURIComponent(val). return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':'). replace(/%3A/gi, ':').
replace(/%24/g, '$'). replace(/%24/g, '$').
replace(/%2C/gi, ','). replace(/%2C/gi, ',').

@ -1,11 +0,0 @@
'use strict';
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
return (typeof payload === 'object') && (payload.isAxiosError === true);
};

@ -105,21 +105,6 @@ function isObject(val) {
return val !== null && typeof val === 'object'; return val !== null && typeof val === 'object';
} }
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (toString.call(val) !== '[object Object]') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/** /**
* Determine if a value is a Date * Determine if a value is a Date
* *
@ -276,12 +261,34 @@ function forEach(obj, fn) {
function merge(/* obj1, obj2, obj3, ... */) { function merge(/* obj1, obj2, obj3, ... */) {
var result = {}; var result = {};
function assignValue(val, key) { function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) { if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val); result[key] = merge(result[key], val);
} else if (isPlainObject(val)) { } else {
result[key] = merge({}, val); result[key] = val;
} else if (isArray(val)) { }
result[key] = val.slice(); }
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else { } else {
result[key] = val; result[key] = val;
} }
@ -312,19 +319,6 @@ function extend(a, b, thisArg) {
return a; return a;
} }
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
module.exports = { module.exports = {
isArray: isArray, isArray: isArray,
isArrayBuffer: isArrayBuffer, isArrayBuffer: isArrayBuffer,
@ -334,7 +328,6 @@ module.exports = {
isString: isString, isString: isString,
isNumber: isNumber, isNumber: isNumber,
isObject: isObject, isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined, isUndefined: isUndefined,
isDate: isDate, isDate: isDate,
isFile: isFile, isFile: isFile,
@ -345,7 +338,7 @@ module.exports = {
isStandardBrowserEnv: isStandardBrowserEnv, isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach, forEach: forEach,
merge: merge, merge: merge,
deepMerge: deepMerge,
extend: extend, extend: extend,
trim: trim, trim: trim
stripBOM: stripBOM
}; };

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

@ -1,148 +0,0 @@
## Follow Redirects
Drop-in replacement for Node's `http` and `https` modules that automatically follows redirects.
[![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects)
[![Build Status](https://github.com/follow-redirects/follow-redirects/workflows/CI/badge.svg)](https://github.com/follow-redirects/follow-redirects/actions)
[![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master)
[![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects)
[![Sponsor on GitHub](https://img.shields.io/static/v1?label=Sponsor&message=%F0%9F%92%96&logo=GitHub)](https://github.com/sponsors/RubenVerborgh)
`follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback)
methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback)
modules, with the exception that they will seamlessly follow redirects.
```javascript
const { http, https } = require('follow-redirects');
http.get('http://bit.ly/900913', response => {
response.on('data', chunk => {
console.log(chunk);
});
}).on('error', err => {
console.error(err);
});
```
You can inspect the final redirected URL through the `responseUrl` property on the `response`.
If no redirection happened, `responseUrl` is the original request URL.
```javascript
const request = https.request({
host: 'bitly.com',
path: '/UHfDGO',
}, response => {
console.log(response.responseUrl);
// 'http://duckduckgo.com/robots.txt'
});
request.end();
```
## Options
### Global options
Global options are set directly on the `follow-redirects` module:
```javascript
const followRedirects = require('follow-redirects');
followRedirects.maxRedirects = 10;
followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB
```
The following global options are supported:
- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.
- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.
### Per-request options
Per-request options are set by passing an `options` object:
```javascript
const url = require('url');
const { http, https } = require('follow-redirects');
const options = url.parse('http://bit.ly/900913');
options.maxRedirects = 10;
options.beforeRedirect = (options, { headers }) => {
// 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 (options.hostname === "example.com") {
options.auth = "user:password";
}
};
http.request(options);
```
In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback),
the following per-request options are supported:
- `followRedirects` (default: `true`) – whether redirects should be followed.
- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.
- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.
- `beforeRedirect` (default: `undefined`) – optionally change the request `options` on redirects, or abort the request by throwing an error.
- `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }`
- `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object.
### Advanced usage
By default, `follow-redirects` will use the Node.js default implementations
of [`http`](https://nodejs.org/api/http.html)
and [`https`](https://nodejs.org/api/https.html).
To enable features such as caching and/or intermediate request tracking,
you might instead want to wrap `follow-redirects` around custom protocol implementations:
```javascript
const { http, https } = require('follow-redirects').wrap({
http: require('your-custom-http'),
https: require('your-custom-https'),
});
```
Such custom protocols only need an implementation of the `request` method.
## Browser Usage
Due to the way the browser works,
the `http` and `https` browser equivalents perform redirects by default.
By requiring `follow-redirects` this way:
```javascript
const http = require('follow-redirects/http');
const https = require('follow-redirects/https');
```
you can easily tell webpack and friends to replace
`follow-redirect` by the built-in versions:
```json
{
"follow-redirects/http" : "http",
"follow-redirects/https" : "https"
}
```
## Contributing
Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues)
detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied
by tests. You can run the test suite locally with a simple `npm test` command.
## Debug Logging
`follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging
set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test
suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well.
## Authors
- [Ruben Verborgh](https://ruben.verborgh.org/)
- [Olivier Lalonde](mailto:olalonde@gmail.com)
- [James Talmage](mailto:james@talmage.io)
## License
[MIT License](https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE)

@ -1,14 +0,0 @@
var debug;
module.exports = function () {
if (!debug) {
try {
/* eslint global-require: off */
debug = require("debug")("follow-redirects");
}
catch (error) {
debug = function () { /* */ };
}
}
debug.apply(null, arguments);
};

@ -1 +0,0 @@
module.exports = require("./").http;

@ -1 +0,0 @@
module.exports = require("./").https;

@ -1,504 +0,0 @@
var url = require("url");
var URL = url.URL;
var http = require("http");
var https = require("https");
var Writable = require("stream").Writable;
var assert = require("assert");
var debug = require("./debug");
// Create handlers that pass events from native requests
var eventHandlers = Object.create(null);
["abort", "aborted", "connect", "error", "socket", "timeout"].forEach(function (event) {
eventHandlers[event] = function (arg1, arg2, arg3) {
this._redirectable.emit(event, arg1, arg2, arg3);
};
});
// Error types with codes
var RedirectionError = createErrorType(
"ERR_FR_REDIRECTION_FAILURE",
""
);
var TooManyRedirectsError = createErrorType(
"ERR_FR_TOO_MANY_REDIRECTS",
"Maximum number of redirects exceeded"
);
var MaxBodyLengthExceededError = createErrorType(
"ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
"Request body larger than maxBodyLength limit"
);
var WriteAfterEndError = createErrorType(
"ERR_STREAM_WRITE_AFTER_END",
"write after end"
);
// An HTTP(S) request that can be redirected
function RedirectableRequest(options, responseCallback) {
// Initialize the request
Writable.call(this);
this._sanitizeOptions(options);
this._options = options;
this._ended = false;
this._ending = false;
this._redirectCount = 0;
this._redirects = [];
this._requestBodyLength = 0;
this._requestBodyBuffers = [];
// Attach a callback if passed
if (responseCallback) {
this.on("response", responseCallback);
}
// React to responses of native requests
var self = this;
this._onNativeResponse = function (response) {
self._processResponse(response);
};
// Perform the first request
this._performRequest();
}
RedirectableRequest.prototype = Object.create(Writable.prototype);
// Writes buffered data to the current native request
RedirectableRequest.prototype.write = function (data, encoding, callback) {
// Writing is not allowed if end has been called
if (this._ending) {
throw new WriteAfterEndError();
}
// Validate input and shift parameters if necessary
if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
throw new TypeError("data should be a string, Buffer or Uint8Array");
}
if (typeof encoding === "function") {
callback = encoding;
encoding = null;
}
// Ignore empty buffers, since writing them doesn't invoke the callback
// https://github.com/nodejs/node/issues/22066
if (data.length === 0) {
if (callback) {
callback();
}
return;
}
// Only write when we don't exceed the maximum body length
if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
this._requestBodyLength += data.length;
this._requestBodyBuffers.push({ data: data, encoding: encoding });
this._currentRequest.write(data, encoding, callback);
}
// Error when we exceed the maximum body length
else {
this.emit("error", new MaxBodyLengthExceededError());
this.abort();
}
};
// Ends the current native request
RedirectableRequest.prototype.end = function (data, encoding, callback) {
// Shift parameters if necessary
if (typeof data === "function") {
callback = data;
data = encoding = null;
}
else if (typeof encoding === "function") {
callback = encoding;
encoding = null;
}
// Write data if needed and end
if (!data) {
this._ended = this._ending = true;
this._currentRequest.end(null, null, callback);
}
else {
var self = this;
var currentRequest = this._currentRequest;
this.write(data, encoding, function () {
self._ended = true;
currentRequest.end(null, null, callback);
});
this._ending = true;
}
};
// Sets a header value on the current native request
RedirectableRequest.prototype.setHeader = function (name, value) {
this._options.headers[name] = value;
this._currentRequest.setHeader(name, value);
};
// Clears a header value on the current native request
RedirectableRequest.prototype.removeHeader = function (name) {
delete this._options.headers[name];
this._currentRequest.removeHeader(name);
};
// Global timeout for all underlying requests
RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
if (callback) {
this.once("timeout", callback);
}
if (this.socket) {
startTimer(this, msecs);
}
else {
var self = this;
this._currentRequest.once("socket", function () {
startTimer(self, msecs);
});
}
this.once("response", clearTimer);
this.once("error", clearTimer);
return this;
};
function startTimer(request, msecs) {
clearTimeout(request._timeout);
request._timeout = setTimeout(function () {
request.emit("timeout");
}, msecs);
}
function clearTimer() {
clearTimeout(this._timeout);
}
// Proxy all other public ClientRequest methods
[
"abort", "flushHeaders", "getHeader",
"setNoDelay", "setSocketKeepAlive",
].forEach(function (method) {
RedirectableRequest.prototype[method] = function (a, b) {
return this._currentRequest[method](a, b);
};
});
// Proxy all public ClientRequest properties
["aborted", "connection", "socket"].forEach(function (property) {
Object.defineProperty(RedirectableRequest.prototype, property, {
get: function () { return this._currentRequest[property]; },
});
});
RedirectableRequest.prototype._sanitizeOptions = function (options) {
// Ensure headers are always present
if (!options.headers) {
options.headers = {};
}
// Since http.request treats host as an alias of hostname,
// but the url module interprets host as hostname plus port,
// eliminate the host property to avoid confusion.
if (options.host) {
// Use hostname if set, because it has precedence
if (!options.hostname) {
options.hostname = options.host;
}
delete options.host;
}
// Complete the URL object when necessary
if (!options.pathname && options.path) {
var searchPos = options.path.indexOf("?");
if (searchPos < 0) {
options.pathname = options.path;
}
else {
options.pathname = options.path.substring(0, searchPos);
options.search = options.path.substring(searchPos);
}
}
};
// Executes the next native request (initial or redirect)
RedirectableRequest.prototype._performRequest = function () {
// Load the native protocol
var protocol = this._options.protocol;
var nativeProtocol = this._options.nativeProtocols[protocol];
if (!nativeProtocol) {
this.emit("error", new TypeError("Unsupported protocol " + protocol));
return;
}
// If specified, use the agent corresponding to the protocol
// (HTTP and HTTPS use different types of agents)
if (this._options.agents) {
var scheme = protocol.substr(0, protocol.length - 1);
this._options.agent = this._options.agents[scheme];
}
// Create the native request
var request = this._currentRequest =
nativeProtocol.request(this._options, this._onNativeResponse);
this._currentUrl = url.format(this._options);
// Set up event handlers
request._redirectable = this;
for (var event in eventHandlers) {
/* istanbul ignore else */
if (event) {
request.on(event, eventHandlers[event]);
}
}
// End a redirected request
// (The first request must be ended explicitly with RedirectableRequest#end)
if (this._isRedirect) {
// Write the request entity and end.
var i = 0;
var self = this;
var buffers = this._requestBodyBuffers;
(function writeNext(error) {
// Only write if this request has not been redirected yet
/* istanbul ignore else */
if (request === self._currentRequest) {
// Report any write errors
/* istanbul ignore if */
if (error) {
self.emit("error", error);
}
// Write the next buffer if there are still left
else if (i < buffers.length) {
var buffer = buffers[i++];
/* istanbul ignore else */
if (!request.finished) {
request.write(buffer.data, buffer.encoding, writeNext);
}
}
// End the request if `end` has been called on us
else if (self._ended) {
request.end();
}
}
}());
}
};
// Processes a response from the current native request
RedirectableRequest.prototype._processResponse = function (response) {
// Store the redirected response
var statusCode = response.statusCode;
if (this._options.trackRedirects) {
this._redirects.push({
url: this._currentUrl,
headers: response.headers,
statusCode: statusCode,
});
}
// RFC7231§6.4: The 3xx (Redirection) class of status code indicates
// that further action needs to be taken by the user agent in order to
// fulfill the request. If a Location header field is provided,
// the user agent MAY automatically redirect its request to the URI
// referenced by the Location field value,
// even if the specific status code is not understood.
var location = response.headers.location;
if (location && this._options.followRedirects !== false &&
statusCode >= 300 && statusCode < 400) {
// Abort the current request
this._currentRequest.removeAllListeners();
this._currentRequest.on("error", noop);
this._currentRequest.abort();
// Discard the remainder of the response to avoid waiting for data
response.destroy();
// RFC7231§6.4: A client SHOULD detect and intervene
// in cyclical redirections (i.e., "infinite" redirection loops).
if (++this._redirectCount > this._options.maxRedirects) {
this.emit("error", new TooManyRedirectsError());
return;
}
// RFC7231§6.4: Automatic redirection needs to done with
// care for methods not known to be safe, […]
// RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
// the request method from POST to GET for the subsequent request.
if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
// RFC7231§6.4.4: The 303 (See Other) status code indicates that
// the server is redirecting the user agent to a different resource […]
// A user agent can perform a retrieval request targeting that URI
// (a GET or HEAD request if using HTTP) […]
(statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
this._options.method = "GET";
// Drop a possible entity and headers related to it
this._requestBodyBuffers = [];
removeMatchingHeaders(/^content-/i, this._options.headers);
}
// Drop the Host header, as the redirect might lead to a different host
var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) ||
url.parse(this._currentUrl).hostname;
// Create the redirected request
var redirectUrl = url.resolve(this._currentUrl, location);
debug("redirecting to", redirectUrl);
this._isRedirect = true;
var redirectUrlParts = url.parse(redirectUrl);
Object.assign(this._options, redirectUrlParts);
// Drop the Authorization header if redirecting to another host
if (redirectUrlParts.hostname !== previousHostName) {
removeMatchingHeaders(/^authorization$/i, this._options.headers);
}
// Evaluate the beforeRedirect callback
if (typeof this._options.beforeRedirect === "function") {
var responseDetails = { headers: response.headers };
try {
this._options.beforeRedirect.call(null, this._options, responseDetails);
}
catch (err) {
this.emit("error", err);
return;
}
this._sanitizeOptions(this._options);
}
// Perform the redirected request
try {
this._performRequest();
}
catch (cause) {
var error = new RedirectionError("Redirected request failed: " + cause.message);
error.cause = cause;
this.emit("error", error);
}
}
else {
// The response is not a redirect; return it as-is
response.responseUrl = this._currentUrl;
response.redirects = this._redirects;
this.emit("response", response);
// Clean up
this._requestBodyBuffers = [];
}
};
// Wraps the key/value object of protocols with redirect functionality
function wrap(protocols) {
// Default settings
var exports = {
maxRedirects: 21,
maxBodyLength: 10 * 1024 * 1024,
};
// Wrap each protocol
var nativeProtocols = {};
Object.keys(protocols).forEach(function (scheme) {
var protocol = scheme + ":";
var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
// Executes a request, following redirects
function request(input, options, callback) {
// Parse parameters
if (typeof input === "string") {
var urlStr = input;
try {
input = urlToOptions(new URL(urlStr));
}
catch (err) {
/* istanbul ignore next */
input = url.parse(urlStr);
}
}
else if (URL && (input instanceof URL)) {
input = urlToOptions(input);
}
else {
callback = options;
options = input;
input = { protocol: protocol };
}
if (typeof options === "function") {
callback = options;
options = null;
}
// Set defaults
options = Object.assign({
maxRedirects: exports.maxRedirects,
maxBodyLength: exports.maxBodyLength,
}, input, options);
options.nativeProtocols = nativeProtocols;
assert.equal(options.protocol, protocol, "protocol mismatch");
debug("options", options);
return new RedirectableRequest(options, callback);
}
// Executes a GET request, following redirects
function get(input, options, callback) {
var wrappedRequest = wrappedProtocol.request(input, options, callback);
wrappedRequest.end();
return wrappedRequest;
}
// Expose the properties on the wrapped protocol
Object.defineProperties(wrappedProtocol, {
request: { value: request, configurable: true, enumerable: true, writable: true },
get: { value: get, configurable: true, enumerable: true, writable: true },
});
});
return exports;
}
/* istanbul ignore next */
function noop() { /* empty */ }
// from https://github.com/nodejs/node/blob/master/lib/internal/url.js
function urlToOptions(urlObject) {
var options = {
protocol: urlObject.protocol,
hostname: urlObject.hostname.startsWith("[") ?
/* istanbul ignore next */
urlObject.hostname.slice(1, -1) :
urlObject.hostname,
hash: urlObject.hash,
search: urlObject.search,
pathname: urlObject.pathname,
path: urlObject.pathname + urlObject.search,
href: urlObject.href,
};
if (urlObject.port !== "") {
options.port = Number(urlObject.port);
}
return options;
}
function removeMatchingHeaders(regex, headers) {
var lastValue;
for (var header in headers) {
if (regex.test(header)) {
lastValue = headers[header];
delete headers[header];
}
}
return lastValue;
}
function createErrorType(code, defaultMessage) {
function CustomError(message) {
Error.captureStackTrace(this, this.constructor);
this.message = message || defaultMessage;
}
CustomError.prototype = new Error();
CustomError.prototype.constructor = CustomError;
CustomError.prototype.name = "Error [" + code + "]";
CustomError.prototype.code = code;
return CustomError;
}
// Exports
module.exports = wrap({ http: http, https: https });
module.exports.wrap = wrap;

@ -1,98 +0,0 @@
{
"_args": [
[
"follow-redirects@1.13.2",
"/home/sigonasr2/divar/server"
]
],
"_from": "follow-redirects@1.13.2",
"_id": "follow-redirects@1.13.2",
"_inBundle": false,
"_integrity": "sha512-6mPTgLxYm3r6Bkkg0vNM0HTjfGrOEtsfbhagQvbxDEsEkpNhw582upBaoRZylzen6krEmxXJgt9Ju6HiI4O7BA==",
"_location": "/axios/follow-redirects",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "follow-redirects@1.13.2",
"name": "follow-redirects",
"escapedName": "follow-redirects",
"rawSpec": "1.13.2",
"saveSpec": null,
"fetchSpec": "1.13.2"
},
"_requiredBy": [
"/axios"
],
"_resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.13.2.tgz",
"_spec": "1.13.2",
"_where": "/home/sigonasr2/divar/server",
"author": {
"name": "Ruben Verborgh",
"email": "ruben@verborgh.org",
"url": "https://ruben.verborgh.org/"
},
"bugs": {
"url": "https://github.com/follow-redirects/follow-redirects/issues"
},
"contributors": [
{
"name": "Olivier Lalonde",
"email": "olalonde@gmail.com",
"url": "http://www.syskall.com"
},
{
"name": "James Talmage",
"email": "james@talmage.io"
}
],
"description": "HTTP and HTTPS modules that follow redirects.",
"devDependencies": {
"concat-stream": "^2.0.0",
"eslint": "^5.16.0",
"express": "^4.16.4",
"lolex": "^3.1.0",
"mocha": "^6.0.2",
"nyc": "^14.1.1"
},
"engines": {
"node": ">=4.0"
},
"files": [
"*.js"
],
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"homepage": "https://github.com/follow-redirects/follow-redirects",
"keywords": [
"http",
"https",
"url",
"redirect",
"client",
"location",
"utility"
],
"license": "MIT",
"main": "index.js",
"name": "follow-redirects",
"peerDependenciesMeta": {
"debug": {
"optional": true
}
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/follow-redirects/follow-redirects.git"
},
"scripts": {
"lint": "eslint *.js test",
"mocha": "nyc mocha",
"test": "npm run lint && npm run mocha"
},
"version": "1.13.2"
}

@ -1,31 +1,27 @@
{ {
"_args": [ "_from": "axios@^0.19.2",
[ "_id": "axios@0.19.2",
"axios@0.21.1",
"/home/sigonasr2/divar/server"
]
],
"_from": "axios@0.21.1",
"_id": "axios@0.21.1",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA==", "_integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==",
"_location": "/axios", "_location": "/axios",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "range",
"registry": true, "registry": true,
"raw": "axios@0.21.1", "raw": "axios@^0.19.2",
"name": "axios", "name": "axios",
"escapedName": "axios", "escapedName": "axios",
"rawSpec": "0.21.1", "rawSpec": "^0.19.2",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "0.21.1" "fetchSpec": "^0.19.2"
}, },
"_requiredBy": [ "_requiredBy": [
"#USER",
"/" "/"
], ],
"_resolved": "https://registry.npmjs.org/axios/-/axios-0.21.1.tgz", "_resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz",
"_spec": "0.21.1", "_shasum": "3ea36c5d8818d0d5f8a8a97a6d36b86cdc00cb27",
"_spec": "axios@^0.19.2",
"_where": "/home/sigonasr2/divar/server", "_where": "/home/sigonasr2/divar/server",
"author": { "author": {
"name": "Matt Zabriskie" "name": "Matt Zabriskie"
@ -36,6 +32,7 @@
"bugs": { "bugs": {
"url": "https://github.com/axios/axios/issues" "url": "https://github.com/axios/axios/issues"
}, },
"bundleDependencies": false,
"bundlesize": [ "bundlesize": [
{ {
"path": "./dist/axios.min.js", "path": "./dist/axios.min.js",
@ -43,8 +40,9 @@
} }
], ],
"dependencies": { "dependencies": {
"follow-redirects": "^1.10.0" "follow-redirects": "1.5.10"
}, },
"deprecated": false,
"description": "Promise based HTTP client for the browser and node.js", "description": "Promise based HTTP client for the browser and node.js",
"devDependencies": { "devDependencies": {
"bundlesize": "^0.17.0", "bundlesize": "^0.17.0",
@ -84,7 +82,6 @@
"webpack-dev-server": "^1.14.1" "webpack-dev-server": "^1.14.1"
}, },
"homepage": "https://github.com/axios/axios", "homepage": "https://github.com/axios/axios",
"jsdelivr": "dist/axios.min.js",
"keywords": [ "keywords": [
"xhr", "xhr",
"http", "http",
@ -111,6 +108,5 @@
"version": "npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json" "version": "npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json"
}, },
"typings": "./index.d.ts", "typings": "./index.d.ts",
"unpkg": "dist/axios.min.js", "version": "0.19.2"
"version": "0.21.1"
} }

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2013-2018 Petka Antonov Copyright (c) 2013-2015 Petka Antonov
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

@ -2,10 +2,8 @@
<img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo" <img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo"
title="Promises/A+ 1.1 compliant" align="right" /> title="Promises/A+ 1.1 compliant" align="right" />
</a> </a>
[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) [![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
[![coverage-98%](https://img.shields.io/badge/coverage-98%25-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) [![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) **Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises)
@ -17,10 +15,6 @@ See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html)
For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x). For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x).
### Note
Promises in Node.js 10 are significantly faster than before. Bluebird still includes a lot of features like cancellation, iteration methods and warnings that native promises don't. If you are using Bluebird for performance rather than for those - please consider giving native promises a shot and running the benchmarks yourself.
# Questions and issues # Questions and issues
The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`.
@ -35,7 +29,7 @@ Thanks to BrowserStack for providing us with a free account which lets us suppor
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2013-2019 Petka Antonov Copyright (c) 2013-2016 Petka Antonov
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

@ -1,7 +1,7 @@
/* @preserve /* @preserve
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2013-2018 Petka Antonov * Copyright (c) 2013-2015 Petka Antonov
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@ -23,7 +23,7 @@
* *
*/ */
/** /**
* bluebird build version 3.7.2 * bluebird build version 3.4.7
* Features enabled: core * Features enabled: core
* Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
*/ */
@ -33,6 +33,7 @@ var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;} try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = _dereq_("./schedule"); var schedule = _dereq_("./schedule");
var Queue = _dereq_("./queue"); var Queue = _dereq_("./queue");
var util = _dereq_("./util");
function Async() { function Async() {
this._customScheduler = false; this._customScheduler = false;
@ -40,6 +41,7 @@ function Async() {
this._lateQueue = new Queue(16); this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16); this._normalQueue = new Queue(16);
this._haveDrainedQueues = false; this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this; var self = this;
this.drainQueues = function () { this.drainQueues = function () {
self._drainQueues(); self._drainQueues();
@ -58,6 +60,16 @@ Async.prototype.hasCustomScheduler = function() {
return this._customScheduler; return this._customScheduler;
}; };
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () { Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues; return this._isTickUsed || this._haveDrainedQueues;
}; };
@ -106,33 +118,62 @@ function AsyncSettlePromises(promise) {
this._queueTick(); this._queueTick();
} }
Async.prototype.invokeLater = AsyncInvokeLater; if (!util.hasDevTools) {
Async.prototype.invoke = AsyncInvoke; Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.settlePromises = AsyncSettlePromises; Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
function _drainQueue(queue) { Async.prototype.settlePromises = function(promise) {
while (queue.length() > 0) { if (this._trampolineEnabled) {
_drainQueueStep(queue); AsyncSettlePromises.call(this, promise);
} } else {
this._schedule(function() {
promise._settlePromises();
});
}
};
} }
function _drainQueueStep(queue) { Async.prototype._drainQueue = function(queue) {
var fn = queue.shift(); while (queue.length() > 0) {
if (typeof fn !== "function") { var fn = queue.shift();
fn._settlePromises(); if (typeof fn !== "function") {
} else { fn._settlePromises();
continue;
}
var receiver = queue.shift(); var receiver = queue.shift();
var arg = queue.shift(); var arg = queue.shift();
fn.call(receiver, arg); fn.call(receiver, arg);
} }
} };
Async.prototype._drainQueues = function () { Async.prototype._drainQueues = function () {
_drainQueue(this._normalQueue); this._drainQueue(this._normalQueue);
this._reset(); this._reset();
this._haveDrainedQueues = true; this._haveDrainedQueues = true;
_drainQueue(this._lateQueue); this._drainQueue(this._lateQueue);
}; };
Async.prototype._queueTick = function () { Async.prototype._queueTick = function () {
@ -149,7 +190,7 @@ Async.prototype._reset = function () {
module.exports = Async; module.exports = Async;
module.exports.firstLineError = firstLineError; module.exports.firstLineError = firstLineError;
},{"./queue":17,"./schedule":18}],2:[function(_dereq_,module,exports){ },{"./queue":17,"./schedule":18,"./util":21}],2:[function(_dereq_,module,exports){
"use strict"; "use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false; var calledBind = false;
@ -479,12 +520,11 @@ return Context;
},{}],7:[function(_dereq_,module,exports){ },{}],7:[function(_dereq_,module,exports){
"use strict"; "use strict";
module.exports = function(Promise, Context, module.exports = function(Promise, Context) {
enableAsyncHooks, disableAsyncHooks) { var getDomain = Promise._getDomain;
var async = Promise._async; var async = Promise._async;
var Warning = _dereq_("./errors").Warning; var Warning = _dereq_("./errors").Warning;
var util = _dereq_("./util"); var util = _dereq_("./util");
var es5 = _dereq_("./es5");
var canAttachTrace = util.canAttachTrace; var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled; var unhandledRejectionHandled;
var possiblyUnhandledRejection; var possiblyUnhandledRejection;
@ -510,34 +550,6 @@ var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
var deferUnhandledRejectionCheck;
(function() {
var promises = [];
function unhandledRejectionCheck() {
for (var i = 0; i < promises.length; ++i) {
promises[i]._notifyUnhandledRejection();
}
unhandledRejectionClear();
}
function unhandledRejectionClear() {
promises.length = 0;
}
deferUnhandledRejectionCheck = function(promise) {
promises.push(promise);
setTimeout(unhandledRejectionCheck, 1);
};
es5.defineProperty(Promise, "_unhandledRejectionCheck", {
value: unhandledRejectionCheck
});
es5.defineProperty(Promise, "_unhandledRejectionClear", {
value: unhandledRejectionClear
});
})();
Promise.prototype.suppressUnhandledRejections = function() { Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target(); var target = this._target();
target._bitField = ((target._bitField & (~1048576)) | target._bitField = ((target._bitField & (~1048576)) |
@ -547,7 +559,7 @@ Promise.prototype.suppressUnhandledRejections = function() {
Promise.prototype._ensurePossibleRejectionHandled = function () { Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return; if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled(); this._setRejectionIsUnhandled();
deferUnhandledRejectionCheck(this); async.invokeLater(this._notifyUnhandledRejection, this, undefined);
}; };
Promise.prototype._notifyUnhandledRejectionIsHandled = function () { Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
@ -605,13 +617,19 @@ Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
}; };
Promise.onPossiblyUnhandledRejection = function (fn) { Promise.onPossiblyUnhandledRejection = function (fn) {
var context = Promise._getContext(); var domain = getDomain();
possiblyUnhandledRejection = util.contextBind(context, fn); possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
}; };
Promise.onUnhandledRejectionHandled = function (fn) { Promise.onUnhandledRejectionHandled = function (fn) {
var context = Promise._getContext(); var domain = getDomain();
unhandledRejectionHandled = util.contextBind(context, fn); unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
}; };
var disableLongStackTraces = function() {}; var disableLongStackTraces = function() {};
@ -622,7 +640,6 @@ Promise.longStackTraces = function () {
if (!config.longStackTraces && longStackTracesIsSupported()) { if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
config.longStackTraces = true; config.longStackTraces = true;
disableLongStackTraces = function() { disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) { if (async.haveItemsQueued() && !config.longStackTraces) {
@ -630,14 +647,14 @@ Promise.longStackTraces = function () {
} }
Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
Context.deactivateLongStackTraces(); Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false; config.longStackTraces = false;
}; };
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
Context.activateLongStackTraces(); Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
} }
}; };
@ -645,85 +662,37 @@ Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported(); return config.longStackTraces && longStackTracesIsSupported();
}; };
var legacyHandlers = {
unhandledrejection: {
before: function() {
var ret = util.global.onunhandledrejection;
util.global.onunhandledrejection = null;
return ret;
},
after: function(fn) {
util.global.onunhandledrejection = fn;
}
},
rejectionhandled: {
before: function() {
var ret = util.global.onrejectionhandled;
util.global.onrejectionhandled = null;
return ret;
},
after: function(fn) {
util.global.onrejectionhandled = fn;
}
}
};
var fireDomEvent = (function() { var fireDomEvent = (function() {
var dispatch = function(legacy, e) {
if (legacy) {
var fn;
try {
fn = legacy.before();
return !util.global.dispatchEvent(e);
} finally {
legacy.after(fn);
}
} else {
return !util.global.dispatchEvent(e);
}
};
try { try {
if (typeof CustomEvent === "function") { if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent"); var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event); util.global.dispatchEvent(event);
return function(name, event) { return function(name, event) {
name = name.toLowerCase(); var domEvent = new CustomEvent(name.toLowerCase(), {
var eventData = {
detail: event, detail: event,
cancelable: true cancelable: true
}; });
var domEvent = new CustomEvent(name, eventData); return !util.global.dispatchEvent(domEvent);
es5.defineProperty(
domEvent, "promise", {value: event.promise});
es5.defineProperty(
domEvent, "reason", {value: event.reason});
return dispatch(legacyHandlers[name], domEvent);
}; };
} else if (typeof Event === "function") { } else if (typeof Event === "function") {
var event = new Event("CustomEvent"); var event = new Event("CustomEvent");
util.global.dispatchEvent(event); util.global.dispatchEvent(event);
return function(name, event) { return function(name, event) {
name = name.toLowerCase(); var domEvent = new Event(name.toLowerCase(), {
var domEvent = new Event(name, {
cancelable: true cancelable: true
}); });
domEvent.detail = event; domEvent.detail = event;
es5.defineProperty(domEvent, "promise", {value: event.promise}); return !util.global.dispatchEvent(domEvent);
es5.defineProperty(domEvent, "reason", {value: event.reason});
return dispatch(legacyHandlers[name], domEvent);
}; };
} else { } else {
var event = document.createEvent("CustomEvent"); var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {}); event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event); util.global.dispatchEvent(event);
return function(name, event) { return function(name, event) {
name = name.toLowerCase();
var domEvent = document.createEvent("CustomEvent"); var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name, false, true, domEvent.initCustomEvent(name.toLowerCase(), false, true,
event); event);
return dispatch(legacyHandlers[name], domEvent); return !util.global.dispatchEvent(domEvent);
}; };
} }
} catch (e) {} } catch (e) {}
@ -841,18 +810,6 @@ Promise.config = function(opts) {
Promise.prototype._fireEvent = defaultFireEvent; Promise.prototype._fireEvent = defaultFireEvent;
} }
} }
if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) {
var prev = config.asyncHooks;
var cur = !!opts.asyncHooks;
if (prev !== cur) {
config.asyncHooks = cur;
if (cur) {
enableAsyncHooks();
} else {
disableAsyncHooks();
}
}
}
return Promise; return Promise;
}; };
@ -873,7 +830,6 @@ Promise.prototype._attachCancellationCallback = function(onCancel) {
}; };
Promise.prototype._captureStackTrace = function () {}; Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._dereferenceTrace = function () {};
Promise.prototype._clearCancellationData = function() {}; Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) { Promise.prototype._propagateFrom = function (parent, flags) {
; ;
@ -979,10 +935,6 @@ function longStackTracesAttachExtraTrace(error, ignoreSelf) {
} }
} }
function longStackTracesDereferenceTrace() {
this._trace = undefined;
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise, function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) { parent) {
if (returnValue === undefined && promiseCreated !== null && if (returnValue === undefined && promiseCreated !== null &&
@ -1240,8 +1192,8 @@ function parseLineInfo(line) {
function setBounds(firstLineError, lastLineError) { function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return; if (!longStackTracesIsSupported()) return;
var firstStackLines = (firstLineError.stack || "").split("\n"); var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = (lastLineError.stack || "").split("\n"); var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1; var firstIndex = -1;
var lastIndex = -1; var lastIndex = -1;
var firstFileName; var firstFileName;
@ -1450,16 +1402,12 @@ var config = {
warnings: warnings, warnings: warnings,
longStackTraces: false, longStackTraces: false,
cancellation: false, cancellation: false,
monitoring: false, monitoring: false
asyncHooks: false
}; };
if (longStackTraces) Promise.longStackTraces(); if (longStackTraces) Promise.longStackTraces();
return { return {
asyncHooks: function() {
return config.asyncHooks;
},
longStackTraces: function() { longStackTraces: function() {
return config.longStackTraces; return config.longStackTraces;
}, },
@ -1488,7 +1436,7 @@ return {
}; };
}; };
},{"./errors":9,"./es5":10,"./util":21}],8:[function(_dereq_,module,exports){ },{"./errors":9,"./util":21}],8:[function(_dereq_,module,exports){
"use strict"; "use strict";
module.exports = function(Promise) { module.exports = function(Promise) {
function returner() { function returner() {
@ -1738,11 +1686,10 @@ if (isES5) {
},{}],11:[function(_dereq_,module,exports){ },{}],11:[function(_dereq_,module,exports){
"use strict"; "use strict";
module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { module.exports = function(Promise, tryConvertToPromise) {
var util = _dereq_("./util"); var util = _dereq_("./util");
var CancellationError = Promise.CancellationError; var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj; var errorObj = util.errorObj;
var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
function PassThroughHandlerContext(promise, type, handler) { function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise; this.promise = promise;
@ -1794,9 +1741,7 @@ function finallyHandler(reasonOrValue) {
var ret = this.isFinallyHandler() var ret = this.isFinallyHandler()
? handler.call(promise._boundValue()) ? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue); : handler.call(promise._boundValue(), reasonOrValue);
if (ret === NEXT_FILTER) { if (ret !== undefined) {
return ret;
} else if (ret !== undefined) {
promise._setReturnedNonUndefined(); promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise); var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) { if (maybePromise instanceof Promise) {
@ -1845,49 +1790,18 @@ Promise.prototype["finally"] = function (handler) {
finallyHandler); finallyHandler);
}; };
Promise.prototype.tap = function (handler) { Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler); return this._passThrough(handler, 1, finallyHandler);
}; };
Promise.prototype.tapCatch = function (handlerOrPredicate) {
var len = arguments.length;
if(len === 1) {
return this._passThrough(handlerOrPredicate,
1,
undefined,
finallyHandler);
} else {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return Promise.reject(new TypeError(
"tapCatch statement predicate: "
+ "expecting an object but got " + util.classString(item)
));
}
}
catchInstances.length = j;
var handler = arguments[i];
return this._passThrough(catchFilter(catchInstances, handler, this),
1,
undefined,
finallyHandler);
}
};
return PassThroughHandlerContext; return PassThroughHandlerContext;
}; };
},{"./catch_filter":5,"./util":21}],12:[function(_dereq_,module,exports){ },{"./util":21}],12:[function(_dereq_,module,exports){
"use strict"; "use strict";
module.exports = module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
getDomain) {
var util = _dereq_("./util"); var util = _dereq_("./util");
var canEvaluate = util.canEvaluate; var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch; var tryCatch = util.tryCatch;
@ -2033,8 +1947,10 @@ Promise.join = function () {
if (!ret._isFateSealed()) { if (!ret._isFateSealed()) {
if (holder.asyncNeeded) { if (holder.asyncNeeded) {
var context = Promise._getContext(); var domain = getDomain();
holder.fn = util.contextBind(context, holder.fn); if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
} }
ret._setAsyncGuaranteed(); ret._setAsyncGuaranteed();
ret._setOnCancel(holder); ret._setOnCancel(holder);
@ -2176,42 +2092,20 @@ var apiRejection = function(msg) {
function Proxyable() {} function Proxyable() {}
var UNDEFINED_BINDING = {}; var UNDEFINED_BINDING = {};
var util = _dereq_("./util"); var util = _dereq_("./util");
util.setReflectHandler(reflectHandler);
var getDomain = function() { var getDomain;
var domain = process.domain; if (util.isNode) {
if (domain === undefined) { getDomain = function() {
return null; var ret = process.domain;
} if (ret === undefined) ret = null;
return domain; return ret;
};
var getContextDefault = function() {
return null;
};
var getContextDomain = function() {
return {
domain: getDomain(),
async: null
}; };
}; } else {
var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? getDomain = function() {
_dereq_("async_hooks").AsyncResource : null; return null;
var getContextAsyncHooks = function() {
return {
domain: getDomain(),
async: new AsyncResource("Bluebird::Promise")
}; };
}; }
var getContext = util.isNode ? getContextDomain : getContextDefault; util.notEnumerableProp(Promise, "_getDomain", getDomain);
util.notEnumerableProp(Promise, "_getContext", getContext);
var enableAsyncHooks = function() {
getContext = getContextAsyncHooks;
util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks);
};
var disableAsyncHooks = function() {
getContext = getContextDomain;
util.notEnumerableProp(Promise, "_getContext", getContextDomain);
};
var es5 = _dereq_("./es5"); var es5 = _dereq_("./es5");
var Async = _dereq_("./async"); var Async = _dereq_("./async");
@ -2235,36 +2129,33 @@ var PromiseArray =
var Context = _dereq_("./context")(Promise); var Context = _dereq_("./context")(Promise);
/*jshint unused:false*/ /*jshint unused:false*/
var createContext = Context.create; var createContext = Context.create;
var debug = _dereq_("./debuggability")(Promise, Context);
var debug = _dereq_("./debuggability")(Promise, Context,
enableAsyncHooks, disableAsyncHooks);
var CapturedTrace = debug.CapturedTrace; var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext = var PassThroughHandlerContext =
_dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); _dereq_("./finally")(Promise, tryConvertToPromise);
var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = _dereq_("./nodeback"); var nodebackForPromise = _dereq_("./nodeback");
var errorObj = util.errorObj; var errorObj = util.errorObj;
var tryCatch = util.tryCatch; var tryCatch = util.tryCatch;
function check(self, executor) { function check(self, executor) {
if (self == null || self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (typeof executor !== "function") { if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor)); throw new TypeError("expecting a function but got " + util.classString(executor));
} }
if (self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
} }
function Promise(executor) { function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0; this._bitField = 0;
this._fulfillmentHandler0 = undefined; this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined; this._rejectionHandler0 = undefined;
this._promise0 = undefined; this._promise0 = undefined;
this._receiver0 = undefined; this._receiver0 = undefined;
this._resolveFromExecutor(executor); if (executor !== INTERNAL) {
check(this, executor);
this._resolveFromExecutor(executor);
}
this._promiseCreated(); this._promiseCreated();
this._fireEvent("promiseCreated", this); this._fireEvent("promiseCreated", this);
} }
@ -2283,17 +2174,12 @@ Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
if (util.isObject(item)) { if (util.isObject(item)) {
catchInstances[j++] = item; catchInstances[j++] = item;
} else { } else {
return apiRejection("Catch statement predicate: " + return apiRejection("expecting an object but got " +
"expecting an object but got " + util.classString(item)); "A catch statement predicate " + util.classString(item));
} }
} }
catchInstances.length = j; catchInstances.length = j;
fn = arguments[i]; fn = arguments[i];
if (typeof fn !== "function") {
throw new TypeError("The last argument to .catch() " +
"must be a function, got " + util.toString(fn));
}
return this.then(undefined, catchFilter(catchInstances, fn, this)); return this.then(undefined, catchFilter(catchInstances, fn, this));
} }
return this.then(undefined, fn); return this.then(undefined, fn);
@ -2434,7 +2320,7 @@ Promise.prototype._then = function (
this._fireEvent("promiseChained", this, promise); this._fireEvent("promiseChained", this, promise);
} }
var context = getContext(); var domain = getDomain();
if (!((bitField & 50397184) === 0)) { if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx; var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) { if (((bitField & 33554432) !== 0)) {
@ -2452,14 +2338,15 @@ Promise.prototype._then = function (
} }
async.invoke(settler, target, { async.invoke(settler, target, {
handler: util.contextBind(context, handler), handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
promise: promise, promise: promise,
receiver: receiver, receiver: receiver,
value: value value: value
}); });
} else { } else {
target._addCallbacks(didFulfill, didReject, promise, target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
receiver, context);
} }
return promise; return promise;
@ -2520,15 +2407,7 @@ Promise.prototype._setWillBeCancelled = function() {
Promise.prototype._setAsyncGuaranteed = function() { Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return; if (async.hasCustomScheduler()) return;
var bitField = this._bitField; this._bitField = this._bitField | 134217728;
this._bitField = bitField |
(((bitField & 536870912) >> 2) ^
134217728);
};
Promise.prototype._setNoAsyncGuarantee = function() {
this._bitField = (this._bitField | 536870912) &
(~134217728);
}; };
Promise.prototype._receiverAt = function (index) { Promise.prototype._receiverAt = function (index) {
@ -2583,7 +2462,7 @@ Promise.prototype._addCallbacks = function (
reject, reject,
promise, promise,
receiver, receiver,
context domain
) { ) {
var index = this._length(); var index = this._length();
@ -2596,10 +2475,12 @@ Promise.prototype._addCallbacks = function (
this._promise0 = promise; this._promise0 = promise;
this._receiver0 = receiver; this._receiver0 = receiver;
if (typeof fulfill === "function") { if (typeof fulfill === "function") {
this._fulfillmentHandler0 = util.contextBind(context, fulfill); this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
} }
if (typeof reject === "function") { if (typeof reject === "function") {
this._rejectionHandler0 = util.contextBind(context, reject); this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
} }
} else { } else {
var base = index * 4 - 4; var base = index * 4 - 4;
@ -2607,11 +2488,11 @@ Promise.prototype._addCallbacks = function (
this[base + 3] = receiver; this[base + 3] = receiver;
if (typeof fulfill === "function") { if (typeof fulfill === "function") {
this[base + 0] = this[base + 0] =
util.contextBind(context, fulfill); domain === null ? fulfill : util.domainBind(domain, fulfill);
} }
if (typeof reject === "function") { if (typeof reject === "function") {
this[base + 1] = this[base + 1] =
util.contextBind(context, reject); domain === null ? reject : util.domainBind(domain, reject);
} }
} }
this._setLength(index + 1); this._setLength(index + 1);
@ -2631,7 +2512,6 @@ Promise.prototype._resolveCallback = function(value, shouldBind) {
if (shouldBind) this._propagateFrom(maybePromise, 2); if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target(); var promise = maybePromise._target();
if (promise === this) { if (promise === this) {
@ -2648,7 +2528,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) {
} }
this._setFollowing(); this._setFollowing();
this._setLength(0); this._setLength(0);
this._setFollowee(maybePromise); this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) { } else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value()); this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) { } else if (((bitField & 16777216) !== 0)) {
@ -2674,7 +2554,6 @@ function(reason, synchronous, ignoreNonErrorWarnings) {
}; };
Promise.prototype._resolveFromExecutor = function (executor) { Promise.prototype._resolveFromExecutor = function (executor) {
if (executor === INTERNAL) return;
var promise = this; var promise = this;
this._captureStackTrace(); this._captureStackTrace();
this._pushContext(); this._pushContext();
@ -2838,7 +2717,6 @@ Promise.prototype._fulfill = function (value) {
} else { } else {
async.settlePromises(this); async.settlePromises(this);
} }
this._dereferenceTrace();
} }
}; };
@ -2907,14 +2785,6 @@ Promise.prototype._settledValue = function() {
} }
}; };
if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
get: function () {
return "Object";
}
});
}
function deferResolve(v) {this.promise._resolveCallback(v);} function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);} function deferReject(v) {this.promise._rejectCallback(v, false);}
@ -2939,9 +2809,9 @@ _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
_dereq_("./direct_resolve")(Promise); _dereq_("./direct_resolve")(Promise);
_dereq_("./synchronous_inspection")(Promise); _dereq_("./synchronous_inspection")(Promise);
_dereq_("./join")( _dereq_("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise.Promise = Promise; Promise.Promise = Promise;
Promise.version = "3.7.2"; Promise.version = "3.4.7";
util.toFastProperties(Promise); util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype); util.toFastProperties(Promise.prototype);
@ -2967,7 +2837,7 @@ Promise.version = "3.7.2";
}; };
},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21,"async_hooks":undefined}],16:[function(_dereq_,module,exports){ },{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(_dereq_,module,exports){
"use strict"; "use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection, Proxyable) { apiRejection, Proxyable) {
@ -2978,7 +2848,6 @@ function toResolutionValue(val) {
switch(val) { switch(val) {
case -2: return []; case -2: return [];
case -3: return {}; case -3: return {};
case -6: return new Map();
} }
} }
@ -2986,7 +2855,6 @@ function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL); var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) { if (values instanceof Promise) {
promise._propagateFrom(values, 3); promise._propagateFrom(values, 3);
values.suppressUnhandledRejections();
} }
promise._setOnCancel(this); promise._setOnCancel(this);
this._values = values; this._values = values;
@ -3253,8 +3121,7 @@ if (util.isNode && typeof MutationObserver === "undefined") {
} else if ((typeof MutationObserver !== "undefined") && } else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" && !(typeof window !== "undefined" &&
window.navigator && window.navigator &&
(window.navigator.standalone || window.cordova)) && (window.navigator.standalone || window.cordova))) {
("classList" in document.documentElement)) {
schedule = (function() { schedule = (function() {
var div = document.createElement("div"); var div = document.createElement("div");
var opts = {attributes: true}; var opts = {attributes: true};
@ -3268,11 +3135,11 @@ if (util.isNode && typeof MutationObserver === "undefined") {
var scheduleToggle = function() { var scheduleToggle = function() {
if (toggleScheduled) return; if (toggleScheduled) return;
toggleScheduled = true; toggleScheduled = true;
div2.classList.toggle("foo"); div2.classList.toggle("foo");
}; };
return function schedule(fn) { return function schedule(fn) {
var o = new MutationObserver(function() { var o = new MutationObserver(function() {
o.disconnect(); o.disconnect();
fn(); fn();
@ -3685,12 +3552,8 @@ function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/ /*jshint -W027,-W055,-W031*/
function FakeConstructor() {} function FakeConstructor() {}
FakeConstructor.prototype = obj; FakeConstructor.prototype = obj;
var receiver = new FakeConstructor(); var l = 8;
function ic() { while (l--) new FakeConstructor();
return typeof receiver.foo;
}
ic();
ic();
return obj; return obj;
eval(obj); eval(obj);
} }
@ -3717,11 +3580,10 @@ function safeToString(obj) {
} }
function isError(obj) { function isError(obj) {
return obj instanceof Error || return obj !== null &&
(obj !== null &&
typeof obj === "object" && typeof obj === "object" &&
typeof obj.message === "string" && typeof obj.message === "string" &&
typeof obj.name === "string"); typeof obj.name === "string";
} }
function markAsOriginatingFromRejection(e) { function markAsOriginatingFromRejection(e) {
@ -3816,42 +3678,18 @@ function getNativePromise() {
if (typeof Promise === "function") { if (typeof Promise === "function") {
try { try {
var promise = new Promise(function(){}); var promise = new Promise(function(){});
if (classString(promise) === "[object Promise]") { if ({}.toString.call(promise) === "[object Promise]") {
return Promise; return Promise;
} }
} catch (e) {} } catch (e) {}
} }
} }
var reflectHandler; function domainBind(self, cb) {
function contextBind(ctx, cb) { return self.bind(cb);
if (ctx === null ||
typeof cb !== "function" ||
cb === reflectHandler) {
return cb;
}
if (ctx.domain !== null) {
cb = ctx.domain.bind(cb);
}
var async = ctx.async;
if (async !== null) {
var old = cb;
cb = function() {
var args = (new Array(2)).concat([].slice.call(arguments));;
args[0] = old;
args[1] = this;
return async.runInAsyncScope.apply(async, args);
};
}
return cb;
} }
var ret = { var ret = {
setReflectHandler: function(fn) {
reflectHandler = fn;
},
isClass: isClass, isClass: isClass,
isIdentifier: isIdentifier, isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys, inheritedDataKeys: inheritedDataKeys,
@ -3878,37 +3716,24 @@ var ret = {
markAsOriginatingFromRejection: markAsOriginatingFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString, classString: classString,
copyDescriptors: copyDescriptors, copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: isNode, isNode: isNode,
hasEnvVariables: hasEnvVariables, hasEnvVariables: hasEnvVariables,
env: env, env: env,
global: globalObject, global: globalObject,
getNativePromise: getNativePromise, getNativePromise: getNativePromise,
contextBind: contextBind domainBind: domainBind
}; };
ret.isRecentNode = ret.isNode && (function() { ret.isRecentNode = ret.isNode && (function() {
var version; var version = process.versions.node.split(".").map(Number);
if (process.versions && process.versions.node) {
version = process.versions.node.split(".").map(Number);
} else if (process.version) {
version = process.version.split(".").map(Number);
}
return (version[0] === 0 && version[1] > 10) || (version[0] > 0); return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})(); })();
ret.nodeSupportsAsyncResource = ret.isNode && (function() {
var supportsAsync = false;
try {
var res = _dereq_("async_hooks").AsyncResource;
supportsAsync = typeof res.prototype.runInAsyncScope === "function";
} catch (e) {
supportsAsync = false;
}
return supportsAsync;
})();
if (ret.isNode) ret.toFastProperties(process); if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;} try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret; module.exports = ret;
},{"./es5":10,"async_hooks":undefined}]},{},[3])(3) },{"./es5":10}]},{},[3])(3)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -3,6 +3,7 @@ var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;} try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = require("./schedule"); var schedule = require("./schedule");
var Queue = require("./queue"); var Queue = require("./queue");
var util = require("./util");
function Async() { function Async() {
this._customScheduler = false; this._customScheduler = false;
@ -10,6 +11,7 @@ function Async() {
this._lateQueue = new Queue(16); this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16); this._normalQueue = new Queue(16);
this._haveDrainedQueues = false; this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this; var self = this;
this.drainQueues = function () { this.drainQueues = function () {
self._drainQueues(); self._drainQueues();
@ -28,6 +30,16 @@ Async.prototype.hasCustomScheduler = function() {
return this._customScheduler; return this._customScheduler;
}; };
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () { Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues; return this._isTickUsed || this._haveDrainedQueues;
}; };
@ -76,33 +88,62 @@ function AsyncSettlePromises(promise) {
this._queueTick(); this._queueTick();
} }
Async.prototype.invokeLater = AsyncInvokeLater; if (!util.hasDevTools) {
Async.prototype.invoke = AsyncInvoke; Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.settlePromises = AsyncSettlePromises; Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
function _drainQueue(queue) { Async.prototype.settlePromises = function(promise) {
while (queue.length() > 0) { if (this._trampolineEnabled) {
_drainQueueStep(queue); AsyncSettlePromises.call(this, promise);
} } else {
this._schedule(function() {
promise._settlePromises();
});
}
};
} }
function _drainQueueStep(queue) { Async.prototype._drainQueue = function(queue) {
var fn = queue.shift(); while (queue.length() > 0) {
if (typeof fn !== "function") { var fn = queue.shift();
fn._settlePromises(); if (typeof fn !== "function") {
} else { fn._settlePromises();
continue;
}
var receiver = queue.shift(); var receiver = queue.shift();
var arg = queue.shift(); var arg = queue.shift();
fn.call(receiver, arg); fn.call(receiver, arg);
} }
} };
Async.prototype._drainQueues = function () { Async.prototype._drainQueues = function () {
_drainQueue(this._normalQueue); this._drainQueue(this._normalQueue);
this._reset(); this._reset();
this._haveDrainedQueues = true; this._haveDrainedQueues = true;
_drainQueue(this._lateQueue); this._drainQueue(this._lateQueue);
}; };
Async.prototype._queueTick = function () { Async.prototype._queueTick = function () {

@ -1,10 +1,9 @@
"use strict"; "use strict";
module.exports = function(Promise, Context, module.exports = function(Promise, Context) {
enableAsyncHooks, disableAsyncHooks) { var getDomain = Promise._getDomain;
var async = Promise._async; var async = Promise._async;
var Warning = require("./errors").Warning; var Warning = require("./errors").Warning;
var util = require("./util"); var util = require("./util");
var es5 = require("./es5");
var canAttachTrace = util.canAttachTrace; var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled; var unhandledRejectionHandled;
var possiblyUnhandledRejection; var possiblyUnhandledRejection;
@ -30,34 +29,6 @@ var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
var deferUnhandledRejectionCheck;
(function() {
var promises = [];
function unhandledRejectionCheck() {
for (var i = 0; i < promises.length; ++i) {
promises[i]._notifyUnhandledRejection();
}
unhandledRejectionClear();
}
function unhandledRejectionClear() {
promises.length = 0;
}
deferUnhandledRejectionCheck = function(promise) {
promises.push(promise);
setTimeout(unhandledRejectionCheck, 1);
};
es5.defineProperty(Promise, "_unhandledRejectionCheck", {
value: unhandledRejectionCheck
});
es5.defineProperty(Promise, "_unhandledRejectionClear", {
value: unhandledRejectionClear
});
})();
Promise.prototype.suppressUnhandledRejections = function() { Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target(); var target = this._target();
target._bitField = ((target._bitField & (~1048576)) | target._bitField = ((target._bitField & (~1048576)) |
@ -67,7 +38,7 @@ Promise.prototype.suppressUnhandledRejections = function() {
Promise.prototype._ensurePossibleRejectionHandled = function () { Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return; if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled(); this._setRejectionIsUnhandled();
deferUnhandledRejectionCheck(this); async.invokeLater(this._notifyUnhandledRejection, this, undefined);
}; };
Promise.prototype._notifyUnhandledRejectionIsHandled = function () { Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
@ -125,13 +96,19 @@ Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
}; };
Promise.onPossiblyUnhandledRejection = function (fn) { Promise.onPossiblyUnhandledRejection = function (fn) {
var context = Promise._getContext(); var domain = getDomain();
possiblyUnhandledRejection = util.contextBind(context, fn); possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
}; };
Promise.onUnhandledRejectionHandled = function (fn) { Promise.onUnhandledRejectionHandled = function (fn) {
var context = Promise._getContext(); var domain = getDomain();
unhandledRejectionHandled = util.contextBind(context, fn); unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
}; };
var disableLongStackTraces = function() {}; var disableLongStackTraces = function() {};
@ -142,7 +119,6 @@ Promise.longStackTraces = function () {
if (!config.longStackTraces && longStackTracesIsSupported()) { if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
config.longStackTraces = true; config.longStackTraces = true;
disableLongStackTraces = function() { disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) { if (async.haveItemsQueued() && !config.longStackTraces) {
@ -150,14 +126,14 @@ Promise.longStackTraces = function () {
} }
Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
Context.deactivateLongStackTraces(); Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false; config.longStackTraces = false;
}; };
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
Context.activateLongStackTraces(); Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
} }
}; };
@ -165,85 +141,37 @@ Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported(); return config.longStackTraces && longStackTracesIsSupported();
}; };
var legacyHandlers = {
unhandledrejection: {
before: function() {
var ret = util.global.onunhandledrejection;
util.global.onunhandledrejection = null;
return ret;
},
after: function(fn) {
util.global.onunhandledrejection = fn;
}
},
rejectionhandled: {
before: function() {
var ret = util.global.onrejectionhandled;
util.global.onrejectionhandled = null;
return ret;
},
after: function(fn) {
util.global.onrejectionhandled = fn;
}
}
};
var fireDomEvent = (function() { var fireDomEvent = (function() {
var dispatch = function(legacy, e) {
if (legacy) {
var fn;
try {
fn = legacy.before();
return !util.global.dispatchEvent(e);
} finally {
legacy.after(fn);
}
} else {
return !util.global.dispatchEvent(e);
}
};
try { try {
if (typeof CustomEvent === "function") { if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent"); var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event); util.global.dispatchEvent(event);
return function(name, event) { return function(name, event) {
name = name.toLowerCase(); var domEvent = new CustomEvent(name.toLowerCase(), {
var eventData = {
detail: event, detail: event,
cancelable: true cancelable: true
}; });
var domEvent = new CustomEvent(name, eventData); return !util.global.dispatchEvent(domEvent);
es5.defineProperty(
domEvent, "promise", {value: event.promise});
es5.defineProperty(
domEvent, "reason", {value: event.reason});
return dispatch(legacyHandlers[name], domEvent);
}; };
} else if (typeof Event === "function") { } else if (typeof Event === "function") {
var event = new Event("CustomEvent"); var event = new Event("CustomEvent");
util.global.dispatchEvent(event); util.global.dispatchEvent(event);
return function(name, event) { return function(name, event) {
name = name.toLowerCase(); var domEvent = new Event(name.toLowerCase(), {
var domEvent = new Event(name, {
cancelable: true cancelable: true
}); });
domEvent.detail = event; domEvent.detail = event;
es5.defineProperty(domEvent, "promise", {value: event.promise}); return !util.global.dispatchEvent(domEvent);
es5.defineProperty(domEvent, "reason", {value: event.reason});
return dispatch(legacyHandlers[name], domEvent);
}; };
} else { } else {
var event = document.createEvent("CustomEvent"); var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {}); event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event); util.global.dispatchEvent(event);
return function(name, event) { return function(name, event) {
name = name.toLowerCase();
var domEvent = document.createEvent("CustomEvent"); var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name, false, true, domEvent.initCustomEvent(name.toLowerCase(), false, true,
event); event);
return dispatch(legacyHandlers[name], domEvent); return !util.global.dispatchEvent(domEvent);
}; };
} }
} catch (e) {} } catch (e) {}
@ -361,18 +289,6 @@ Promise.config = function(opts) {
Promise.prototype._fireEvent = defaultFireEvent; Promise.prototype._fireEvent = defaultFireEvent;
} }
} }
if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) {
var prev = config.asyncHooks;
var cur = !!opts.asyncHooks;
if (prev !== cur) {
config.asyncHooks = cur;
if (cur) {
enableAsyncHooks();
} else {
disableAsyncHooks();
}
}
}
return Promise; return Promise;
}; };
@ -393,7 +309,6 @@ Promise.prototype._attachCancellationCallback = function(onCancel) {
}; };
Promise.prototype._captureStackTrace = function () {}; Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._dereferenceTrace = function () {};
Promise.prototype._clearCancellationData = function() {}; Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) { Promise.prototype._propagateFrom = function (parent, flags) {
; ;
@ -499,10 +414,6 @@ function longStackTracesAttachExtraTrace(error, ignoreSelf) {
} }
} }
function longStackTracesDereferenceTrace() {
this._trace = undefined;
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise, function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) { parent) {
if (returnValue === undefined && promiseCreated !== null && if (returnValue === undefined && promiseCreated !== null &&
@ -760,8 +671,8 @@ function parseLineInfo(line) {
function setBounds(firstLineError, lastLineError) { function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return; if (!longStackTracesIsSupported()) return;
var firstStackLines = (firstLineError.stack || "").split("\n"); var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = (lastLineError.stack || "").split("\n"); var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1; var firstIndex = -1;
var lastIndex = -1; var lastIndex = -1;
var firstFileName; var firstFileName;
@ -970,16 +881,12 @@ var config = {
warnings: warnings, warnings: warnings,
longStackTraces: false, longStackTraces: false,
cancellation: false, cancellation: false,
monitoring: false, monitoring: false
asyncHooks: false
}; };
if (longStackTraces) Promise.longStackTraces(); if (longStackTraces) Promise.longStackTraces();
return { return {
asyncHooks: function() {
return config.asyncHooks;
},
longStackTraces: function() { longStackTraces: function() {
return config.longStackTraces; return config.longStackTraces;
}, },

@ -1,9 +1,8 @@
"use strict"; "use strict";
module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { module.exports = function(Promise, tryConvertToPromise) {
var util = require("./util"); var util = require("./util");
var CancellationError = Promise.CancellationError; var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj; var errorObj = util.errorObj;
var catchFilter = require("./catch_filter")(NEXT_FILTER);
function PassThroughHandlerContext(promise, type, handler) { function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise; this.promise = promise;
@ -55,9 +54,7 @@ function finallyHandler(reasonOrValue) {
var ret = this.isFinallyHandler() var ret = this.isFinallyHandler()
? handler.call(promise._boundValue()) ? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue); : handler.call(promise._boundValue(), reasonOrValue);
if (ret === NEXT_FILTER) { if (ret !== undefined) {
return ret;
} else if (ret !== undefined) {
promise._setReturnedNonUndefined(); promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise); var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) { if (maybePromise instanceof Promise) {
@ -106,41 +103,9 @@ Promise.prototype["finally"] = function (handler) {
finallyHandler); finallyHandler);
}; };
Promise.prototype.tap = function (handler) { Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler); return this._passThrough(handler, 1, finallyHandler);
}; };
Promise.prototype.tapCatch = function (handlerOrPredicate) {
var len = arguments.length;
if(len === 1) {
return this._passThrough(handlerOrPredicate,
1,
undefined,
finallyHandler);
} else {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return Promise.reject(new TypeError(
"tapCatch statement predicate: "
+ "expecting an object but got " + util.classString(item)
));
}
}
catchInstances.length = j;
var handler = arguments[i];
return this._passThrough(catchFilter(catchInstances, handler, this),
1,
undefined,
finallyHandler);
}
};
return PassThroughHandlerContext; return PassThroughHandlerContext;
}; };

@ -157,7 +157,7 @@ PromiseSpawn.prototype._continue = function (result) {
if (maybePromise === null) { if (maybePromise === null) {
this._promiseRejected( this._promiseRejected(
new TypeError( new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" + "From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n") this._stack.split("\n").slice(1, -7).join("\n")
) )

@ -1,6 +1,7 @@
"use strict"; "use strict";
module.exports = module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
getDomain) {
var util = require("./util"); var util = require("./util");
var canEvaluate = util.canEvaluate; var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch; var tryCatch = util.tryCatch;
@ -146,8 +147,10 @@ Promise.join = function () {
if (!ret._isFateSealed()) { if (!ret._isFateSealed()) {
if (holder.asyncNeeded) { if (holder.asyncNeeded) {
var context = Promise._getContext(); var domain = getDomain();
holder.fn = util.contextBind(context, holder.fn); if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
} }
ret._setAsyncGuaranteed(); ret._setAsyncGuaranteed();
ret._setOnCancel(holder); ret._setOnCancel(holder);
@ -156,7 +159,7 @@ Promise.join = function () {
} }
} }
} }
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i ];}; var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
if (fn) args.pop(); if (fn) args.pop();
var ret = new PromiseArray(args).promise(); var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret; return fn !== undefined ? ret.spread(fn) : ret;

@ -5,6 +5,7 @@ module.exports = function(Promise,
tryConvertToPromise, tryConvertToPromise,
INTERNAL, INTERNAL,
debug) { debug) {
var getDomain = Promise._getDomain;
var util = require("./util"); var util = require("./util");
var tryCatch = util.tryCatch; var tryCatch = util.tryCatch;
var errorObj = util.errorObj; var errorObj = util.errorObj;
@ -13,8 +14,8 @@ var async = Promise._async;
function MappingPromiseArray(promises, fn, limit, _filter) { function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises); this.constructor$(promises);
this._promise._captureStackTrace(); this._promise._captureStackTrace();
var context = Promise._getContext(); var domain = getDomain();
this._callback = util.contextBind(context, fn); this._callback = domain === null ? fn : util.domainBind(domain, fn);
this._preservedValues = _filter === INTERNAL this._preservedValues = _filter === INTERNAL
? new Array(this.length()) ? new Array(this.length())
: null; : null;
@ -22,14 +23,6 @@ function MappingPromiseArray(promises, fn, limit, _filter) {
this._inFlight = 0; this._inFlight = 0;
this._queue = []; this._queue = [];
async.invoke(this._asyncInit, this, undefined); async.invoke(this._asyncInit, this, undefined);
if (util.isArray(promises)) {
for (var i = 0; i < promises.length; ++i) {
var maybePromise = promises[i];
if (maybePromise instanceof Promise) {
maybePromise.suppressUnhandledRejections();
}
}
}
} }
util.inherits(MappingPromiseArray, PromiseArray); util.inherits(MappingPromiseArray, PromiseArray);

@ -12,42 +12,20 @@ var apiRejection = function(msg) {
function Proxyable() {} function Proxyable() {}
var UNDEFINED_BINDING = {}; var UNDEFINED_BINDING = {};
var util = require("./util"); var util = require("./util");
util.setReflectHandler(reflectHandler);
var getDomain = function() { var getDomain;
var domain = process.domain; if (util.isNode) {
if (domain === undefined) { getDomain = function() {
return null; var ret = process.domain;
} if (ret === undefined) ret = null;
return domain; return ret;
};
var getContextDefault = function() {
return null;
};
var getContextDomain = function() {
return {
domain: getDomain(),
async: null
}; };
}; } else {
var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? getDomain = function() {
require("async_hooks").AsyncResource : null; return null;
var getContextAsyncHooks = function() {
return {
domain: getDomain(),
async: new AsyncResource("Bluebird::Promise")
}; };
}; }
var getContext = util.isNode ? getContextDomain : getContextDefault; util.notEnumerableProp(Promise, "_getDomain", getDomain);
util.notEnumerableProp(Promise, "_getContext", getContext);
var enableAsyncHooks = function() {
getContext = getContextAsyncHooks;
util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks);
};
var disableAsyncHooks = function() {
getContext = getContextDomain;
util.notEnumerableProp(Promise, "_getContext", getContextDomain);
};
var es5 = require("./es5"); var es5 = require("./es5");
var Async = require("./async"); var Async = require("./async");
@ -71,36 +49,33 @@ var PromiseArray =
var Context = require("./context")(Promise); var Context = require("./context")(Promise);
/*jshint unused:false*/ /*jshint unused:false*/
var createContext = Context.create; var createContext = Context.create;
var debug = require("./debuggability")(Promise, Context);
var debug = require("./debuggability")(Promise, Context,
enableAsyncHooks, disableAsyncHooks);
var CapturedTrace = debug.CapturedTrace; var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext = var PassThroughHandlerContext =
require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); require("./finally")(Promise, tryConvertToPromise);
var catchFilter = require("./catch_filter")(NEXT_FILTER); var catchFilter = require("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = require("./nodeback"); var nodebackForPromise = require("./nodeback");
var errorObj = util.errorObj; var errorObj = util.errorObj;
var tryCatch = util.tryCatch; var tryCatch = util.tryCatch;
function check(self, executor) { function check(self, executor) {
if (self == null || self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (typeof executor !== "function") { if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor)); throw new TypeError("expecting a function but got " + util.classString(executor));
} }
if (self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
} }
function Promise(executor) { function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0; this._bitField = 0;
this._fulfillmentHandler0 = undefined; this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined; this._rejectionHandler0 = undefined;
this._promise0 = undefined; this._promise0 = undefined;
this._receiver0 = undefined; this._receiver0 = undefined;
this._resolveFromExecutor(executor); if (executor !== INTERNAL) {
check(this, executor);
this._resolveFromExecutor(executor);
}
this._promiseCreated(); this._promiseCreated();
this._fireEvent("promiseCreated", this); this._fireEvent("promiseCreated", this);
} }
@ -119,17 +94,12 @@ Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
if (util.isObject(item)) { if (util.isObject(item)) {
catchInstances[j++] = item; catchInstances[j++] = item;
} else { } else {
return apiRejection("Catch statement predicate: " + return apiRejection("expecting an object but got " +
"expecting an object but got " + util.classString(item)); "A catch statement predicate " + util.classString(item));
} }
} }
catchInstances.length = j; catchInstances.length = j;
fn = arguments[i]; fn = arguments[i];
if (typeof fn !== "function") {
throw new TypeError("The last argument to .catch() " +
"must be a function, got " + util.toString(fn));
}
return this.then(undefined, catchFilter(catchInstances, fn, this)); return this.then(undefined, catchFilter(catchInstances, fn, this));
} }
return this.then(undefined, fn); return this.then(undefined, fn);
@ -270,7 +240,7 @@ Promise.prototype._then = function (
this._fireEvent("promiseChained", this, promise); this._fireEvent("promiseChained", this, promise);
} }
var context = getContext(); var domain = getDomain();
if (!((bitField & 50397184) === 0)) { if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx; var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) { if (((bitField & 33554432) !== 0)) {
@ -288,14 +258,15 @@ Promise.prototype._then = function (
} }
async.invoke(settler, target, { async.invoke(settler, target, {
handler: util.contextBind(context, handler), handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
promise: promise, promise: promise,
receiver: receiver, receiver: receiver,
value: value value: value
}); });
} else { } else {
target._addCallbacks(didFulfill, didReject, promise, target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
receiver, context);
} }
return promise; return promise;
@ -356,15 +327,7 @@ Promise.prototype._setWillBeCancelled = function() {
Promise.prototype._setAsyncGuaranteed = function() { Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return; if (async.hasCustomScheduler()) return;
var bitField = this._bitField; this._bitField = this._bitField | 134217728;
this._bitField = bitField |
(((bitField & 536870912) >> 2) ^
134217728);
};
Promise.prototype._setNoAsyncGuarantee = function() {
this._bitField = (this._bitField | 536870912) &
(~134217728);
}; };
Promise.prototype._receiverAt = function (index) { Promise.prototype._receiverAt = function (index) {
@ -419,7 +382,7 @@ Promise.prototype._addCallbacks = function (
reject, reject,
promise, promise,
receiver, receiver,
context domain
) { ) {
var index = this._length(); var index = this._length();
@ -432,10 +395,12 @@ Promise.prototype._addCallbacks = function (
this._promise0 = promise; this._promise0 = promise;
this._receiver0 = receiver; this._receiver0 = receiver;
if (typeof fulfill === "function") { if (typeof fulfill === "function") {
this._fulfillmentHandler0 = util.contextBind(context, fulfill); this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
} }
if (typeof reject === "function") { if (typeof reject === "function") {
this._rejectionHandler0 = util.contextBind(context, reject); this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
} }
} else { } else {
var base = index * 4 - 4; var base = index * 4 - 4;
@ -443,11 +408,11 @@ Promise.prototype._addCallbacks = function (
this[base + 3] = receiver; this[base + 3] = receiver;
if (typeof fulfill === "function") { if (typeof fulfill === "function") {
this[base + 0] = this[base + 0] =
util.contextBind(context, fulfill); domain === null ? fulfill : util.domainBind(domain, fulfill);
} }
if (typeof reject === "function") { if (typeof reject === "function") {
this[base + 1] = this[base + 1] =
util.contextBind(context, reject); domain === null ? reject : util.domainBind(domain, reject);
} }
} }
this._setLength(index + 1); this._setLength(index + 1);
@ -467,7 +432,6 @@ Promise.prototype._resolveCallback = function(value, shouldBind) {
if (shouldBind) this._propagateFrom(maybePromise, 2); if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target(); var promise = maybePromise._target();
if (promise === this) { if (promise === this) {
@ -484,7 +448,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) {
} }
this._setFollowing(); this._setFollowing();
this._setLength(0); this._setLength(0);
this._setFollowee(maybePromise); this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) { } else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value()); this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) { } else if (((bitField & 16777216) !== 0)) {
@ -510,7 +474,6 @@ function(reason, synchronous, ignoreNonErrorWarnings) {
}; };
Promise.prototype._resolveFromExecutor = function (executor) { Promise.prototype._resolveFromExecutor = function (executor) {
if (executor === INTERNAL) return;
var promise = this; var promise = this;
this._captureStackTrace(); this._captureStackTrace();
this._pushContext(); this._pushContext();
@ -674,7 +637,6 @@ Promise.prototype._fulfill = function (value) {
} else { } else {
async.settlePromises(this); async.settlePromises(this);
} }
this._dereferenceTrace();
} }
}; };
@ -743,14 +705,6 @@ Promise.prototype._settledValue = function() {
} }
}; };
if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
get: function () {
return "Object";
}
});
}
function deferResolve(v) {this.promise._resolveCallback(v);} function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);} function deferReject(v) {this.promise._rejectCallback(v, false);}
@ -775,12 +729,14 @@ require("./cancel")(Promise, PromiseArray, apiRejection, debug);
require("./direct_resolve")(Promise); require("./direct_resolve")(Promise);
require("./synchronous_inspection")(Promise); require("./synchronous_inspection")(Promise);
require("./join")( require("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise.Promise = Promise; Promise.Promise = Promise;
Promise.version = "3.7.2"; Promise.version = "3.4.7";
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./call_get.js')(Promise); require('./call_get.js')(Promise);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./timers.js')(Promise, INTERNAL, debug);
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./nodeify.js')(Promise); require('./nodeify.js')(Promise);
require('./promisify.js')(Promise, INTERNAL); require('./promisify.js')(Promise, INTERNAL);
require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
@ -788,11 +744,9 @@ require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./settle.js')(Promise, PromiseArray, debug); require('./settle.js')(Promise, PromiseArray, debug);
require('./some.js')(Promise, PromiseArray, apiRejection); require('./some.js')(Promise, PromiseArray, apiRejection);
require('./timers.js')(Promise, INTERNAL, debug);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./any.js')(Promise);
require('./each.js')(Promise, INTERNAL);
require('./filter.js')(Promise, INTERNAL); require('./filter.js')(Promise, INTERNAL);
require('./each.js')(Promise, INTERNAL);
require('./any.js')(Promise);
util.toFastProperties(Promise); util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype); util.toFastProperties(Promise.prototype);

@ -8,7 +8,6 @@ function toResolutionValue(val) {
switch(val) { switch(val) {
case -2: return []; case -2: return [];
case -3: return {}; case -3: return {};
case -6: return new Map();
} }
} }
@ -16,7 +15,6 @@ function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL); var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) { if (values instanceof Promise) {
promise._propagateFrom(values, 3); promise._propagateFrom(values, 3);
values.suppressUnhandledRejections();
} }
promise._setOnCancel(this); promise._setOnCancel(this);
this._values = values; this._values = values;

@ -55,7 +55,7 @@ function PropertiesPromiseArray(obj) {
} }
this.constructor$(entries); this.constructor$(entries);
this._isMap = isMap; this._isMap = isMap;
this._init$(undefined, isMap ? -6 : -3); this._init$(undefined, -3);
} }
util.inherits(PropertiesPromiseArray, PromiseArray); util.inherits(PropertiesPromiseArray, PromiseArray);

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

Loading…
Cancel
Save