이세린

cute.js API 가 작동 안해서 es6 모듈로 바꾸는 중...

Showing 209 changed files with 8883 additions and 10397 deletions
1 module.exports = { 1 module.exports = {
2 name: 'breathe', 2 name: 'breathe',
3 - description: 'Embeds a gif', 3 + description: 'Replies with a breathing gif',
4 - execute(message, args, Discord){ 4 + execute(message, args){
5 message.channel.send('https://images.squarespace-cdn.com/content/v1/5f6a71b620b6aa40a963641d/1609631567334-8E5V3K3WXD4PW4YWB0ZZ/6a-1575918606525.gif'); 5 message.channel.send('https://images.squarespace-cdn.com/content/v1/5f6a71b620b6aa40a963641d/1609631567334-8E5V3K3WXD4PW4YWB0ZZ/6a-1575918606525.gif');
6 } 6 }
7 } 7 }
...\ No newline at end of file ...\ No newline at end of file
......
1 module.exports = { 1 module.exports = {
2 name: 'calm', 2 name: 'calm',
3 description: 'Actual help section', 3 description: 'Actual help section',
4 - execute(message, args){ 4 + execute(message, args, Discord){
5 - message.channel.send("It's okay, I'm here to help! What would you like to do?\n\n;breathe : A gif to sync your breathing to!\n;cute : Some cute animal pictures to banish the bad feels!\n;checklist : I will guide you through an anxiety checklist\n;chat : If you just want a chat with me!"); 5 + const calmEmbed = new Discord.MessageEmbed()
6 + .setColor('#91B2C7')
7 + .setDescription("It's okay, I'm here to help! What would you like to do?")
8 + .addFields(
9 + {name: ';breathe', value: "A gif to sync your breathing to!"},
10 + {name: ';cute', value: "Some cute animal pictures to banish the bad feels!"},
11 + {name: ';checklist', value: "I'll guide you through an anxiety checklist"},
12 + {name: ';chat', value: "If you just want a chat with me, I'm all ears!"}
13 + );
14 + message.channel.send(calmEmbed);
6 } 15 }
7 -}
...\ No newline at end of file ...\ No newline at end of file
16 +}
17 +
18 +//Add reaction event flag later
...\ No newline at end of file ...\ No newline at end of file
......
1 +import fetch from "node-fetch";
2 +
1 const subReddits = [ 3 const subReddits = [
2 - "r/aww" 4 + "aww",
5 + "jellybeantoes",
6 + "puppies"
3 ] 7 ]
8 +// Currently BROKEN
4 9
5 module.exports = { 10 module.exports = {
6 name: 'cute', 11 name: 'cute',
7 description: 'Embeds pictures pulled from listed subreddits', 12 description: 'Embeds pictures pulled from listed subreddits',
8 - execute(message, args, Discord){ 13 + async execute(message, args, Discord){
9 const randomIndex = randomInt(0, subReddits.length); 14 const randomIndex = randomInt(0, subReddits.length);
10 - axios
11 - .get(`https://reddit.com/${subReddits[randomIndex]}/.json`)
12 - .then((resp) => {
13 - const {
14 - title,
15 - url,
16 - subreddit_name_prefixed: subreddit
17 - } = getRandomPost(resp.data.data.children);
18 - })
19 15
20 - const newEmbed = new Discord.cuteEmbed() 16 + //"https://reddit.com/${subReddits[randomIndex]}/.json?jsonp=?"
21 - .setTitle('${title}') 17 + let data = await fetch
22 - .setImage('${url}'); 18 + ("https://meme-api.herokuapp.com/gimme/${subReddits[randomIndex]}").then(
19 + res => res.json
20 + )
21 +
22 + const cuteEmbed = new Discord.MessageEmbed()
23 + .setColor('#91B2C7')
24 + .setImage(data.url);
25 +
26 + message.channel.send(cuteEmbed);
23 } 27 }
24 } 28 }
25 29
26 //random int generator 30 //random int generator
27 function randomInt(min, max) { 31 function randomInt(min, max) {
28 return (Math.floor(Math.random() * (max - min))) + min; 32 return (Math.floor(Math.random() * (max - min))) + min;
29 -}
30 -//random post generator
31 -function getRandomPost(posts) {
32 - const randomIndex = randomInt(0, posts.length);
33 - return posts[randomIndex].data;
34 } 33 }
...\ No newline at end of file ...\ No newline at end of file
......
1 //bot basic primer 1 //bot basic primer
2 -const Discord = require('discord.js'); 2 +import {Discord} from 'discord.js'
3 3
4 const client = new Discord.Client(); 4 const client = new Discord.Client();
5 5
6 const prefix = ';'; 6 const prefix = ';';
7 7
8 -const fs = require('fs'); 8 +import {fs} from 'fs';
9 -
10 -//import 'regenerator-runtime/runtime'; -> do i need this?
11 -const axios = require("axios");
12 9
13 client.commands = new Discord.Collection(); 10 client.commands = new Discord.Collection();
14 11
15 const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); 12 const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
13 +
14 +import breathe from './commands/breathe';
15 +import calm from './commands/calm';
16 +import chat from './commands/chat';
17 +import checklist from './commands/checklist';
18 +import cute from './commands/cute';
19 +import help from './commands/help';
20 +
16 for(const file of commandFiles){ 21 for(const file of commandFiles){
17 - const command = require(`./commands/${file}`); 22 + //const command = require(`./commands/${file}`);
18 client.commands.set(command.name, command); 23 client.commands.set(command.name, command);
19 } 24 }
20 25
...@@ -35,7 +40,7 @@ client.on('message', message => { ...@@ -35,7 +40,7 @@ client.on('message', message => {
35 } else if(command == 'help'){ 40 } else if(command == 'help'){
36 client.commands.get('help').execute(message, args); 41 client.commands.get('help').execute(message, args);
37 } else if(command == 'calm'){ 42 } else if(command == 'calm'){
38 - client.commands.get('calm').execute(message, args); 43 + client.commands.get('calm').execute(message, args, Discord);
39 } else if(command == 'breathe'){ 44 } else if(command == 'breathe'){
40 client.commands.get('breathe').execute(message, args); 45 client.commands.get('breathe').execute(message, args);
41 } else if(command == 'cute'){ 46 } else if(command == 'cute'){
......
...@@ -38,15 +38,6 @@ ...@@ -38,15 +38,6 @@
38 "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", 38 "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
39 "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" 39 "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
40 }, 40 },
41 - "node_modules/axios": {
42 - "version": "0.27.2",
43 - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz",
44 - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==",
45 - "dependencies": {
46 - "follow-redirects": "^1.14.9",
47 - "form-data": "^4.0.0"
48 - }
49 - },
50 "node_modules/combined-stream": { 41 "node_modules/combined-stream": {
51 "version": "1.0.8", 42 "version": "1.0.8",
52 "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", 43 "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
...@@ -58,6 +49,14 @@ ...@@ -58,6 +49,14 @@
58 "node": ">= 0.8" 49 "node": ">= 0.8"
59 } 50 }
60 }, 51 },
52 + "node_modules/data-uri-to-buffer": {
53 + "version": "4.0.0",
54 + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.0.tgz",
55 + "integrity": "sha512-Vr3mLBA8qWmcuschSLAOogKgQ/Jwxulv3RNE4FXnYWRGujzrRWQI4m12fQqRkwX06C0KanhLr4hK+GydchZsaA==",
56 + "engines": {
57 + "node": ">= 12"
58 + }
59 + },
61 "node_modules/delayed-stream": { 60 "node_modules/delayed-stream": {
62 "version": "1.0.0", 61 "version": "1.0.0",
63 "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", 62 "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
...@@ -85,6 +84,25 @@ ...@@ -85,6 +84,25 @@
85 "node": ">=12.0.0" 84 "node": ">=12.0.0"
86 } 85 }
87 }, 86 },
87 + "node_modules/discord.js/node_modules/node-fetch": {
88 + "version": "2.6.7",
89 + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
90 + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
91 + "dependencies": {
92 + "whatwg-url": "^5.0.0"
93 + },
94 + "engines": {
95 + "node": "4.x || >=6.0.0"
96 + },
97 + "peerDependencies": {
98 + "encoding": "^0.1.0"
99 + },
100 + "peerDependenciesMeta": {
101 + "encoding": {
102 + "optional": true
103 + }
104 + }
105 + },
88 "node_modules/event-target-shim": { 106 "node_modules/event-target-shim": {
89 "version": "5.0.1", 107 "version": "5.0.1",
90 "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", 108 "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
...@@ -93,36 +111,37 @@ ...@@ -93,36 +111,37 @@
93 "node": ">=6" 111 "node": ">=6"
94 } 112 }
95 }, 113 },
96 - "node_modules/follow-redirects": { 114 + "node_modules/fetch-blob": {
97 - "version": "1.15.1", 115 + "version": "3.1.5",
98 - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz", 116 + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.1.5.tgz",
99 - "integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==", 117 + "integrity": "sha512-N64ZpKqoLejlrwkIAnb9iLSA3Vx/kjgzpcDhygcqJ2KKjky8nCgUQ+dzXtbrLaWZGZNmNfQTsiQ0weZ1svglHg==",
100 "funding": [ 118 "funding": [
101 { 119 {
102 - "type": "individual", 120 + "type": "github",
103 - "url": "https://github.com/sponsors/RubenVerborgh" 121 + "url": "https://github.com/sponsors/jimmywarting"
122 + },
123 + {
124 + "type": "paypal",
125 + "url": "https://paypal.me/jimmywarting"
104 } 126 }
105 ], 127 ],
106 - "engines": { 128 + "dependencies": {
107 - "node": ">=4.0" 129 + "node-domexception": "^1.0.0",
130 + "web-streams-polyfill": "^3.0.3"
108 }, 131 },
109 - "peerDependenciesMeta": { 132 + "engines": {
110 - "debug": { 133 + "node": "^12.20 || >= 14.13"
111 - "optional": true
112 - }
113 } 134 }
114 }, 135 },
115 - "node_modules/form-data": { 136 + "node_modules/formdata-polyfill": {
116 - "version": "4.0.0", 137 + "version": "4.0.10",
117 - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", 138 + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
118 - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", 139 + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
119 "dependencies": { 140 "dependencies": {
120 - "asynckit": "^0.4.0", 141 + "fetch-blob": "^3.1.2"
121 - "combined-stream": "^1.0.8",
122 - "mime-types": "^2.1.12"
123 }, 142 },
124 "engines": { 143 "engines": {
125 - "node": ">= 6" 144 + "node": ">=12.20.0"
126 } 145 }
127 }, 146 },
128 "node_modules/mime-db": { 147 "node_modules/mime-db": {
...@@ -144,23 +163,39 @@ ...@@ -144,23 +163,39 @@
144 "node": ">= 0.6" 163 "node": ">= 0.6"
145 } 164 }
146 }, 165 },
166 + "node_modules/node-domexception": {
167 + "version": "1.0.0",
168 + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
169 + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
170 + "funding": [
171 + {
172 + "type": "github",
173 + "url": "https://github.com/sponsors/jimmywarting"
174 + },
175 + {
176 + "type": "github",
177 + "url": "https://paypal.me/jimmywarting"
178 + }
179 + ],
180 + "engines": {
181 + "node": ">=10.5.0"
182 + }
183 + },
147 "node_modules/node-fetch": { 184 "node_modules/node-fetch": {
148 - "version": "2.6.7", 185 + "version": "3.2.4",
149 - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", 186 + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.2.4.tgz",
150 - "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", 187 + "integrity": "sha512-WvYJRN7mMyOLurFR2YpysQGuwYrJN+qrrpHjJDuKMcSPdfFccRUla/kng2mz6HWSBxJcqPbvatS6Gb4RhOzCJw==",
151 "dependencies": { 188 "dependencies": {
152 - "whatwg-url": "^5.0.0" 189 + "data-uri-to-buffer": "^4.0.0",
190 + "fetch-blob": "^3.1.4",
191 + "formdata-polyfill": "^4.0.10"
153 }, 192 },
154 "engines": { 193 "engines": {
155 - "node": "4.x || >=6.0.0" 194 + "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
156 - },
157 - "peerDependencies": {
158 - "encoding": "^0.1.0"
159 }, 195 },
160 - "peerDependenciesMeta": { 196 + "funding": {
161 - "encoding": { 197 + "type": "opencollective",
162 - "optional": true 198 + "url": "https://opencollective.com/node-fetch"
163 - }
164 } 199 }
165 }, 200 },
166 "node_modules/prism-media": { 201 "node_modules/prism-media": {
...@@ -203,6 +238,14 @@ ...@@ -203,6 +238,14 @@
203 "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", 238 "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
204 "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" 239 "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw=="
205 }, 240 },
241 + "node_modules/web-streams-polyfill": {
242 + "version": "3.2.1",
243 + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz",
244 + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==",
245 + "engines": {
246 + "node": ">= 8"
247 + }
248 + },
206 "node_modules/webidl-conversions": { 249 "node_modules/webidl-conversions": {
207 "version": "3.0.1", 250 "version": "3.0.1",
208 "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", 251 "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
......
1 -# Changelog
2 -
3 -### 0.27.2 (April 27, 2022)
4 -
5 -Fixes and Functionality:
6 -- Fixed FormData posting in browser environment by reverting #3785 ([#4640](https://github.com/axios/axios/pull/4640))
7 -- Enhanced protocol parsing implementation ([#4639](https://github.com/axios/axios/pull/4639))
8 -- Fixed bundle size
9 -
10 -### 0.27.1 (April 26, 2022)
11 -
12 -Fixes and Functionality:
13 -- Removed import of url module in browser build due to huge size overhead and builds being broken ([#4594](https://github.com/axios/axios/pull/4594))
14 -- Bumped follow-redirects to ^1.14.9 ([#4615](https://github.com/axios/axios/pull/4615))
15 -
16 -### 0.27.0 (April 25, 2022)
17 -
18 -Breaking changes:
19 -- New toFormData helper function that allows the implementor to pass an object and allow axios to convert it to FormData ([#3757](https://github.com/axios/axios/pull/3757))
20 -- Removed functionality that removed the the `Content-Type` request header when passing FormData ([#3785](https://github.com/axios/axios/pull/3785))
21 -- **(*)** Refactored error handling implementing AxiosError as a constructor, this is a large change to error handling on the whole ([#3645](https://github.com/axios/axios/pull/3645))
22 -- Separated responsibility for FormData instantiation between `transformRequest` and `toFormData` ([#4470](https://github.com/axios/axios/pull/4470))
23 -- **(*)** Improved and fixed multiple issues with FormData support ([#4448](https://github.com/axios/axios/pull/4448))
24 -
25 -QOL and DevX improvements:
26 -- Added a multipart/form-data testing playground allowing contributors to debug changes easily ([#4465](https://github.com/axios/axios/pull/4465))
27 -
28 -Fixes and Functionality:
29 -- Refactored project file structure to avoid circular imports ([#4515](https://github.com/axios/axios/pull/4516)) & ([#4516](https://github.com/axios/axios/pull/4516))
30 -- Bumped follow-redirects to ^1.14.9 ([#4562](https://github.com/axios/axios/pull/4562))
31 -
32 -Internal and Tests:
33 -- Updated dev dependencies to latest version
34 -
35 -Documentation:
36 -- Fixing incorrect link in changelog ([#4551](https://github.com/axios/axios/pull/4551))
37 -
38 -Notes:
39 -- **(*)** Please read these pull requests before updating, these changes are very impactful and far reaching.
40 -
41 -### 0.26.1 (March 9, 2022)
42 -
43 -Fixes and Functionality:
44 -- Refactored project file structure to avoid circular imports ([#4220](https://github.com/axios/axios/pull/4220))
45 -
46 -### 0.26.0 (February 13, 2022)
47 -
48 -Fixes and Functionality:
49 -- Fixed The timeoutErrorMessage property in config not work with Node.js ([#3581](https://github.com/axios/axios/pull/3581))
50 -- Added errors to be displayed when the query parsing process itself fails ([#3961](https://github.com/axios/axios/pull/3961))
51 -- Fix/remove url required ([#4426](https://github.com/axios/axios/pull/4426))
52 -- Update follow-redirects dependency due to Vulnerability ([#4462](https://github.com/axios/axios/pull/4462))
53 -- Bump karma from 6.3.11 to 6.3.14 ([#4461](https://github.com/axios/axios/pull/4461))
54 -- Bump follow-redirects from 1.14.7 to 1.14.8 ([#4473](https://github.com/axios/axios/pull/4473))
55 -
56 -### 0.25.0 (January 18, 2022)
57 -
58 -Breaking changes:
59 -- Fixing maxBodyLength enforcement ([#3786](https://github.com/axios/axios/pull/3786))
60 -- Don't rely on strict mode behavior for arguments ([#3470](https://github.com/axios/axios/pull/3470))
61 -- Adding error handling when missing url ([#3791](https://github.com/axios/axios/pull/3791))
62 -- Update isAbsoluteURL.js removing escaping of non-special characters ([#3809](https://github.com/axios/axios/pull/3809))
63 -- Use native Array.isArray() in utils.js ([#3836](https://github.com/axios/axios/pull/3836))
64 -- Adding error handling inside stream end callback ([#3967](https://github.com/axios/axios/pull/3967))
65 -
66 -Fixes and Functionality:
67 -- Added aborted even handler ([#3916](https://github.com/axios/axios/pull/3916))
68 -- Header types expanded allowing `boolean` and `number` types ([#4144](https://github.com/axios/axios/pull/4144))
69 -- Fix cancel signature allowing cancel message to be `undefined` ([#3153](https://github.com/axios/axios/pull/3153))
70 -- Updated type checks to be formulated better ([#3342](https://github.com/axios/axios/pull/3342))
71 -- Avoid unnecessary buffer allocations ([#3321](https://github.com/axios/axios/pull/3321))
72 -- Adding a socket handler to keep TCP connection live when processing long living requests ([#3422](https://github.com/axios/axios/pull/3422))
73 -- Added toFormData helper function ([#3757](https://github.com/axios/axios/pull/3757))
74 -- Adding responseEncoding prop type in AxiosRequestConfig ([#3918](https://github.com/axios/axios/pull/3918))
75 -
76 -Internal and Tests:
77 -- Adding axios-test-instance to ecosystem ([#3496](https://github.com/axios/axios/pull/3496))
78 -- Optimize the logic of isAxiosError ([#3546](https://github.com/axios/axios/pull/3546))
79 -- Add tests and documentation to display how multiple inceptors work ([#3564](https://github.com/axios/axios/pull/3564))
80 -- Updating follow-redirects to version 1.14.7 ([#4379](https://github.com/axios/axios/pull/4379))
81 -
82 -Documentation:
83 -- Fixing changelog to show correct pull request ([#4219](https://github.com/axios/axios/pull/4219))
84 -- Update upgrade guide for https proxy setting ([#3604](https://github.com/axios/axios/pull/3604))
85 -
86 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
87 -
88 -- [Jay](mailto:jasonsaayman@gmail.com)
89 -- [Rijk van Zanten](https://github.com/rijkvanzanten)
90 -- [Kohta Ito](https://github.com/koh110)
91 -- [Brandon Faulkner](https://github.com/bfaulk96)
92 -- [Stefano Magni](https://github.com/NoriSte)
93 -- [enofan](https://github.com/fanguangyi)
94 -- [Andrey Pechkurov](https://github.com/puzpuzpuz)
95 -- [Doowonee](https://github.com/doowonee)
96 -- [Emil Broman](https://github.com/emilbroman-eqt)
97 -- [Remco Haszing](https://github.com/remcohaszing)
98 -- [Black-Hole](https://github.com/BlackHole1)
99 -- [Wolfram Kriesing](https://github.com/wolframkriesing)
100 -- [Andrew Ovens](https://github.com/repl-andrew-ovens)
101 -- [Paulo Renato](https://github.com/PauloRSF)
102 -- [Ben Carp](https://github.com/carpben)
103 -- [Hirotaka Tagawa](https://github.com/wafuwafu13)
104 -- [狼族小狈](https://github.com/lzxb)
105 -- [C. Lewis](https://github.com/ctjlewis)
106 -- [Felipe Carvalho](https://github.com/FCarvalhoVII)
107 -- [Daniel](https://github.com/djs113)
108 -- [Gustavo Sales](https://github.com/gussalesdev)
109 -
110 -### 0.24.0 (October 25, 2021)
111 -
112 -Breaking changes:
113 -- Revert: change type of AxiosResponse to any, please read lengthy discussion here: ([#4141](https://github.com/axios/axios/issues/4141)) pull request: ([#4186](https://github.com/axios/axios/pull/4186))
114 -
115 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
116 -
117 -- [Jay](mailto:jasonsaayman@gmail.com)
118 -- [Rodry](https://github.com/ImRodry)
119 -- [Remco Haszing](https://github.com/remcohaszing)
120 -- [Isaiah Thomason](https://github.com/ITenthusiasm)
121 -
122 -### 0.23.0 (October 12, 2021)
123 -
124 -Breaking changes:
125 -- Distinguish request and response data types ([#4116](https://github.com/axios/axios/pull/4116))
126 -- Change never type to unknown ([#4142](https://github.com/axios/axios/pull/4142))
127 -- Fixed TransitionalOptions typings ([#4147](https://github.com/axios/axios/pull/4147))
128 -
129 -Fixes and Functionality:
130 -- Adding globalObject: 'this' to webpack config ([#3176](https://github.com/axios/axios/pull/3176))
131 -- Adding insecureHTTPParser type to AxiosRequestConfig ([#4066](https://github.com/axios/axios/pull/4066))
132 -- Fix missing semicolon in typings ([#4115](https://github.com/axios/axios/pull/4115))
133 -- Fix response headers types ([#4136](https://github.com/axios/axios/pull/4136))
134 -
135 -Internal and Tests:
136 -- Improve timeout error when timeout is browser default ([#3209](https://github.com/axios/axios/pull/3209))
137 -- Fix node version on CI ([#4069](https://github.com/axios/axios/pull/4069))
138 -- Added testing to TypeScript portion of project ([#4140](https://github.com/axios/axios/pull/4140))
139 -
140 -Documentation:
141 -- Rename Angular to AngularJS ([#4114](https://github.com/axios/axios/pull/4114))
142 -
143 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
144 -
145 -- [Jay](mailto:jasonsaayman@gmail.com)
146 -- [Evan-Finkelstein](https://github.com/Evan-Finkelstein)
147 -- [Paweł Szymański](https://github.com/Jezorko)
148 -- [Dobes Vandermeer](https://github.com/dobesv)
149 -- [Claas Augner](https://github.com/caugner)
150 -- [Remco Haszing](https://github.com/remcohaszing)
151 -- [Evgeniy](https://github.com/egmen)
152 -- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
153 -
154 -### 0.22.0 (October 01, 2021)
155 -
156 -Fixes and Functionality:
157 -- Caseless header comparing in HTTP adapter ([#2880](https://github.com/axios/axios/pull/2880))
158 -- Avoid package.json import fixing issues and warnings related to this ([#4041](https://github.com/axios/axios/pull/4041)), ([#4065](https://github.com/axios/axios/pull/4065))
159 -- Fixed cancelToken leakage and added AbortController support ([#3305](https://github.com/axios/axios/pull/3305))
160 -- Updating CI to run on release branches
161 -- Bump follow redirects version
162 -- Fixed default transitional config for custom Axios instance; ([#4052](https://github.com/axios/axios/pull/4052))
163 -
164 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
165 -
166 -- [Jay](mailto:jasonsaayman@gmail.com)
167 -- [Matt R. Wilson](https://github.com/mastermatt)
168 -- [Xianming Zhong](https://github.com/chinesedfan)
169 -- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
170 -
171 -### 0.21.4 (September 6, 2021)
172 -
173 -Fixes and Functionality:
174 -- Fixing JSON transform when data is stringified. Providing backward compatibility and complying to the JSON RFC standard ([#4020](https://github.com/axios/axios/pull/4020))
175 -
176 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
177 -
178 -- [Jay](mailto:jasonsaayman@gmail.com)
179 -- [Guillaume Fortaine](https://github.com/gfortaine)
180 -- [Yusuke Kawasaki](https://github.com/kawanet)
181 -- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
182 -
183 -### 0.21.3 (September 4, 2021)
184 -
185 -Fixes and Functionality:
186 -- Fixing response interceptor not being called when request interceptor is attached ([#4013](https://github.com/axios/axios/pull/4013))
187 -
188 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
189 -
190 -- [Jay](mailto:jasonsaayman@gmail.com)
191 -- [Julian Hollmann](https://github.com/nerdbeere)
192 -
193 -### 0.21.2 (September 4, 2021)
194 -
195 -Fixes and Functionality:
196 -
197 -- Updating axios requests to be delayed by pre-emptive promise creation ([#2702](https://github.com/axios/axios/pull/2702))
198 -- Adding "synchronous" and "runWhen" options to interceptors api ([#2702](https://github.com/axios/axios/pull/2702))
199 -- Updating of transformResponse ([#3377](https://github.com/axios/axios/pull/3377))
200 -- Adding ability to omit User-Agent header ([#3703](https://github.com/axios/axios/pull/3703))
201 -- Adding multiple JSON improvements ([#3688](https://github.com/axios/axios/pull/3688), [#3763](https://github.com/axios/axios/pull/3763))
202 -- Fixing quadratic runtime and extra memory usage when setting a maxContentLength ([#3738](https://github.com/axios/axios/pull/3738))
203 -- Adding parseInt to config.timeout ([#3781](https://github.com/axios/axios/pull/3781))
204 -- Adding custom return type support to interceptor ([#3783](https://github.com/axios/axios/pull/3783))
205 -- Adding security fix for ReDoS vulnerability ([#3980](https://github.com/axios/axios/pull/3980))
206 -
207 -Internal and Tests:
208 -
209 -- Updating build dev dependencies ([#3401](https://github.com/axios/axios/pull/3401))
210 -- Fixing builds running on Travis CI ([#3538](https://github.com/axios/axios/pull/3538))
211 -- Updating follow redirect version ([#3694](https://github.com/axios/axios/pull/3694), [#3771](https://github.com/axios/axios/pull/3771))
212 -- Updating karma sauce launcher to fix failing sauce tests ([#3712](https://github.com/axios/axios/pull/3712), [#3717](https://github.com/axios/axios/pull/3717))
213 -- Updating content-type header for application/json to not contain charset field, according do RFC 8259 ([#2154](https://github.com/axios/axios/pull/2154))
214 -- Fixing tests by bumping karma-sauce-launcher version ([#3813](https://github.com/axios/axios/pull/3813))
215 -- Changing testing process from Travis CI to GitHub Actions ([#3938](https://github.com/axios/axios/pull/3938))
216 -
217 -Documentation:
218 -
219 -- Updating documentation around the use of `AUTH_TOKEN` with multiple domain endpoints ([#3539](https://github.com/axios/axios/pull/3539))
220 -- Remove duplication of item in changelog ([#3523](https://github.com/axios/axios/pull/3523))
221 -- Fixing grammatical errors ([#2642](https://github.com/axios/axios/pull/2642))
222 -- Fixing spelling error ([#3567](https://github.com/axios/axios/pull/3567))
223 -- Moving gitpod mention ([#2637](https://github.com/axios/axios/pull/2637))
224 -- Adding new axios documentation website link ([#3681](https://github.com/axios/axios/pull/3681), [#3707](https://github.com/axios/axios/pull/3707))
225 -- Updating documentation around dispatching requests ([#3772](https://github.com/axios/axios/pull/3772))
226 -- Adding documentation for the type guard isAxiosError ([#3767](https://github.com/axios/axios/pull/3767))
227 -- Adding explanation of cancel token ([#3803](https://github.com/axios/axios/pull/3803))
228 -- Updating CI status badge ([#3953](https://github.com/axios/axios/pull/3953))
229 -- Fixing errors with JSON documentation ([#3936](https://github.com/axios/axios/pull/3936))
230 -- Fixing README typo under Request Config ([#3825](https://github.com/axios/axios/pull/3825))
231 -- Adding axios-multi-api to the ecosystem file ([#3817](https://github.com/axios/axios/pull/3817))
232 -- Adding SECURITY.md to properly disclose security vulnerabilities ([#3981](https://github.com/axios/axios/pull/3981))
233 -
234 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
235 -
236 -- [Jay](mailto:jasonsaayman@gmail.com)
237 -- [Sasha Korotkov](https://github.com/SashaKoro)
238 -- [Daniel Lopretto](https://github.com/timemachine3030)
239 -- [Mike Bishop](https://github.com/MikeBishop)
240 -- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
241 -- [Mark](https://github.com/bimbiltu)
242 -- [Philipe Gouveia Paixão](https://github.com/piiih)
243 -- [hippo](https://github.com/hippo2cat)
244 -- [ready-research](https://github.com/ready-research)
245 -- [Xianming Zhong](https://github.com/chinesedfan)
246 -- [Christopher Chrapka](https://github.com/OJezu)
247 -- [Brian Anglin](https://github.com/anglinb)
248 -- [Kohta Ito](https://github.com/koh110)
249 -- [Ali Clark](https://github.com/aliclark)
250 -- [caikan](https://github.com/caikan)
251 -- [Elina Gorshkova](https://github.com/elinagorshkova)
252 -- [Ryota Ikezawa](https://github.com/paveg)
253 -- [Nisar Hassan Naqvi](https://github.com/nisarhassan12)
254 -- [Jake](https://github.com/codemaster138)
255 -- [TagawaHirotaka](https://github.com/wafuwafu13)
256 -- [Johannes Jarbratt](https://github.com/johachi)
257 -- [Mo Sattler](https://github.com/MoSattler)
258 -- [Sam Carlton](https://github.com/ThatGuySam)
259 -- [Matt Czapliński](https://github.com/MattCCC)
260 -- [Ziding Zhang](https://github.com/zidingz)
261 -
262 -### 0.21.1 (December 21, 2020)
263 -
264 -Fixes and Functionality:
265 -
266 -- Hotfix: Prevent SSRF ([#3410](https://github.com/axios/axios/pull/3410))
267 -- Protocol not parsed when setting proxy config from env vars ([#3070](https://github.com/axios/axios/pull/3070))
268 -- Updating axios in types to be lower case ([#2797](https://github.com/axios/axios/pull/2797))
269 -- Adding a type guard for `AxiosError` ([#2949](https://github.com/axios/axios/pull/2949))
270 -
271 -Internal and Tests:
272 -
273 -- Remove the skipping of the `socket` http test ([#3364](https://github.com/axios/axios/pull/3364))
274 -- Use different socket for Win32 test ([#3375](https://github.com/axios/axios/pull/3375))
275 -
276 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
277 -
278 -- Daniel Lopretto <timemachine3030@users.noreply.github.com>
279 -- Jason Kwok <JasonHK@users.noreply.github.com>
280 -- Jay <jasonsaayman@gmail.com>
281 -- Jonathan Foster <jonathan@jonathanfoster.io>
282 -- Remco Haszing <remcohaszing@gmail.com>
283 -- Xianming Zhong <chinesedfan@qq.com>
284 -
285 -### 0.21.0 (October 23, 2020)
286 -
287 -Fixes and Functionality:
288 -
289 -- Fixing requestHeaders.Authorization ([#3287](https://github.com/axios/axios/pull/3287))
290 -- Fixing node types ([#3237](https://github.com/axios/axios/pull/3237))
291 -- Fixing axios.delete ignores config.data ([#3282](https://github.com/axios/axios/pull/3282))
292 -- Revert "Fixing overwrite Blob/File type as Content-Type in browser. (#1773)" ([#3289](https://github.com/axios/axios/pull/3289))
293 -- 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))
294 -
295 -Internal and Tests:
296 -
297 -- Lock travis to not use node v15 ([#3361](https://github.com/axios/axios/pull/3361))
298 -
299 -Documentation:
300 -
301 -- Fixing simple typo, existent -> existent ([#3252](https://github.com/axios/axios/pull/3252))
302 -- Fixing typos ([#3309](https://github.com/axios/axios/pull/3309))
303 -
304 -Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
305 -
306 -- Allan Cruz <57270969+Allanbcruz@users.noreply.github.com>
307 -- George Cheng <Gerhut@GMail.com>
308 -- Jay <jasonsaayman@gmail.com>
309 -- Kevin Kirsche <Kev.Kirsche+GitHub@gmail.com>
310 -- Remco Haszing <remcohaszing@gmail.com>
311 -- Taemin Shin <cprayer13@gmail.com>
312 -- Tim Gates <tim.gates@iress.com>
313 -- Xianming Zhong <chinesedfan@qq.com>
314 -
315 -### 0.20.0 (August 20, 2020)
316 -
317 -Release of 0.20.0-pre as a full release with no other changes.
318 -
319 -### 0.20.0-pre (July 15, 2020)
320 -
321 -Fixes and Functionality:
322 -
323 -- Fixing response with utf-8 BOM can not parse to json ([#2419](https://github.com/axios/axios/pull/2419))
324 - - fix: remove byte order marker (UTF-8 BOM) when transform response
325 - - fix: remove BOM only utf-8
326 - - test: utf-8 BOM
327 - - fix: incorrect param name
328 -- Refactor mergeConfig without utils.deepMerge ([#2844](https://github.com/axios/axios/pull/2844))
329 - - Adding failing test
330 - - Fixing #2587 default custom config persisting
331 - - Adding Concat keys and filter duplicates
332 - - Fixed value from CPE
333 - - update for review feedbacks
334 - - no deepMerge
335 - - only merge between plain objects
336 - - fix rename
337 - - always merge config by mergeConfig
338 - - extract function mergeDeepProperties
339 - - refactor mergeConfig with all keys, and add special logic for validateStatus
340 - - add test for resetting headers
341 - - add lots of tests and fix a bug
342 - - should not inherit `data`
343 - - use simple toString
344 -- Fixing overwrite Blob/File type as Content-Type in browser. ([#1773](https://github.com/axios/axios/pull/1773))
345 -- Fixing an issue that type 'null' is not assignable to validateStatus ([#2773](https://github.com/axios/axios/pull/2773))
346 -- Fixing special char encoding ([#1671](https://github.com/axios/axios/pull/1671))
347 - - removing @ character from replacement list since it is a reserved character
348 - - Updating buildURL test to not include the @ character
349 - - Removing console logs
350 -- Fixing password encoding with special characters in basic authentication ([#1492](https://github.com/axios/axios/pull/1492))
351 - - Fixing password encoding with special characters in basic authentication
352 - - Adding test to check if password with non-Latin1 characters pass
353 -- Fixing 'Network Error' in react native android ([#1487](https://github.com/axios/axios/pull/1487))
354 - 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.
355 -- Fixing Cookie Helper with Async Components ([#1105](https://github.com/axios/axios/pull/1105)) ([#1107](https://github.com/axios/axios/pull/1107))
356 -- Fixing 'progressEvent' type ([#2851](https://github.com/axios/axios/pull/2851))
357 - - Fix 'progressEvent' type
358 - - Update axios.ts
359 -- Fixing getting local files (file://) failed ([#2470](https://github.com/axios/axios/pull/2470))
360 - - fix issue #2416, #2396
361 - - fix Eslint warn
362 - - Modify judgment conditions
363 - - add unit test
364 - - update unit test
365 - - update unit test
366 -- Allow PURGE method in typings ([#2191](https://github.com/axios/axios/pull/2191))
367 -- Adding option to disable automatic decompression ([#2661](https://github.com/axios/axios/pull/2661))
368 - - Adding ability to disable auto decompression
369 - - Updating decompress documentation in README
370 - - Fixing test\unit\adapters\http.js lint errors
371 - - Adding test for disabling auto decompression
372 - - Removing changes that fixed lint errors in tests
373 - - Removing formatting change to unit test
374 -- Add independent `maxBodyLength` option ([#2781](https://github.com/axios/axios/pull/2781))
375 - - Add independent option to set the maximum size of the request body
376 - - Remove maxBodyLength check
377 - - Update README
378 - - Assert for error code and message
379 -- Adding responseEncoding to mergeConfig ([#1745](https://github.com/axios/axios/pull/1745))
380 -- Compatible with follow-redirect aborts the request ([#2689](https://github.com/axios/axios/pull/2689))
381 - - Compatible with follow-redirect aborts the request
382 - - Use the error code
383 -- Fix merging of params ([#2656](https://github.com/axios/axios/pull/2656))
384 - - Name function to avoid ESLint func-names warning
385 - - Switch params config to merge list and update tests
386 - - Restore testing of both false and null
387 - - Restore test cases for keys without defaults
388 - - Include test for non-object values that aren't false-y.
389 -- Revert `finally` as `then` ([#2683](https://github.com/axios/axios/pull/2683))
390 -
391 -Internal and Tests:
392 -
393 -- Fix stale bot config ([#3049](https://github.com/axios/axios/pull/3049))
394 - - fix stale bot config
395 - - fix multiple lines
396 -- Add days and change name to work ([#3035](https://github.com/axios/axios/pull/3035))
397 -- Update close-issues.yml ([#3031](https://github.com/axios/axios/pull/3031))
398 - - Update close-issues.yml
399 - Update close message to read better 😄
400 - - Fix use of quotations
401 - Use single quotes as per other .yml files
402 - - Remove user name form message
403 -- Add GitHub actions to close stale issues/prs ([#3029](https://github.com/axios/axios/pull/3029))
404 - - prepare stale actions
405 - - update messages
406 - - Add exempt labels and lighten up comments
407 -- Add GitHub actions to close invalid issues ([#3022](https://github.com/axios/axios/pull/3022))
408 - - add close actions
409 - - fix with checkout
410 - - update issue templates
411 - - add reminder
412 - - update close message
413 -- Add test with Node.js 12 ([#2860](https://github.com/axios/axios/pull/2860))
414 - - test with Node.js 12
415 - - test with latest
416 -- Adding console log on sandbox server startup ([#2210](https://github.com/axios/axios/pull/2210))
417 - - Adding console log on sandbox server startup
418 - - Update server.js
419 - Add server error handling
420 - - Update server.js
421 - Better error message, remove retry.
422 -- Adding tests for method `options` type definitions ([#1996](https://github.com/axios/axios/pull/1996))
423 - Update tests.
424 -- Add test for redirecting with too large response ([#2695](https://github.com/axios/axios/pull/2695))
425 -- Fixing unit test failure in Windows OS ([#2601](https://github.com/axios/axios/pull/2601))
426 -- Fixing issue for HEAD method and gzipped response ([#2666](https://github.com/axios/axios/pull/2666))
427 -- Fix tests in browsers ([#2748](https://github.com/axios/axios/pull/2748))
428 -- chore: add `jsdelivr` and `unpkg` support ([#2443](https://github.com/axios/axios/pull/2443))
429 -
430 -Documentation:
431 -
432 -- Adding support for URLSearchParams in node ([#1900](https://github.com/axios/axios/pull/1900))
433 - - Adding support for URLSearchParams in node
434 - - Remove un-needed code
435 - - Update utils.js
436 - - Make changes as suggested
437 -- Adding table of content (preview) ([#3050](https://github.com/axios/axios/pull/3050))
438 - - add toc (preview)
439 - - remove toc in toc
440 - Signed-off-by: Moni <usmoni@gmail.com>
441 - - fix sublinks
442 - - fix indentation
443 - - remove redundant table links
444 - - update caps and indent
445 - - remove axios
446 -- Replace 'blacklist' with 'blocklist' ([#3006](https://github.com/axios/axios/pull/3006))
447 -- docs(): Detailed config options environment. ([#2088](https://github.com/axios/axios/pull/2088))
448 - - docs(): Detailed config options environment.
449 - - Update README.md
450 -- Include axios-data-unpacker in ECOSYSTEM.md ([#2080](https://github.com/axios/axios/pull/2080))
451 -- Allow opening examples in Gitpod ([#1958](https://github.com/axios/axios/pull/1958))
452 -- Remove axios.all() and axios.spread() from Readme.md ([#2727](https://github.com/axios/axios/pull/2727))
453 - - remove axios.all(), axios.spread()
454 - - replace example
455 - - axios.all() -> Promise.all()
456 - - axios.spread(function (acct, perms)) -> function (acct, perms)
457 - - add deprecated mark
458 -- Update README.md ([#2887](https://github.com/axios/axios/pull/2887))
459 - 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.
460 -- Include swagger-taxos-codegen in ECOSYSTEM.md ([#2162](https://github.com/axios/axios/pull/2162))
461 -- Add CDNJS version badge in README.md ([#878](https://github.com/axios/axios/pull/878))
462 - This badge will show the version on CDNJS!
463 -- Documentation update to clear up ambiguity in code examples ([#2928](https://github.com/axios/axios/pull/2928))
464 - - 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.
465 -- Update README.md about validateStatus ([#2912](https://github.com/axios/axios/pull/2912))
466 - 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"
467 -- Updating documentation for usage form-data ([#2805](https://github.com/axios/axios/pull/2805))
468 - Closes #2049
469 -- Fixing CHANGELOG.md issue link ([#2784](https://github.com/axios/axios/pull/2784))
470 -- Include axios-hooks in ECOSYSTEM.md ([#2003](https://github.com/axios/axios/pull/2003))
471 -- Added Response header access instructions ([#1901](https://github.com/axios/axios/pull/1901))
472 - - Added Response header access instructions
473 - - Added note about using bracket notation
474 -- Add `onUploadProgress` and `onDownloadProgress` are browser only ([#2763](https://github.com/axios/axios/pull/2763))
475 - Saw in #928 and #1966 that `onUploadProgress` and `onDownloadProgress` only work in the browser and was missing that from the README.
476 -- Update ' sign to ` in proxy spec ([#2778](https://github.com/axios/axios/pull/2778))
477 -- Adding jsDelivr link in README ([#1110](https://github.com/axios/axios/pull/1110))
478 - - Adding jsDelivr link
479 - - Add SRI
480 - - Remove SRI
481 -
482 -Huge thanks to everyone who contributed to this release via code (authors listed
483 -below) or via reviews and triaging on GitHub:
484 -
485 -- Alan Wang <wp_scut@163.com>
486 -- Alexandru Ungureanu <khakcarot@gmail.com>
487 -- Anubhav Srivastava <anubhav.srivastava00@gmail.com>
488 -- Benny Neugebauer <bn@bennyn.de>
489 -- Cr <631807682@qq.com>
490 -- David <cygnidavid@gmail.com>
491 -- David Ko <david.ko@pvtmethod.com>
492 -- David Tanner <david.tanner@lifeomic.com>
493 -- Emily Morehouse <emilyemorehouse@gmail.com>
494 -- Felipe Martins <felipewmartins@gmail.com>
495 -- Fonger <5862369+Fonger@users.noreply.github.com>
496 -- Frostack <soulburn007@gmail.com>
497 -- George Cheng <Gerhut@GMail.com>
498 -- grumblerchester <grumblerchester@users.noreply.github.com>
499 -- Gustavo López <gualopezb@gmail.com>
500 -- hexaez <45806662+hexaez@users.noreply.github.com>
501 -- huangzuizui <huangzuizui@gmail.com>
502 -- Ian Wijma <ian@wij.ma>
503 -- Jay <jasonsaayman@gmail.com>
504 -- jeffjing <zgayjjf@qq.com>
505 -- jennynju <46782518+jennynju@users.noreply.github.com>
506 -- Jimmy Liao <52391190+jimmy-liao-gogoro@users.noreply.github.com>
507 -- Jonathan Sharpe <j.r.sharpe@gmail.com>
508 -- JounQin <admin@1stg.me>
509 -- Justin Beckwith <justin.beckwith@gmail.com>
510 -- Kamil Posiadała <3dcreator.pl@gmail.com>
511 -- Lukas Drgon <lukas.drgon@gmail.com>
512 -- marcinx <mail@marcinx.com>
513 -- Martti Laine <martti@codeclown.net>
514 -- Michał Zarach <michal.m.zarach@gmail.com>
515 -- Moni <usmoni@gmail.com>
516 -- Motonori Iwata <121048+iwata@users.noreply.github.com>
517 -- Nikita Galkin <nikita@galk.in>
518 -- Petr Mares <petr@mares.tw>
519 -- Philippe Recto <precto1285@gmal.com>
520 -- Remco Haszing <remcohaszing@gmail.com>
521 -- rockcs1992 <chengshi1219@gmail.com>
522 -- Ryan Bown <rbown@niftee.com.au>
523 -- Samina Fu <sufuf3@gmail.com>
524 -- Simone Busoli <simone.busoli@gmail.com>
525 -- Spencer von der Ohe <s.vonderohe40@gmail.com>
526 -- Sven Efftinge <sven.efftinge@typefox.io>
527 -- Taegyeoung Oh <otk1090@naver.com>
528 -- Taemin Shin <cprayer13@gmail.com>
529 -- Thibault Ehrhart <1208424+ehrhart@users.noreply.github.com>
530 -- Xianming Zhong <chinesedfan@qq.com>
531 -- Yasu Flores <carlosyasu91@gmail.com>
532 -- Zac Delventhal <delventhalz@gmail.com>
533 -
534 -### 0.19.2 (Jan 20, 2020)
535 -
536 -- Remove unnecessary XSS check ([#2679](https://github.com/axios/axios/pull/2679)) (see ([#2646](https://github.com/axios/axios/issues/2646)) for discussion)
537 -
538 -### 0.19.1 (Jan 7, 2020)
539 -
540 -Fixes and Functionality:
541 -
542 -- Fixing invalid agent issue ([#1904](https://github.com/axios/axios/pull/1904))
543 -- Fix ignore set withCredentials false ([#2582](https://github.com/axios/axios/pull/2582))
544 -- Delete useless default to hash ([#2458](https://github.com/axios/axios/pull/2458))
545 -- Fix HTTP/HTTPs agents passing to follow-redirect ([#1904](https://github.com/axios/axios/pull/1904))
546 -- Fix ignore set withCredentials false ([#2582](https://github.com/axios/axios/pull/2582))
547 -- Fix CI build failure ([#2570](https://github.com/axios/axios/pull/2570))
548 -- Remove dependency on is-buffer from package.json ([#1816](https://github.com/axios/axios/pull/1816))
549 -- Adding options typings ([#2341](https://github.com/axios/axios/pull/2341))
550 -- Adding Typescript HTTP method definition for LINK and UNLINK. ([#2444](https://github.com/axios/axios/pull/2444))
551 -- Update dist with newest changes, fixes Custom Attributes issue
552 -- Change syntax to see if build passes ([#2488](https://github.com/axios/axios/pull/2488))
553 -- Update Webpack + deps, remove now unnecessary polyfills ([#2410](https://github.com/axios/axios/pull/2410))
554 -- Fix to prevent XSS, throw an error when the URL contains a JS script ([#2464](https://github.com/axios/axios/pull/2464))
555 -- Add custom timeout error copy in config ([#2275](https://github.com/axios/axios/pull/2275))
556 -- Add error toJSON example ([#2466](https://github.com/axios/axios/pull/2466))
557 -- Fixing Vulnerability A Fortify Scan finds a critical Cross-Site Scrip… ([#2451](https://github.com/axios/axios/pull/2451))
558 -- Fixing subdomain handling on no_proxy ([#2442](https://github.com/axios/axios/pull/2442))
559 -- Make redirection from HTTP to HTTPS work ([#2426](https://github.com/axios/axios/pull/2426)) and ([#2547](https://github.com/axios/axios/pull/2547))
560 -- Add toJSON property to AxiosError type ([#2427](https://github.com/axios/axios/pull/2427))
561 -- Fixing socket hang up error on node side for slow response. ([#1752](https://github.com/axios/axios/pull/1752))
562 -- Alternative syntax to send data into the body ([#2317](https://github.com/axios/axios/pull/2317))
563 -- Fixing custom config options ([#2207](https://github.com/axios/axios/pull/2207))
564 -- Fixing set `config.method` after mergeConfig for Axios.prototype.request ([#2383](https://github.com/axios/axios/pull/2383))
565 -- Axios create url bug ([#2290](https://github.com/axios/axios/pull/2290))
566 -- Do not modify config.url when using a relative baseURL (resolves [#1628](https://github.com/axios/axios/issues/1098)) ([#2391](https://github.com/axios/axios/pull/2391))
567 -
568 -Internal:
569 -
570 -- Revert "Update Webpack + deps, remove now unnecessary polyfills" ([#2479](https://github.com/axios/axios/pull/2479))
571 -- Order of if/else blocks is causing unit tests mocking XHR. ([#2201](https://github.com/axios/axios/pull/2201))
572 -- Add license badge ([#2446](https://github.com/axios/axios/pull/2446))
573 -- Fix travis CI build [#2386](https://github.com/axios/axios/pull/2386)
574 -- Fix cancellation error on build master. #2290 #2207 ([#2407](https://github.com/axios/axios/pull/2407))
575 -
576 -Documentation:
577 -
578 -- Fixing typo in CHANGELOG.md: s/Functionallity/Functionality ([#2639](https://github.com/axios/axios/pull/2639))
579 -- Fix badge, use master branch ([#2538](https://github.com/axios/axios/pull/2538))
580 -- Fix typo in changelog [#2193](https://github.com/axios/axios/pull/2193)
581 -- Document fix ([#2514](https://github.com/axios/axios/pull/2514))
582 -- Update docs with no_proxy change, issue #2484 ([#2513](https://github.com/axios/axios/pull/2513))
583 -- Fixing missing words in docs template ([#2259](https://github.com/axios/axios/pull/2259))
584 -- 🐛Fix request finally documentation in README ([#2189](https://github.com/axios/axios/pull/2189))
585 -- updating spelling and adding link to docs ([#2212](https://github.com/axios/axios/pull/2212))
586 -- docs: minor tweak ([#2404](https://github.com/axios/axios/pull/2404))
587 -- Update response interceptor docs ([#2399](https://github.com/axios/axios/pull/2399))
588 -- Update README.md ([#2504](https://github.com/axios/axios/pull/2504))
589 -- Fix word 'sintaxe' to 'syntax' in README.md ([#2432](https://github.com/axios/axios/pull/2432))
590 -- updating README: notes on CommonJS autocomplete ([#2256](https://github.com/axios/axios/pull/2256))
591 -- Fix grammar in README.md ([#2271](https://github.com/axios/axios/pull/2271))
592 -- Doc fixes, minor examples cleanup ([#2198](https://github.com/axios/axios/pull/2198))
593 -
594 -### 0.19.0 (May 30, 2019)
595 -
596 -Fixes and Functionality:
597 -
598 -- Added support for no_proxy env variable ([#1693](https://github.com/axios/axios/pull/1693/files)) - Chance Dickson
599 -- Unzip response body only for statuses != 204 ([#1129](https://github.com/axios/axios/pull/1129)) - drawski
600 -- Destroy stream on exceeding maxContentLength (fixes [#1098](https://github.com/axios/axios/issues/1098)) ([#1485](https://github.com/axios/axios/pull/1485)) - Gadzhi Gadzhiev
601 -- Makes Axios error generic to use AxiosResponse ([#1738](https://github.com/axios/axios/pull/1738)) - Suman Lama
602 -- Fixing Mocha tests by locking follow-redirects version to 1.5.10 ([#1993](https://github.com/axios/axios/pull/1993)) - grumblerchester
603 -- Allow uppercase methods in typings. ([#1781](https://github.com/axios/axios/pull/1781)) - Ken Powers
604 -- Fixing building url with hash mark ([#1771](https://github.com/axios/axios/pull/1771)) - Anatoly Ryabov
605 -- This commit fix building url with hash map (fragment identifier) when parameters are present: they must not be added after `#`, because client cut everything after `#`
606 -- Preserve HTTP method when following redirect ([#1758](https://github.com/axios/axios/pull/1758)) - Rikki Gibson
607 -- Add `getUri` signature to TypeScript definition. ([#1736](https://github.com/axios/axios/pull/1736)) - Alexander Trauzzi
608 -- Adding isAxiosError flag to errors thrown by axios ([#1419](https://github.com/axios/axios/pull/1419)) - Ayush Gupta
609 -
610 -Internal:
611 -
612 -- Fixing .eslintrc without extension ([#1789](https://github.com/axios/axios/pull/1789)) - Manoel
613 -- Fix failing SauceLabs tests by updating configuration - Emily Morehouse
614 -- Add issue templates - Emily Morehouse
615 -
616 -Documentation:
617 -
618 -- Consistent coding style in README ([#1787](https://github.com/axios/axios/pull/1787)) - Ali Servet Donmez
619 -- Add information about auth parameter to README ([#2166](https://github.com/axios/axios/pull/2166)) - xlaguna
620 -- Add DELETE to list of methods that allow data as a config option ([#2169](https://github.com/axios/axios/pull/2169)) - Daniela Borges Matos de Carvalho
621 -- Update ECOSYSTEM.md - Add Axios Endpoints ([#2176](https://github.com/axios/axios/pull/2176)) - Renan
622 -- Add r2curl in ECOSYSTEM ([#2141](https://github.com/axios/axios/pull/2141)) - 유용우 / CX
623 -- Update README.md - Add instructions for installing with yarn ([#2036](https://github.com/axios/axios/pull/2036)) - Victor Hermes
624 -- Fixing spacing for README.md ([#2066](https://github.com/axios/axios/pull/2066)) - Josh McCarty
625 -- Update README.md. - Change `.then` to `.finally` in example code ([#2090](https://github.com/axios/axios/pull/2090)) - Omar Cai
626 -- Clarify what values responseType can have in Node ([#2121](https://github.com/axios/axios/pull/2121)) - Tyler Breisacher
627 -- docs(ECOSYSTEM): add axios-api-versioning ([#2020](https://github.com/axios/axios/pull/2020)) - Weffe
628 -- It seems that `responseType: 'blob'` doesn't actually work in Node (when I tried using it, response.data was a string, not a Blob, since Node doesn't have Blobs), so this clarifies that this option should only be used in the browser
629 -- Update README.md. - Add Querystring library note ([#1896](https://github.com/axios/axios/pull/1896)) - Dmitriy Eroshenko
630 -- Add react-hooks-axios to Libraries section of ECOSYSTEM.md ([#1925](https://github.com/axios/axios/pull/1925)) - Cody Chan
631 -- Clarify in README that default timeout is 0 (no timeout) ([#1750](https://github.com/axios/axios/pull/1750)) - Ben Standefer
632 -
633 -### 0.19.0-beta.1 (Aug 9, 2018)
634 -
635 -**NOTE:** This is a beta version of this release. There may be functionality that is broken in
636 -certain browsers, though we suspect that builds are hanging and not erroring. See
637 -https://saucelabs.com/u/axios for the most up-to-date information.
638 -
639 -New Functionality:
640 -
641 -- Add getUri method ([#1712](https://github.com/axios/axios/issues/1712))
642 -- Add support for no_proxy env variable ([#1693](https://github.com/axios/axios/issues/1693))
643 -- Add toJSON to decorated Axios errors to facilitate serialization ([#1625](https://github.com/axios/axios/issues/1625))
644 -- Add second then on axios call ([#1623](https://github.com/axios/axios/issues/1623))
645 -- Typings: allow custom return types
646 -- Add option to specify character set in responses (with http adapter)
647 -
648 -Fixes:
649 -
650 -- Fix Keep defaults local to instance ([#385](https://github.com/axios/axios/issues/385))
651 -- Correctly catch exception in http test ([#1475](https://github.com/axios/axios/issues/1475))
652 -- Fix accept header normalization ([#1698](https://github.com/axios/axios/issues/1698))
653 -- Fix http adapter to allow HTTPS connections via HTTP ([#959](https://github.com/axios/axios/issues/959))
654 -- Fix Removes usage of deprecated Buffer constructor. ([#1555](https://github.com/axios/axios/issues/1555), [#1622](https://github.com/axios/axios/issues/1622))
655 -- Fix defaults to use httpAdapter if available ([#1285](https://github.com/axios/axios/issues/1285))
656 - - Fixing defaults to use httpAdapter if available
657 - - Use a safer, cross-platform method to detect the Node environment
658 -- Fix Reject promise if request is cancelled by the browser ([#537](https://github.com/axios/axios/issues/537))
659 -- [Typescript] Fix missing type parameters on delete/head methods
660 -- [NS]: Send `false` flag isStandardBrowserEnv for Nativescript
661 -- Fix missing type parameters on delete/head
662 -- Fix Default method for an instance always overwritten by get
663 -- Fix type error when socketPath option in AxiosRequestConfig
664 -- Capture errors on request data streams
665 -- Decorate resolve and reject to clear timeout in all cases
666 -
667 -Huge thanks to everyone who contributed to this release via code (authors listed
668 -below) or via reviews and triaging on GitHub:
669 -
670 -- Andrew Scott <ascott18@gmail.com>
671 -- Anthony Gauthier <antho325@hotmail.com>
672 -- arpit <arpit2438735@gmail.com>
673 -- ascott18
674 -- Benedikt Rötsch <axe312ger@users.noreply.github.com>
675 -- Chance Dickson <me@chancedickson.com>
676 -- Dave Stewart <info@davestewart.co.uk>
677 -- Deric Cain <deric.cain@gmail.com>
678 -- Guillaume Briday <guillaumebriday@gmail.com>
679 -- Jacob Wejendorp <jacob@wejendorp.dk>
680 -- Jim Lynch <mrdotjim@gmail.com>
681 -- johntron
682 -- Justin Beckwith <beckwith@google.com>
683 -- Justin Beckwith <justin.beckwith@gmail.com>
684 -- Khaled Garbaya <khaledgarbaya@gmail.com>
685 -- Lim Jing Rong <jjingrong@users.noreply.github.com>
686 -- Mark van den Broek <mvdnbrk@gmail.com>
687 -- Martti Laine <martti@codeclown.net>
688 -- mattridley
689 -- mattridley <matt.r@joinblink.com>
690 -- Nicolas Del Valle <nicolas.delvalle@gmail.com>
691 -- Nilegfx
692 -- pbarbiero
693 -- Rikki Gibson <rikkigibson@gmail.com>
694 -- Sako Hartounian <sakohartounian@yahoo.com>
695 -- Shane Fitzpatrick <fitzpasd@gmail.com>
696 -- Stephan Schneider <stephanschndr@gmail.com>
697 -- Steven <steven@ceriously.com>
698 -- Tim Garthwaite <tim.garthwaite@jibo.com>
699 -- Tim Johns <timjohns@yahoo.com>
700 -- Yutaro Miyazaki <yutaro@studio-rubbish.com>
701 -
702 -### 0.18.0 (Feb 19, 2018)
703 -
704 -- Adding support for UNIX Sockets when running with Node.js ([#1070](https://github.com/axios/axios/pull/1070))
705 -- Fixing typings ([#1177](https://github.com/axios/axios/pull/1177)):
706 - - AxiosRequestConfig.proxy: allows type false
707 - - AxiosProxyConfig: added auth field
708 -- Adding function signature in AxiosInstance interface so AxiosInstance can be invoked ([#1192](https://github.com/axios/axios/pull/1192), [#1254](https://github.com/axios/axios/pull/1254))
709 -- Allowing maxContentLength to pass through to redirected calls as maxBodyLength in follow-redirects config ([#1287](https://github.com/axios/axios/pull/1287))
710 -- Fixing configuration when using an instance - method can now be set ([#1342](https://github.com/axios/axios/pull/1342))
711 -
712 -### 0.17.1 (Nov 11, 2017)
713 -
714 -- Fixing issue with web workers ([#1160](https://github.com/axios/axios/pull/1160))
715 -- Allowing overriding transport ([#1080](https://github.com/axios/axios/pull/1080))
716 -- Updating TypeScript typings ([#1165](https://github.com/axios/axios/pull/1165), [#1125](https://github.com/axios/axios/pull/1125), [#1131](https://github.com/axios/axios/pull/1131))
717 -
718 -### 0.17.0 (Oct 21, 2017)
719 -
720 -- **BREAKING** Fixing issue with `baseURL` and interceptors ([#950](https://github.com/axios/axios/pull/950))
721 -- **BREAKING** Improving handing of duplicate headers ([#874](https://github.com/axios/axios/pull/874))
722 -- Adding support for disabling proxies ([#691](https://github.com/axios/axios/pull/691))
723 -- Updating TypeScript typings with generic type parameters ([#1061](https://github.com/axios/axios/pull/1061))
724 -
725 -### 0.16.2 (Jun 3, 2017)
726 -
727 -- Fixing issue with including `buffer` in bundle ([#887](https://github.com/axios/axios/pull/887))
728 -- Including underlying request in errors ([#830](https://github.com/axios/axios/pull/830))
729 -- Convert `method` to lowercase ([#930](https://github.com/axios/axios/pull/930))
730 -
731 -### 0.16.1 (Apr 8, 2017)
732 -
733 -- Improving HTTP adapter to return last request in case of redirects ([#828](https://github.com/axios/axios/pull/828))
734 -- Updating `follow-redirects` dependency ([#829](https://github.com/axios/axios/pull/829))
735 -- Adding support for passing `Buffer` in node ([#773](https://github.com/axios/axios/pull/773))
736 -
737 -### 0.16.0 (Mar 31, 2017)
738 -
739 -- **BREAKING** Removing `Promise` from axios typings in favor of built-in type declarations ([#480](https://github.com/axios/axios/issues/480))
740 -- Adding `options` shortcut method ([#461](https://github.com/axios/axios/pull/461))
741 -- Fixing issue with using `responseType: 'json'` in browsers incompatible with XHR Level 2 ([#654](https://github.com/axios/axios/pull/654))
742 -- Improving React Native detection ([#731](https://github.com/axios/axios/pull/731))
743 -- Fixing `combineURLs` to support empty `relativeURL` ([#581](https://github.com/axios/axios/pull/581))
744 -- Removing `PROTECTION_PREFIX` support ([#561](https://github.com/axios/axios/pull/561))
745 -
746 -### 0.15.3 (Nov 27, 2016)
747 -
748 -- Fixing issue with custom instances and global defaults ([#443](https://github.com/axios/axios/issues/443))
749 -- Renaming `axios.d.ts` to `index.d.ts` ([#519](https://github.com/axios/axios/issues/519))
750 -- Adding `get`, `head`, and `delete` to `defaults.headers` ([#509](https://github.com/axios/axios/issues/509))
751 -- Fixing issue with `btoa` and IE ([#507](https://github.com/axios/axios/issues/507))
752 -- Adding support for proxy authentication ([#483](https://github.com/axios/axios/pull/483))
753 -- Improving HTTP adapter to use `http` protocol by default ([#493](https://github.com/axios/axios/pull/493))
754 -- Fixing proxy issues ([#491](https://github.com/axios/axios/pull/491))
755 -
756 -### 0.15.2 (Oct 17, 2016)
757 -
758 -- Fixing issue with calling `cancel` after response has been received ([#482](https://github.com/axios/axios/issues/482))
759 -
760 -### 0.15.1 (Oct 14, 2016)
761 -
762 -- Fixing issue with UMD ([#485](https://github.com/axios/axios/issues/485))
763 -
764 -### 0.15.0 (Oct 10, 2016)
765 -
766 -- Adding cancellation support ([#452](https://github.com/axios/axios/pull/452))
767 -- Moving default adapter to global defaults ([#437](https://github.com/axios/axios/pull/437))
768 -- Fixing issue with `file` URI scheme ([#440](https://github.com/axios/axios/pull/440))
769 -- Fixing issue with `params` objects that have no prototype ([#445](https://github.com/axios/axios/pull/445))
770 -
771 -### 0.14.0 (Aug 27, 2016)
772 -
773 -- **BREAKING** Updating TypeScript definitions ([#419](https://github.com/axios/axios/pull/419))
774 -- **BREAKING** Replacing `agent` option with `httpAgent` and `httpsAgent` ([#387](https://github.com/axios/axios/pull/387))
775 -- **BREAKING** Splitting `progress` event handlers into `onUploadProgress` and `onDownloadProgress` ([#423](https://github.com/axios/axios/pull/423))
776 -- Adding support for `http_proxy` and `https_proxy` environment variables ([#366](https://github.com/axios/axios/pull/366))
777 -- Fixing issue with `auth` config option and `Authorization` header ([#397](https://github.com/axios/axios/pull/397))
778 -- Don't set XSRF header if `xsrfCookieName` is `null` ([#406](https://github.com/axios/axios/pull/406))
779 -
780 -### 0.13.1 (Jul 16, 2016)
781 -
782 -- Fixing issue with response data not being transformed on error ([#378](https://github.com/axios/axios/issues/378))
783 -
784 -### 0.13.0 (Jul 13, 2016)
785 -
786 -- **BREAKING** Improved error handling ([#345](https://github.com/axios/axios/pull/345))
787 -- **BREAKING** Response transformer now invoked in dispatcher not adapter ([10eb238](https://github.com/axios/axios/commit/10eb23865101f9347570552c04e9d6211376e25e))
788 -- **BREAKING** Request adapters now return a `Promise` ([157efd5](https://github.com/axios/axios/commit/157efd5615890301824e3121cc6c9d2f9b21f94a))
789 -- Fixing issue with `withCredentials` not being overwritten ([#343](https://github.com/axios/axios/issues/343))
790 -- Fixing regression with request transformer being called before request interceptor ([#352](https://github.com/axios/axios/issues/352))
791 -- Fixing custom instance defaults ([#341](https://github.com/axios/axios/issues/341))
792 -- Fixing instances created from `axios.create` to have same API as default axios ([#217](https://github.com/axios/axios/issues/217))
793 -
794 -### 0.12.0 (May 31, 2016)
795 -
796 -- Adding support for `URLSearchParams` ([#317](https://github.com/axios/axios/pull/317))
797 -- Adding `maxRedirects` option ([#307](https://github.com/axios/axios/pull/307))
798 -
799 -### 0.11.1 (May 17, 2016)
800 -
801 -- Fixing IE CORS support ([#313](https://github.com/axios/axios/pull/313))
802 -- Fixing detection of `FormData` ([#325](https://github.com/axios/axios/pull/325))
803 -- Adding `Axios` class to exports ([#321](https://github.com/axios/axios/pull/321))
804 -
805 -### 0.11.0 (Apr 26, 2016)
806 -
807 -- Adding support for Stream with HTTP adapter ([#296](https://github.com/axios/axios/pull/296))
808 -- Adding support for custom HTTP status code error ranges ([#308](https://github.com/axios/axios/pull/308))
809 -- Fixing issue with ArrayBuffer ([#299](https://github.com/axios/axios/pull/299))
810 -
811 -### 0.10.0 (Apr 20, 2016)
812 -
813 -- Fixing issue with some requests sending `undefined` instead of `null` ([#250](https://github.com/axios/axios/pull/250))
814 -- Fixing basic auth for HTTP adapter ([#252](https://github.com/axios/axios/pull/252))
815 -- Fixing request timeout for XHR adapter ([#227](https://github.com/axios/axios/pull/227))
816 -- Fixing IE8 support by using `onreadystatechange` instead of `onload` ([#249](https://github.com/axios/axios/pull/249))
817 -- Fixing IE9 cross domain requests ([#251](https://github.com/axios/axios/pull/251))
818 -- Adding `maxContentLength` option ([#275](https://github.com/axios/axios/pull/275))
819 -- Fixing XHR support for WebWorker environment ([#279](https://github.com/axios/axios/pull/279))
820 -- Adding request instance to response ([#200](https://github.com/axios/axios/pull/200))
821 -
822 -### 0.9.1 (Jan 24, 2016)
823 -
824 -- Improving handling of request timeout in node ([#124](https://github.com/axios/axios/issues/124))
825 -- Fixing network errors not rejecting ([#205](https://github.com/axios/axios/pull/205))
826 -- Fixing issue with IE rejecting on HTTP 204 ([#201](https://github.com/axios/axios/issues/201))
827 -- Fixing host/port when following redirects ([#198](https://github.com/axios/axios/pull/198))
828 -
829 -### 0.9.0 (Jan 18, 2016)
830 -
831 -- Adding support for custom adapters
832 -- Fixing Content-Type header being removed when data is false ([#195](https://github.com/axios/axios/pull/195))
833 -- Improving XDomainRequest implementation ([#185](https://github.com/axios/axios/pull/185))
834 -- Improving config merging and order of precedence ([#183](https://github.com/axios/axios/pull/183))
835 -- Fixing XDomainRequest support for only <= IE9 ([#182](https://github.com/axios/axios/pull/182))
836 -
837 -### 0.8.1 (Dec 14, 2015)
838 -
839 -- Adding support for passing XSRF token for cross domain requests when using `withCredentials` ([#168](https://github.com/axios/axios/pull/168))
840 -- Fixing error with format of basic auth header ([#178](https://github.com/axios/axios/pull/173))
841 -- Fixing error with JSON payloads throwing `InvalidStateError` in some cases ([#174](https://github.com/axios/axios/pull/174))
842 -
843 -### 0.8.0 (Dec 11, 2015)
844 -
845 -- Adding support for creating instances of axios ([#123](https://github.com/axios/axios/pull/123))
846 -- Fixing http adapter to use `Buffer` instead of `String` in case of `responseType === 'arraybuffer'` ([#128](https://github.com/axios/axios/pull/128))
847 -- Adding support for using custom parameter serializer with `paramsSerializer` option ([#121](https://github.com/axios/axios/pull/121))
848 -- Fixing issue in IE8 caused by `forEach` on `arguments` ([#127](https://github.com/axios/axios/pull/127))
849 -- Adding support for following redirects in node ([#146](https://github.com/axios/axios/pull/146))
850 -- Adding support for transparent decompression if `content-encoding` is set ([#149](https://github.com/axios/axios/pull/149))
851 -- Adding support for transparent XDomainRequest to handle cross domain requests in IE9 ([#140](https://github.com/axios/axios/pull/140))
852 -- Adding support for HTTP basic auth via Authorization header ([#167](https://github.com/axios/axios/pull/167))
853 -- Adding support for baseURL option ([#160](https://github.com/axios/axios/pull/160))
854 -
855 -### 0.7.0 (Sep 29, 2015)
856 -
857 -- Fixing issue with minified bundle in IE8 ([#87](https://github.com/axios/axios/pull/87))
858 -- Adding support for passing agent in node ([#102](https://github.com/axios/axios/pull/102))
859 -- Adding support for returning result from `axios.spread` for chaining ([#106](https://github.com/axios/axios/pull/106))
860 -- Fixing typescript definition ([#105](https://github.com/axios/axios/pull/105))
861 -- Fixing default timeout config for node ([#112](https://github.com/axios/axios/pull/112))
862 -- Adding support for use in web workers, and react-native ([#70](https://github.com/axios/axios/issue/70)), ([#98](https://github.com/axios/axios/pull/98))
863 -- Adding support for fetch like API `axios(url[, config])` ([#116](https://github.com/axios/axios/issues/116))
864 -
865 -### 0.6.0 (Sep 21, 2015)
866 -
867 -- Removing deprecated success/error aliases
868 -- Fixing issue with array params not being properly encoded ([#49](https://github.com/axios/axios/pull/49))
869 -- Fixing issue with User-Agent getting overridden ([#69](https://github.com/axios/axios/issues/69))
870 -- Adding support for timeout config ([#56](https://github.com/axios/axios/issues/56))
871 -- Removing es6-promise dependency
872 -- Fixing issue preventing `length` to be used as a parameter ([#91](https://github.com/axios/axios/pull/91))
873 -- Fixing issue with IE8 ([#85](https://github.com/axios/axios/pull/85))
874 -- Converting build to UMD
875 -
876 -### 0.5.4 (Apr 08, 2015)
877 -
878 -- Fixing issue with FormData not being sent ([#53](https://github.com/axios/axios/issues/53))
879 -
880 -### 0.5.3 (Apr 07, 2015)
881 -
882 -- Using JSON.parse unconditionally when transforming response string ([#55](https://github.com/axios/axios/issues/55))
883 -
884 -### 0.5.2 (Mar 13, 2015)
885 -
886 -- Adding support for `statusText` in response ([#46](https://github.com/axios/axios/issues/46))
887 -
888 -### 0.5.1 (Mar 10, 2015)
889 -
890 -- Fixing issue using strict mode ([#45](https://github.com/axios/axios/issues/45))
891 -- Fixing issue with standalone build ([#47](https://github.com/axios/axios/issues/47))
892 -
893 -### 0.5.0 (Jan 23, 2015)
894 -
895 -- Adding support for intercepetors ([#14](https://github.com/axios/axios/issues/14))
896 -- Updating es6-promise dependency
897 -
898 -### 0.4.2 (Dec 10, 2014)
899 -
900 -- Fixing issue with `Content-Type` when using `FormData` ([#22](https://github.com/axios/axios/issues/22))
901 -- Adding support for TypeScript ([#25](https://github.com/axios/axios/issues/25))
902 -- Fixing issue with standalone build ([#29](https://github.com/axios/axios/issues/29))
903 -- Fixing issue with verbs needing to be capitalized in some browsers ([#30](https://github.com/axios/axios/issues/30))
904 -
905 -### 0.4.1 (Oct 15, 2014)
906 -
907 -- Adding error handling to request for node.js ([#18](https://github.com/axios/axios/issues/18))
908 -
909 -### 0.4.0 (Oct 03, 2014)
910 -
911 -- Adding support for `ArrayBuffer` and `ArrayBufferView` ([#10](https://github.com/axios/axios/issues/10))
912 -- Adding support for utf-8 for node.js ([#13](https://github.com/axios/axios/issues/13))
913 -- Adding support for SSL for node.js ([#12](https://github.com/axios/axios/issues/12))
914 -- Fixing incorrect `Content-Type` header ([#9](https://github.com/axios/axios/issues/9))
915 -- Adding standalone build without bundled es6-promise ([#11](https://github.com/axios/axios/issues/11))
916 -- Deprecating `success`/`error` in favor of `then`/`catch`
917 -
918 -### 0.3.1 (Sep 16, 2014)
919 -
920 -- Fixing missing post body when using node.js ([#3](https://github.com/axios/axios/issues/3))
921 -
922 -### 0.3.0 (Sep 16, 2014)
923 -
924 -- Fixing `success` and `error` to properly receive response data as individual arguments ([#8](https://github.com/axios/axios/issues/8))
925 -- Updating `then` and `catch` to receive response data as a single object ([#6](https://github.com/axios/axios/issues/6))
926 -- Fixing issue with `all` not working ([#7](https://github.com/axios/axios/issues/7))
927 -
928 -### 0.2.2 (Sep 14, 2014)
929 -
930 -- Fixing bundling with browserify ([#4](https://github.com/axios/axios/issues/4))
931 -
932 -### 0.2.1 (Sep 12, 2014)
933 -
934 -- Fixing build problem causing ridiculous file sizes
935 -
936 -### 0.2.0 (Sep 12, 2014)
937 -
938 -- Adding support for `all` and `spread`
939 -- Adding support for node.js ([#1](https://github.com/axios/axios/issues/1))
940 -
941 -### 0.1.0 (Aug 29, 2014)
942 -
943 -- Initial release
1 -# axios
2 -
3 -[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
4 -[![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios)
5 -![Build status](https://github.com/axios/axios/actions/workflows/ci.yml/badge.svg)
6 -[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/axios/axios)
7 -[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)
8 -[![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios)
9 -[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios)
10 -[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
11 -[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
12 -[![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios)
13 -
14 -Promise based HTTP client for the browser and node.js
15 -
16 -> New axios docs website: [click here](https://axios-http.com/)
17 -
18 -## Table of Contents
19 -
20 - - [Features](#features)
21 - - [Browser Support](#browser-support)
22 - - [Installing](#installing)
23 - - [Example](#example)
24 - - [Axios API](#axios-api)
25 - - [Request method aliases](#request-method-aliases)
26 - - [Concurrency 👎](#concurrency-deprecated)
27 - - [Creating an instance](#creating-an-instance)
28 - - [Instance methods](#instance-methods)
29 - - [Request Config](#request-config)
30 - - [Response Schema](#response-schema)
31 - - [Config Defaults](#config-defaults)
32 - - [Global axios defaults](#global-axios-defaults)
33 - - [Custom instance defaults](#custom-instance-defaults)
34 - - [Config order of precedence](#config-order-of-precedence)
35 - - [Interceptors](#interceptors)
36 - - [Multiple Interceptors](#multiple-interceptors)
37 - - [Handling Errors](#handling-errors)
38 - - [Cancellation](#cancellation)
39 - - [AbortController](#abortcontroller)
40 - - [CancelToken 👎](#canceltoken-deprecated)
41 - - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
42 - - [Browser](#browser)
43 - - [Node.js](#nodejs)
44 - - [Query string](#query-string)
45 - - [Form data](#form-data)
46 - - [Automatic serialization](#-automatic-serialization)
47 - - [Manual FormData passing](#manual-formdata-passing)
48 - - [Semver](#semver)
49 - - [Promises](#promises)
50 - - [TypeScript](#typescript)
51 - - [Resources](#resources)
52 - - [Credits](#credits)
53 - - [License](#license)
54 -
55 -## Features
56 -
57 -- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
58 -- Make [http](http://nodejs.org/api/http.html) requests from node.js
59 -- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
60 -- Intercept request and response
61 -- Transform request and response data
62 -- Cancel requests
63 -- Automatic transforms for JSON data
64 -- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
65 -
66 -## Browser Support
67 -
68 -![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) |
69 ---- | --- | --- | --- | --- | --- |
70 -Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
71 -
72 -[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)
73 -
74 -## Installing
75 -
76 -Using npm:
77 -
78 -```bash
79 -$ npm install axios
80 -```
81 -
82 -Using bower:
83 -
84 -```bash
85 -$ bower install axios
86 -```
87 -
88 -Using yarn:
89 -
90 -```bash
91 -$ yarn add axios
92 -```
93 -
94 -Using jsDelivr CDN:
95 -
96 -```html
97 -<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
98 -```
99 -
100 -Using unpkg CDN:
101 -
102 -```html
103 -<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
104 -```
105 -
106 -## Example
107 -
108 -### note: CommonJS usage
109 -In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
110 -
111 -```js
112 -const axios = require('axios').default;
113 -
114 -// axios.<method> will now provide autocomplete and parameter typings
115 -```
116 -
117 -Performing a `GET` request
118 -
119 -```js
120 -const axios = require('axios').default;
121 -
122 -// Make a request for a user with a given ID
123 -axios.get('/user?ID=12345')
124 - .then(function (response) {
125 - // handle success
126 - console.log(response);
127 - })
128 - .catch(function (error) {
129 - // handle error
130 - console.log(error);
131 - })
132 - .then(function () {
133 - // always executed
134 - });
135 -
136 -// Optionally the request above could also be done as
137 -axios.get('/user', {
138 - params: {
139 - ID: 12345
140 - }
141 - })
142 - .then(function (response) {
143 - console.log(response);
144 - })
145 - .catch(function (error) {
146 - console.log(error);
147 - })
148 - .then(function () {
149 - // always executed
150 - });
151 -
152 -// Want to use async/await? Add the `async` keyword to your outer function/method.
153 -async function getUser() {
154 - try {
155 - const response = await axios.get('/user?ID=12345');
156 - console.log(response);
157 - } catch (error) {
158 - console.error(error);
159 - }
160 -}
161 -```
162 -
163 -> **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet
164 -> Explorer and older browsers, so use with caution.
165 -
166 -Performing a `POST` request
167 -
168 -```js
169 -axios.post('/user', {
170 - firstName: 'Fred',
171 - lastName: 'Flintstone'
172 - })
173 - .then(function (response) {
174 - console.log(response);
175 - })
176 - .catch(function (error) {
177 - console.log(error);
178 - });
179 -```
180 -
181 -Performing multiple concurrent requests
182 -
183 -```js
184 -function getUserAccount() {
185 - return axios.get('/user/12345');
186 -}
187 -
188 -function getUserPermissions() {
189 - return axios.get('/user/12345/permissions');
190 -}
191 -
192 -Promise.all([getUserAccount(), getUserPermissions()])
193 - .then(function (results) {
194 - const acct = results[0];
195 - const perm = results[1];
196 - });
197 -```
198 -
199 -## axios API
200 -
201 -Requests can be made by passing the relevant config to `axios`.
202 -
203 -##### axios(config)
204 -
205 -```js
206 -// Send a POST request
207 -axios({
208 - method: 'post',
209 - url: '/user/12345',
210 - data: {
211 - firstName: 'Fred',
212 - lastName: 'Flintstone'
213 - }
214 -});
215 -```
216 -
217 -```js
218 -// GET request for remote image in node.js
219 -axios({
220 - method: 'get',
221 - url: 'http://bit.ly/2mTM3nY',
222 - responseType: 'stream'
223 -})
224 - .then(function (response) {
225 - response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
226 - });
227 -```
228 -
229 -##### axios(url[, config])
230 -
231 -```js
232 -// Send a GET request (default method)
233 -axios('/user/12345');
234 -```
235 -
236 -### Request method aliases
237 -
238 -For convenience, aliases have been provided for all common request methods.
239 -
240 -##### axios.request(config)
241 -##### axios.get(url[, config])
242 -##### axios.delete(url[, config])
243 -##### axios.head(url[, config])
244 -##### axios.options(url[, config])
245 -##### axios.post(url[, data[, config]])
246 -##### axios.put(url[, data[, config]])
247 -##### axios.patch(url[, data[, config]])
248 -
249 -###### NOTE
250 -When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
251 -
252 -### Concurrency (Deprecated)
253 -Please use `Promise.all` to replace the below functions.
254 -
255 -Helper functions for dealing with concurrent requests.
256 -
257 -axios.all(iterable)
258 -axios.spread(callback)
259 -
260 -### Creating an instance
261 -
262 -You can create a new instance of axios with a custom config.
263 -
264 -##### axios.create([config])
265 -
266 -```js
267 -const instance = axios.create({
268 - baseURL: 'https://some-domain.com/api/',
269 - timeout: 1000,
270 - headers: {'X-Custom-Header': 'foobar'}
271 -});
272 -```
273 -
274 -### Instance methods
275 -
276 -The available instance methods are listed below. The specified config will be merged with the instance config.
277 -
278 -##### axios#request(config)
279 -##### axios#get(url[, config])
280 -##### axios#delete(url[, config])
281 -##### axios#head(url[, config])
282 -##### axios#options(url[, config])
283 -##### axios#post(url[, data[, config]])
284 -##### axios#put(url[, data[, config]])
285 -##### axios#patch(url[, data[, config]])
286 -##### axios#getUri([config])
287 -
288 -## Request Config
289 -
290 -These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
291 -
292 -```js
293 -{
294 - // `url` is the server URL that will be used for the request
295 - url: '/user',
296 -
297 - // `method` is the request method to be used when making the request
298 - method: 'get', // default
299 -
300 - // `baseURL` will be prepended to `url` unless `url` is absolute.
301 - // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
302 - // to methods of that instance.
303 - baseURL: 'https://some-domain.com/api/',
304 -
305 - // `transformRequest` allows changes to the request data before it is sent to the server
306 - // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
307 - // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
308 - // FormData or Stream
309 - // You may modify the headers object.
310 - transformRequest: [function (data, headers) {
311 - // Do whatever you want to transform the data
312 -
313 - return data;
314 - }],
315 -
316 - // `transformResponse` allows changes to the response data to be made before
317 - // it is passed to then/catch
318 - transformResponse: [function (data) {
319 - // Do whatever you want to transform the data
320 -
321 - return data;
322 - }],
323 -
324 - // `headers` are custom headers to be sent
325 - headers: {'X-Requested-With': 'XMLHttpRequest'},
326 -
327 - // `params` are the URL parameters to be sent with the request
328 - // Must be a plain object or a URLSearchParams object
329 - params: {
330 - ID: 12345
331 - },
332 -
333 - // `paramsSerializer` is an optional function in charge of serializing `params`
334 - // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
335 - paramsSerializer: function (params) {
336 - return Qs.stringify(params, {arrayFormat: 'brackets'})
337 - },
338 -
339 - // `data` is the data to be sent as the request body
340 - // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
341 - // When no `transformRequest` is set, must be of one of the following types:
342 - // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
343 - // - Browser only: FormData, File, Blob
344 - // - Node only: Stream, Buffer
345 - data: {
346 - firstName: 'Fred'
347 - },
348 -
349 - // syntax alternative to send data into the body
350 - // method post
351 - // only the value is sent, not the key
352 - data: 'Country=Brasil&City=Belo Horizonte',
353 -
354 - // `timeout` specifies the number of milliseconds before the request times out.
355 - // If the request takes longer than `timeout`, the request will be aborted.
356 - timeout: 1000, // default is `0` (no timeout)
357 -
358 - // `withCredentials` indicates whether or not cross-site Access-Control requests
359 - // should be made using credentials
360 - withCredentials: false, // default
361 -
362 - // `adapter` allows custom handling of requests which makes testing easier.
363 - // Return a promise and supply a valid response (see lib/adapters/README.md).
364 - adapter: function (config) {
365 - /* ... */
366 - },
367 -
368 - // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
369 - // This will set an `Authorization` header, overwriting any existing
370 - // `Authorization` custom headers you have set using `headers`.
371 - // Please note that only HTTP Basic auth is configurable through this parameter.
372 - // For Bearer tokens and such, use `Authorization` custom headers instead.
373 - auth: {
374 - username: 'janedoe',
375 - password: 's00pers3cret'
376 - },
377 -
378 - // `responseType` indicates the type of data that the server will respond with
379 - // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
380 - // browser only: 'blob'
381 - responseType: 'json', // default
382 -
383 - // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
384 - // Note: Ignored for `responseType` of 'stream' or client-side requests
385 - responseEncoding: 'utf8', // default
386 -
387 - // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
388 - xsrfCookieName: 'XSRF-TOKEN', // default
389 -
390 - // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
391 - xsrfHeaderName: 'X-XSRF-TOKEN', // default
392 -
393 - // `onUploadProgress` allows handling of progress events for uploads
394 - // browser only
395 - onUploadProgress: function (progressEvent) {
396 - // Do whatever you want with the native progress event
397 - },
398 -
399 - // `onDownloadProgress` allows handling of progress events for downloads
400 - // browser only
401 - onDownloadProgress: function (progressEvent) {
402 - // Do whatever you want with the native progress event
403 - },
404 -
405 - // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
406 - maxContentLength: 2000,
407 -
408 - // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
409 - maxBodyLength: 2000,
410 -
411 - // `validateStatus` defines whether to resolve or reject the promise for a given
412 - // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
413 - // or `undefined`), the promise will be resolved; otherwise, the promise will be
414 - // rejected.
415 - validateStatus: function (status) {
416 - return status >= 200 && status < 300; // default
417 - },
418 -
419 - // `maxRedirects` defines the maximum number of redirects to follow in node.js.
420 - // If set to 0, no redirects will be followed.
421 - maxRedirects: 21, // default
422 -
423 - // `beforeRedirect` defines a function that will be called before redirect.
424 - // Use this to adjust the request options upon redirecting,
425 - // to inspect the latest response headers,
426 - // or to cancel the request by throwing an error
427 - // If maxRedirects is set to 0, `beforeRedirect` is not used.
428 - beforeRedirect: (options, { headers }) => {
429 - if (options.hostname === "example.com") {
430 - options.auth = "user:password";
431 - }
432 - };
433 -
434 - // `socketPath` defines a UNIX Socket to be used in node.js.
435 - // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
436 - // Only either `socketPath` or `proxy` can be specified.
437 - // If both are specified, `socketPath` is used.
438 - socketPath: null, // default
439 -
440 - // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
441 - // and https requests, respectively, in node.js. This allows options to be added like
442 - // `keepAlive` that are not enabled by default.
443 - httpAgent: new http.Agent({ keepAlive: true }),
444 - httpsAgent: new https.Agent({ keepAlive: true }),
445 -
446 - // `proxy` defines the hostname, port, and protocol of the proxy server.
447 - // You can also define your proxy using the conventional `http_proxy` and
448 - // `https_proxy` environment variables. If you are using environment variables
449 - // for your proxy configuration, you can also define a `no_proxy` environment
450 - // variable as a comma-separated list of domains that should not be proxied.
451 - // Use `false` to disable proxies, ignoring environment variables.
452 - // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
453 - // supplies credentials.
454 - // This will set an `Proxy-Authorization` header, overwriting any existing
455 - // `Proxy-Authorization` custom headers you have set using `headers`.
456 - // If the proxy server uses HTTPS, then you must set the protocol to `https`.
457 - proxy: {
458 - protocol: 'https',
459 - host: '127.0.0.1',
460 - port: 9000,
461 - auth: {
462 - username: 'mikeymike',
463 - password: 'rapunz3l'
464 - }
465 - },
466 -
467 - // `cancelToken` specifies a cancel token that can be used to cancel the request
468 - // (see Cancellation section below for details)
469 - cancelToken: new CancelToken(function (cancel) {
470 - }),
471 -
472 - // an alternative way to cancel Axios requests using AbortController
473 - signal: new AbortController().signal,
474 -
475 - // `decompress` indicates whether or not the response body should be decompressed
476 - // automatically. If set to `true` will also remove the 'content-encoding' header
477 - // from the responses objects of all decompressed responses
478 - // - Node only (XHR cannot turn off decompression)
479 - decompress: true // default
480 -
481 - // `insecureHTTPParser` boolean.
482 - // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
483 - // This may allow interoperability with non-conformant HTTP implementations.
484 - // Using the insecure parser should be avoided.
485 - // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
486 - // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
487 - insecureHTTPParser: undefined // default
488 -
489 - // transitional options for backward compatibility that may be removed in the newer versions
490 - transitional: {
491 - // silent JSON parsing mode
492 - // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
493 - // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
494 - silentJSONParsing: true, // default value for the current Axios version
495 -
496 - // try to parse the response string as JSON even if `responseType` is not 'json'
497 - forcedJSONParsing: true,
498 -
499 - // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
500 - clarifyTimeoutError: false,
501 - },
502 -
503 - env: {
504 - // The FormData class to be used to automatically serialize the payload into a FormData object
505 - FormData: window?.FormData || global?.FormData
506 - }
507 -}
508 -```
509 -
510 -## Response Schema
511 -
512 -The response for a request contains the following information.
513 -
514 -```js
515 -{
516 - // `data` is the response that was provided by the server
517 - data: {},
518 -
519 - // `status` is the HTTP status code from the server response
520 - status: 200,
521 -
522 - // `statusText` is the HTTP status message from the server response
523 - statusText: 'OK',
524 -
525 - // `headers` the HTTP headers that the server responded with
526 - // All header names are lower cased and can be accessed using the bracket notation.
527 - // Example: `response.headers['content-type']`
528 - headers: {},
529 -
530 - // `config` is the config that was provided to `axios` for the request
531 - config: {},
532 -
533 - // `request` is the request that generated this response
534 - // It is the last ClientRequest instance in node.js (in redirects)
535 - // and an XMLHttpRequest instance in the browser
536 - request: {}
537 -}
538 -```
539 -
540 -When using `then`, you will receive the response as follows:
541 -
542 -```js
543 -axios.get('/user/12345')
544 - .then(function (response) {
545 - console.log(response.data);
546 - console.log(response.status);
547 - console.log(response.statusText);
548 - console.log(response.headers);
549 - console.log(response.config);
550 - });
551 -```
552 -
553 -When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section.
554 -
555 -## Config Defaults
556 -
557 -You can specify config defaults that will be applied to every request.
558 -
559 -### Global axios defaults
560 -
561 -```js
562 -axios.defaults.baseURL = 'https://api.example.com';
563 -
564 -// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
565 -// See below for an example using Custom instance defaults instead.
566 -axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
567 -
568 -axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
569 -```
570 -
571 -### Custom instance defaults
572 -
573 -```js
574 -// Set config defaults when creating the instance
575 -const instance = axios.create({
576 - baseURL: 'https://api.example.com'
577 -});
578 -
579 -// Alter defaults after instance has been created
580 -instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
581 -```
582 -
583 -### Config order of precedence
584 -
585 -Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.
586 -
587 -```js
588 -// Create an instance using the config defaults provided by the library
589 -// At this point the timeout config value is `0` as is the default for the library
590 -const instance = axios.create();
591 -
592 -// Override timeout default for the library
593 -// Now all requests using this instance will wait 2.5 seconds before timing out
594 -instance.defaults.timeout = 2500;
595 -
596 -// Override timeout for this request as it's known to take a long time
597 -instance.get('/longRequest', {
598 - timeout: 5000
599 -});
600 -```
601 -
602 -## Interceptors
603 -
604 -You can intercept requests or responses before they are handled by `then` or `catch`.
605 -
606 -```js
607 -// Add a request interceptor
608 -axios.interceptors.request.use(function (config) {
609 - // Do something before request is sent
610 - return config;
611 - }, function (error) {
612 - // Do something with request error
613 - return Promise.reject(error);
614 - });
615 -
616 -// Add a response interceptor
617 -axios.interceptors.response.use(function (response) {
618 - // Any status code that lie within the range of 2xx cause this function to trigger
619 - // Do something with response data
620 - return response;
621 - }, function (error) {
622 - // Any status codes that falls outside the range of 2xx cause this function to trigger
623 - // Do something with response error
624 - return Promise.reject(error);
625 - });
626 -```
627 -
628 -If you need to remove an interceptor later you can.
629 -
630 -```js
631 -const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
632 -axios.interceptors.request.eject(myInterceptor);
633 -```
634 -
635 -You can add interceptors to a custom instance of axios.
636 -
637 -```js
638 -const instance = axios.create();
639 -instance.interceptors.request.use(function () {/*...*/});
640 -```
641 -
642 -When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
643 -in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
644 -the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag
645 -to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
646 -
647 -```js
648 -axios.interceptors.request.use(function (config) {
649 - config.headers.test = 'I am only a header!';
650 - return config;
651 -}, null, { synchronous: true });
652 -```
653 -
654 -If you want to execute a particular interceptor based on a runtime check,
655 -you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return
656 -of `runWhen` is `false`. The function will be called with the config
657 -object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
658 -asynchronous request interceptor that only needs to run at certain times.
659 -
660 -```js
661 -function onGetCall(config) {
662 - return config.method === 'get';
663 -}
664 -axios.interceptors.request.use(function (config) {
665 - config.headers.test = 'special get headers';
666 - return config;
667 -}, null, { runWhen: onGetCall });
668 -```
669 -
670 -### Multiple Interceptors
671 -
672 -Given you add multiple response interceptors
673 -and when the response was fulfilled
674 -- then each interceptor is executed
675 -- then they are executed in the order they were added
676 -- then only the last interceptor's result is returned
677 -- then every interceptor receives the result of it's predecessor
678 -- and when the fulfillment-interceptor throws
679 - - then the following fulfillment-interceptor is not called
680 - - then the following rejection-interceptor is called
681 - - once caught, another following fulfill-interceptor is called again (just like in a promise chain).
682 -
683 -Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code.
684 -
685 -## Handling Errors
686 -
687 -```js
688 -axios.get('/user/12345')
689 - .catch(function (error) {
690 - if (error.response) {
691 - // The request was made and the server responded with a status code
692 - // that falls out of the range of 2xx
693 - console.log(error.response.data);
694 - console.log(error.response.status);
695 - console.log(error.response.headers);
696 - } else if (error.request) {
697 - // The request was made but no response was received
698 - // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
699 - // http.ClientRequest in node.js
700 - console.log(error.request);
701 - } else {
702 - // Something happened in setting up the request that triggered an Error
703 - console.log('Error', error.message);
704 - }
705 - console.log(error.config);
706 - });
707 -```
708 -
709 -Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error.
710 -
711 -```js
712 -axios.get('/user/12345', {
713 - validateStatus: function (status) {
714 - return status < 500; // Resolve only if the status code is less than 500
715 - }
716 -})
717 -```
718 -
719 -Using `toJSON` you get an object with more information about the HTTP error.
720 -
721 -```js
722 -axios.get('/user/12345')
723 - .catch(function (error) {
724 - console.log(error.toJSON());
725 - });
726 -```
727 -
728 -## Cancellation
729 -
730 -### AbortController
731 -
732 -Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way:
733 -
734 -```js
735 -const controller = new AbortController();
736 -
737 -axios.get('/foo/bar', {
738 - signal: controller.signal
739 -}).then(function(response) {
740 - //...
741 -});
742 -// cancel the request
743 -controller.abort()
744 -```
745 -
746 -### CancelToken `👎deprecated`
747 -
748 -You can also cancel a request using a *CancelToken*.
749 -
750 -> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
751 -
752 -> This API is deprecated since v0.22.0 and shouldn't be used in new projects
753 -
754 -You can create a cancel token using the `CancelToken.source` factory as shown below:
755 -
756 -```js
757 -const CancelToken = axios.CancelToken;
758 -const source = CancelToken.source();
759 -
760 -axios.get('/user/12345', {
761 - cancelToken: source.token
762 -}).catch(function (thrown) {
763 - if (axios.isCancel(thrown)) {
764 - console.log('Request canceled', thrown.message);
765 - } else {
766 - // handle error
767 - }
768 -});
769 -
770 -axios.post('/user/12345', {
771 - name: 'new name'
772 -}, {
773 - cancelToken: source.token
774 -})
775 -
776 -// cancel the request (the message parameter is optional)
777 -source.cancel('Operation canceled by the user.');
778 -```
779 -
780 -You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
781 -
782 -```js
783 -const CancelToken = axios.CancelToken;
784 -let cancel;
785 -
786 -axios.get('/user/12345', {
787 - cancelToken: new CancelToken(function executor(c) {
788 - // An executor function receives a cancel function as a parameter
789 - cancel = c;
790 - })
791 -});
792 -
793 -// cancel the request
794 -cancel();
795 -```
796 -
797 -> Note: you can cancel several requests with the same cancel token/abort controller.
798 -> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make real request.
799 -
800 -> During the transition period, you can use both cancellation APIs, even for the same request:
801 -
802 -## Using application/x-www-form-urlencoded format
803 -
804 -By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options.
805 -
806 -### Browser
807 -
808 -In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:
809 -
810 -```js
811 -const params = new URLSearchParams();
812 -params.append('param1', 'value1');
813 -params.append('param2', 'value2');
814 -axios.post('/foo', params);
815 -```
816 -
817 -> Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
818 -
819 -Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
820 -
821 -```js
822 -const qs = require('qs');
823 -axios.post('/foo', qs.stringify({ 'bar': 123 }));
824 -```
825 -
826 -Or in another way (ES6),
827 -
828 -```js
829 -import qs from 'qs';
830 -const data = { 'bar': 123 };
831 -const options = {
832 - method: 'POST',
833 - headers: { 'content-type': 'application/x-www-form-urlencoded' },
834 - data: qs.stringify(data),
835 - url,
836 -};
837 -axios(options);
838 -```
839 -
840 -### Node.js
841 -
842 -#### Query string
843 -
844 -In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
845 -
846 -```js
847 -const querystring = require('querystring');
848 -axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
849 -```
850 -
851 -or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows:
852 -
853 -```js
854 -const url = require('url');
855 -const params = new url.URLSearchParams({ foo: 'bar' });
856 -axios.post('http://something.com/', params.toString());
857 -```
858 -
859 -You can also use the [`qs`](https://github.com/ljharb/qs) library.
860 -
861 -> NOTE:
862 -> The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case.
863 -
864 -#### Form data
865 -
866 -##### 🆕 Automatic serialization
867 -
868 -Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`
869 -header is set to `multipart/form-data`.
870 -
871 -The following request will submit the data in a FormData format (Browser & Node.js):
872 -
873 -```js
874 -import axios from 'axios';
875 -
876 -axios.post('https://httpbin.org/post', {x: 1}, {
877 - headers: {
878 - 'Content-Type': 'multipart/form-data'
879 - }
880 -}).then(({data})=> console.log(data));
881 -```
882 -
883 -In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.
884 -
885 -You can overload the FormData class by setting the `env.FormData` config variable,
886 -but you probably won't need it in most cases:
887 -
888 -```js
889 -const axios= require('axios');
890 -var FormData = require('form-data');
891 -
892 -axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {
893 - headers: {
894 - 'Content-Type': 'multipart/form-data'
895 - }
896 -}).then(({data})=> console.log(data));
897 -```
898 -
899 -Axios FormData serializer supports some special endings to perform the following operations:
900 -
901 -- `{}` - serialize the value with JSON.stringify
902 -- `[]` - unwrap the array like object as separate fields with the same key
903 -
904 -```js
905 -const axios= require('axios');
906 -
907 -axios.post('https://httpbin.org/post', {
908 - 'myObj{}': {x: 1, s: "foo"},
909 - 'files[]': document.querySelector('#fileInput').files
910 -}, {
911 - headers: {
912 - 'Content-Type': 'multipart/form-data'
913 - }
914 -}).then(({data})=> console.log(data));
915 -```
916 -
917 -Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
918 -which are just the corresponding http methods with a header preset: `Content-Type`: `multipart/form-data`.
919 -
920 -FileList object can be passed directly:
921 -
922 -```js
923 -await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
924 -```
925 -
926 -All files will be sent with the same field names: `files[]`;
927 -
928 -##### Manual FormData passing
929 -
930 -In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
931 -
932 -```js
933 -const FormData = require('form-data');
934 -
935 -const form = new FormData();
936 -form.append('my_field', 'my value');
937 -form.append('my_buffer', new Buffer(10));
938 -form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
939 -
940 -axios.post('https://example.com', form)
941 -```
942 -
943 -## Semver
944 -
945 -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.
946 -
947 -## Promises
948 -
949 -axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
950 -If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
951 -
952 -## TypeScript
953 -
954 -axios includes [TypeScript](http://typescriptlang.org) definitions and a type guard for axios errors.
955 -
956 -```typescript
957 -let user: User = null;
958 -try {
959 - const { data } = await axios.get('/user?ID=12345');
960 - user = data.userDetails;
961 -} catch (error) {
962 - if (axios.isAxiosError(error)) {
963 - handleAxiosError(error);
964 - } else {
965 - handleUnexpectedError(error);
966 - }
967 -}
968 -```
969 -
970 -## Online one-click setup
971 -
972 -You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online.
973 -
974 -[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/master/examples/server.js)
975 -
976 -
977 -## Resources
978 -
979 -* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
980 -* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
981 -* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
982 -* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
983 -* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)
984 -
985 -## Credits
986 -
987 -axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [AngularJS](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of AngularJS.
988 -
989 -## License
990 -
991 -[MIT](LICENSE)
1 -# Security Policy
2 -
3 -## Reporting a Vulnerability
4 -
5 -Please report security issues to jasonsaayman@gmail.com
1 -# Upgrade Guide
2 -
3 -### 0.18.x -> 0.19.0
4 -
5 -#### HTTPS Proxies
6 -
7 -Routing through an https proxy now requires setting the `protocol` attribute of the proxy configuration to `https`
8 -
9 -### 0.15.x -> 0.16.0
10 -
11 -#### `Promise` Type Declarations
12 -
13 -The `Promise` type declarations have been removed from the axios typings in favor of the built-in type declarations. If you use axios in a TypeScript project that targets `ES5`, please make sure to include the `es2015.promise` lib. Please see [this post](https://blog.mariusschulz.com/2016/11/25/typescript-2-0-built-in-type-declarations) for details.
14 -
15 -### 0.13.x -> 0.14.0
16 -
17 -#### TypeScript Definitions
18 -
19 -The axios TypeScript definitions have been updated to match the axios API and use the ES2015 module syntax.
20 -
21 -Please use the following `import` statement to import axios in TypeScript:
22 -
23 -```typescript
24 -import axios from 'axios';
25 -
26 -axios.get('/foo')
27 - .then(response => console.log(response))
28 - .catch(error => console.log(error));
29 -```
30 -
31 -#### `agent` Config Option
32 -
33 -The `agent` config option has been replaced with two new options: `httpAgent` and `httpsAgent`. Please use them instead.
34 -
35 -```js
36 -{
37 - // Define a custom agent for HTTP
38 - httpAgent: new http.Agent({ keepAlive: true }),
39 - // Define a custom agent for HTTPS
40 - httpsAgent: new https.Agent({ keepAlive: true })
41 -}
42 -```
43 -
44 -#### `progress` Config Option
45 -
46 -The `progress` config option has been replaced with the `onUploadProgress` and `onDownloadProgress` options.
47 -
48 -```js
49 -{
50 - // Define a handler for upload progress events
51 - onUploadProgress: function (progressEvent) {
52 - // ...
53 - },
54 -
55 - // Define a handler for download progress events
56 - onDownloadProgress: function (progressEvent) {
57 - // ...
58 - }
59 -}
60 -```
61 -
62 -### 0.12.x -> 0.13.0
63 -
64 -The `0.13.0` release contains several changes to custom adapters and error handling.
65 -
66 -#### Error Handling
67 -
68 -Previous to this release an error could either be a server response with bad status code or an actual `Error`. With this release Promise will always reject with an `Error`. In the case that a response was received, the `Error` will also include the response.
69 -
70 -```js
71 -axios.get('/user/12345')
72 - .catch((error) => {
73 - console.log(error.message);
74 - console.log(error.code); // Not always specified
75 - console.log(error.config); // The config that was used to make the request
76 - console.log(error.response); // Only available if response was received from the server
77 - });
78 -```
79 -
80 -#### Request Adapters
81 -
82 -This release changes a few things about how request adapters work. Please take note if you are using your own custom adapter.
83 -
84 -1. Response transformer is now called outside of adapter.
85 -2. Request adapter returns a `Promise`.
86 -
87 -This means that you no longer need to invoke `transformData` on response data. You will also no longer receive `resolve` and `reject` as arguments in your adapter.
88 -
89 -Previous code:
90 -
91 -```js
92 -function myAdapter(resolve, reject, config) {
93 - var response = {
94 - data: transformData(
95 - responseData,
96 - responseHeaders,
97 - config.transformResponse
98 - ),
99 - status: request.status,
100 - statusText: request.statusText,
101 - headers: responseHeaders
102 - };
103 - settle(resolve, reject, response);
104 -}
105 -```
106 -
107 -New code:
108 -
109 -```js
110 -function myAdapter(config) {
111 - return new Promise(function (resolve, reject) {
112 - var response = {
113 - data: responseData,
114 - status: request.status,
115 - statusText: request.statusText,
116 - headers: responseHeaders
117 - };
118 - settle(resolve, reject, response);
119 - });
120 -}
121 -```
122 -
123 -See the related commits for more details:
124 -- [Response transformers](https://github.com/axios/axios/commit/10eb23865101f9347570552c04e9d6211376e25e)
125 -- [Request adapter Promise](https://github.com/axios/axios/commit/157efd5615890301824e3121cc6c9d2f9b21f94a)
126 -
127 -### 0.5.x -> 0.6.0
128 -
129 -The `0.6.0` release contains mostly bug fixes, but there are a couple things to be aware of when upgrading.
130 -
131 -#### ES6 Promise Polyfill
132 -
133 -Up until the `0.6.0` release ES6 `Promise` was being polyfilled using [es6-promise](https://github.com/jakearchibald/es6-promise). With this release, the polyfill has been removed, and you will need to supply it yourself if your environment needs it.
134 -
135 -```js
136 -require('es6-promise').polyfill();
137 -var axios = require('axios');
138 -```
139 -
140 -This will polyfill the global environment, and only needs to be done once.
141 -
142 -#### `axios.success`/`axios.error`
143 -
144 -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.
145 -
146 -```js
147 -axios.get('some/url')
148 - .then(function (res) {
149 - /* ... */
150 - })
151 - .catch(function (err) {
152 - /* ... */
153 - });
154 -```
155 -
156 -#### UMD
157 -
158 -Previous versions of axios shipped with an AMD, CommonJS, and Global build. This has all been rolled into a single UMD build.
159 -
160 -```js
161 -// AMD
162 -require(['bower_components/axios/dist/axios'], function (axios) {
163 - /* ... */
164 -});
165 -
166 -// CommonJS
167 -var axios = require('axios/dist/axios');
168 -```
1 -/* axios v0.27.2 | (c) 2022 by Matt Zabriskie */
2 -(function webpackUniversalModuleDefinition(root, factory) {
3 - if(typeof exports === 'object' && typeof module === 'object')
4 - module.exports = factory();
5 - else if(typeof define === 'function' && define.amd)
6 - define([], factory);
7 - else if(typeof exports === 'object')
8 - exports["axios"] = factory();
9 - else
10 - root["axios"] = factory();
11 -})(this, function() {
12 -return /******/ (function(modules) { // webpackBootstrap
13 -/******/ // The module cache
14 -/******/ var installedModules = {};
15 -/******/
16 -/******/ // The require function
17 -/******/ function __webpack_require__(moduleId) {
18 -/******/
19 -/******/ // Check if module is in cache
20 -/******/ if(installedModules[moduleId]) {
21 -/******/ return installedModules[moduleId].exports;
22 -/******/ }
23 -/******/ // Create a new module (and put it into the cache)
24 -/******/ var module = installedModules[moduleId] = {
25 -/******/ i: moduleId,
26 -/******/ l: false,
27 -/******/ exports: {}
28 -/******/ };
29 -/******/
30 -/******/ // Execute the module function
31 -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
32 -/******/
33 -/******/ // Flag the module as loaded
34 -/******/ module.l = true;
35 -/******/
36 -/******/ // Return the exports of the module
37 -/******/ return module.exports;
38 -/******/ }
39 -/******/
40 -/******/
41 -/******/ // expose the modules object (__webpack_modules__)
42 -/******/ __webpack_require__.m = modules;
43 -/******/
44 -/******/ // expose the module cache
45 -/******/ __webpack_require__.c = installedModules;
46 -/******/
47 -/******/ // define getter function for harmony exports
48 -/******/ __webpack_require__.d = function(exports, name, getter) {
49 -/******/ if(!__webpack_require__.o(exports, name)) {
50 -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
51 -/******/ }
52 -/******/ };
53 -/******/
54 -/******/ // define __esModule on exports
55 -/******/ __webpack_require__.r = function(exports) {
56 -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
57 -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
58 -/******/ }
59 -/******/ Object.defineProperty(exports, '__esModule', { value: true });
60 -/******/ };
61 -/******/
62 -/******/ // create a fake namespace object
63 -/******/ // mode & 1: value is a module id, require it
64 -/******/ // mode & 2: merge all properties of value into the ns
65 -/******/ // mode & 4: return value when already ns object
66 -/******/ // mode & 8|1: behave like require
67 -/******/ __webpack_require__.t = function(value, mode) {
68 -/******/ if(mode & 1) value = __webpack_require__(value);
69 -/******/ if(mode & 8) return value;
70 -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
71 -/******/ var ns = Object.create(null);
72 -/******/ __webpack_require__.r(ns);
73 -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
74 -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
75 -/******/ return ns;
76 -/******/ };
77 -/******/
78 -/******/ // getDefaultExport function for compatibility with non-harmony modules
79 -/******/ __webpack_require__.n = function(module) {
80 -/******/ var getter = module && module.__esModule ?
81 -/******/ function getDefault() { return module['default']; } :
82 -/******/ function getModuleExports() { return module; };
83 -/******/ __webpack_require__.d(getter, 'a', getter);
84 -/******/ return getter;
85 -/******/ };
86 -/******/
87 -/******/ // Object.prototype.hasOwnProperty.call
88 -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
89 -/******/
90 -/******/ // __webpack_public_path__
91 -/******/ __webpack_require__.p = "";
92 -/******/
93 -/******/
94 -/******/ // Load entry module and return exports
95 -/******/ return __webpack_require__(__webpack_require__.s = "./index.js");
96 -/******/ })
97 -/************************************************************************/
98 -/******/ ({
99 -
100 -/***/ "./index.js":
101 -/*!******************!*\
102 - !*** ./index.js ***!
103 - \******************/
104 -/*! no static exports found */
105 -/***/ (function(module, exports, __webpack_require__) {
106 -
107 -module.exports = __webpack_require__(/*! ./lib/axios */ "./lib/axios.js");
108 -
109 -/***/ }),
110 -
111 -/***/ "./lib/adapters/xhr.js":
112 -/*!*****************************!*\
113 - !*** ./lib/adapters/xhr.js ***!
114 - \*****************************/
115 -/*! no static exports found */
116 -/***/ (function(module, exports, __webpack_require__) {
117 -
118 -"use strict";
119 -
120 -
121 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
122 -var settle = __webpack_require__(/*! ./../core/settle */ "./lib/core/settle.js");
123 -var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./lib/helpers/cookies.js");
124 -var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./lib/helpers/buildURL.js");
125 -var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./lib/core/buildFullPath.js");
126 -var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./lib/helpers/parseHeaders.js");
127 -var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./lib/helpers/isURLSameOrigin.js");
128 -var transitionalDefaults = __webpack_require__(/*! ../defaults/transitional */ "./lib/defaults/transitional.js");
129 -var AxiosError = __webpack_require__(/*! ../core/AxiosError */ "./lib/core/AxiosError.js");
130 -var CanceledError = __webpack_require__(/*! ../cancel/CanceledError */ "./lib/cancel/CanceledError.js");
131 -var parseProtocol = __webpack_require__(/*! ../helpers/parseProtocol */ "./lib/helpers/parseProtocol.js");
132 -
133 -module.exports = function xhrAdapter(config) {
134 - return new Promise(function dispatchXhrRequest(resolve, reject) {
135 - var requestData = config.data;
136 - var requestHeaders = config.headers;
137 - var responseType = config.responseType;
138 - var onCanceled;
139 - function done() {
140 - if (config.cancelToken) {
141 - config.cancelToken.unsubscribe(onCanceled);
142 - }
143 -
144 - if (config.signal) {
145 - config.signal.removeEventListener('abort', onCanceled);
146 - }
147 - }
148 -
149 - if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
150 - delete requestHeaders['Content-Type']; // Let the browser set it
151 - }
152 -
153 - var request = new XMLHttpRequest();
154 -
155 - // HTTP basic authentication
156 - if (config.auth) {
157 - var username = config.auth.username || '';
158 - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
159 - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
160 - }
161 -
162 - var fullPath = buildFullPath(config.baseURL, config.url);
163 -
164 - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
165 -
166 - // Set the request timeout in MS
167 - request.timeout = config.timeout;
168 -
169 - function onloadend() {
170 - if (!request) {
171 - return;
172 - }
173 - // Prepare the response
174 - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
175 - var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
176 - request.responseText : request.response;
177 - var response = {
178 - data: responseData,
179 - status: request.status,
180 - statusText: request.statusText,
181 - headers: responseHeaders,
182 - config: config,
183 - request: request
184 - };
185 -
186 - settle(function _resolve(value) {
187 - resolve(value);
188 - done();
189 - }, function _reject(err) {
190 - reject(err);
191 - done();
192 - }, response);
193 -
194 - // Clean up request
195 - request = null;
196 - }
197 -
198 - if ('onloadend' in request) {
199 - // Use onloadend if available
200 - request.onloadend = onloadend;
201 - } else {
202 - // Listen for ready state to emulate onloadend
203 - request.onreadystatechange = function handleLoad() {
204 - if (!request || request.readyState !== 4) {
205 - return;
206 - }
207 -
208 - // The request errored out and we didn't get a response, this will be
209 - // handled by onerror instead
210 - // With one exception: request that using file: protocol, most browsers
211 - // will return status as 0 even though it's a successful request
212 - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
213 - return;
214 - }
215 - // readystate handler is calling before onerror or ontimeout handlers,
216 - // so we should call onloadend on the next 'tick'
217 - setTimeout(onloadend);
218 - };
219 - }
220 -
221 - // Handle browser request cancellation (as opposed to a manual cancellation)
222 - request.onabort = function handleAbort() {
223 - if (!request) {
224 - return;
225 - }
226 -
227 - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
228 -
229 - // Clean up request
230 - request = null;
231 - };
232 -
233 - // Handle low level network errors
234 - request.onerror = function handleError() {
235 - // Real errors are hidden from us by the browser
236 - // onerror should only fire if it's a network error
237 - reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request));
238 -
239 - // Clean up request
240 - request = null;
241 - };
242 -
243 - // Handle timeout
244 - request.ontimeout = function handleTimeout() {
245 - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
246 - var transitional = config.transitional || transitionalDefaults;
247 - if (config.timeoutErrorMessage) {
248 - timeoutErrorMessage = config.timeoutErrorMessage;
249 - }
250 - reject(new AxiosError(
251 - timeoutErrorMessage,
252 - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
253 - config,
254 - request));
255 -
256 - // Clean up request
257 - request = null;
258 - };
259 -
260 - // Add xsrf header
261 - // This is only done if running in a standard browser environment.
262 - // Specifically not if we're in a web worker, or react-native.
263 - if (utils.isStandardBrowserEnv()) {
264 - // Add xsrf header
265 - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
266 - cookies.read(config.xsrfCookieName) :
267 - undefined;
268 -
269 - if (xsrfValue) {
270 - requestHeaders[config.xsrfHeaderName] = xsrfValue;
271 - }
272 - }
273 -
274 - // Add headers to the request
275 - if ('setRequestHeader' in request) {
276 - utils.forEach(requestHeaders, function setRequestHeader(val, key) {
277 - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
278 - // Remove Content-Type if data is undefined
279 - delete requestHeaders[key];
280 - } else {
281 - // Otherwise add header to the request
282 - request.setRequestHeader(key, val);
283 - }
284 - });
285 - }
286 -
287 - // Add withCredentials to request if needed
288 - if (!utils.isUndefined(config.withCredentials)) {
289 - request.withCredentials = !!config.withCredentials;
290 - }
291 -
292 - // Add responseType to request if needed
293 - if (responseType && responseType !== 'json') {
294 - request.responseType = config.responseType;
295 - }
296 -
297 - // Handle progress if needed
298 - if (typeof config.onDownloadProgress === 'function') {
299 - request.addEventListener('progress', config.onDownloadProgress);
300 - }
301 -
302 - // Not all browsers support upload events
303 - if (typeof config.onUploadProgress === 'function' && request.upload) {
304 - request.upload.addEventListener('progress', config.onUploadProgress);
305 - }
306 -
307 - if (config.cancelToken || config.signal) {
308 - // Handle cancellation
309 - // eslint-disable-next-line func-names
310 - onCanceled = function(cancel) {
311 - if (!request) {
312 - return;
313 - }
314 - reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);
315 - request.abort();
316 - request = null;
317 - };
318 -
319 - config.cancelToken && config.cancelToken.subscribe(onCanceled);
320 - if (config.signal) {
321 - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
322 - }
323 - }
324 -
325 - if (!requestData) {
326 - requestData = null;
327 - }
328 -
329 - var protocol = parseProtocol(fullPath);
330 -
331 - if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {
332 - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
333 - return;
334 - }
335 -
336 -
337 - // Send the request
338 - request.send(requestData);
339 - });
340 -};
341 -
342 -
343 -/***/ }),
344 -
345 -/***/ "./lib/axios.js":
346 -/*!**********************!*\
347 - !*** ./lib/axios.js ***!
348 - \**********************/
349 -/*! no static exports found */
350 -/***/ (function(module, exports, __webpack_require__) {
351 -
352 -"use strict";
353 -
354 -
355 -var utils = __webpack_require__(/*! ./utils */ "./lib/utils.js");
356 -var bind = __webpack_require__(/*! ./helpers/bind */ "./lib/helpers/bind.js");
357 -var Axios = __webpack_require__(/*! ./core/Axios */ "./lib/core/Axios.js");
358 -var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./lib/core/mergeConfig.js");
359 -var defaults = __webpack_require__(/*! ./defaults */ "./lib/defaults/index.js");
360 -
361 -/**
362 - * Create an instance of Axios
363 - *
364 - * @param {Object} defaultConfig The default config for the instance
365 - * @return {Axios} A new instance of Axios
366 - */
367 -function createInstance(defaultConfig) {
368 - var context = new Axios(defaultConfig);
369 - var instance = bind(Axios.prototype.request, context);
370 -
371 - // Copy axios.prototype to instance
372 - utils.extend(instance, Axios.prototype, context);
373 -
374 - // Copy context to instance
375 - utils.extend(instance, context);
376 -
377 - // Factory for creating new instances
378 - instance.create = function create(instanceConfig) {
379 - return createInstance(mergeConfig(defaultConfig, instanceConfig));
380 - };
381 -
382 - return instance;
383 -}
384 -
385 -// Create the default instance to be exported
386 -var axios = createInstance(defaults);
387 -
388 -// Expose Axios class to allow class inheritance
389 -axios.Axios = Axios;
390 -
391 -// Expose Cancel & CancelToken
392 -axios.CanceledError = __webpack_require__(/*! ./cancel/CanceledError */ "./lib/cancel/CanceledError.js");
393 -axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./lib/cancel/CancelToken.js");
394 -axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./lib/cancel/isCancel.js");
395 -axios.VERSION = __webpack_require__(/*! ./env/data */ "./lib/env/data.js").version;
396 -axios.toFormData = __webpack_require__(/*! ./helpers/toFormData */ "./lib/helpers/toFormData.js");
397 -
398 -// Expose AxiosError class
399 -axios.AxiosError = __webpack_require__(/*! ../lib/core/AxiosError */ "./lib/core/AxiosError.js");
400 -
401 -// alias for CanceledError for backward compatibility
402 -axios.Cancel = axios.CanceledError;
403 -
404 -// Expose all/spread
405 -axios.all = function all(promises) {
406 - return Promise.all(promises);
407 -};
408 -axios.spread = __webpack_require__(/*! ./helpers/spread */ "./lib/helpers/spread.js");
409 -
410 -// Expose isAxiosError
411 -axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./lib/helpers/isAxiosError.js");
412 -
413 -module.exports = axios;
414 -
415 -// Allow use of default import syntax in TypeScript
416 -module.exports.default = axios;
417 -
418 -
419 -/***/ }),
420 -
421 -/***/ "./lib/cancel/CancelToken.js":
422 -/*!***********************************!*\
423 - !*** ./lib/cancel/CancelToken.js ***!
424 - \***********************************/
425 -/*! no static exports found */
426 -/***/ (function(module, exports, __webpack_require__) {
427 -
428 -"use strict";
429 -
430 -
431 -var CanceledError = __webpack_require__(/*! ./CanceledError */ "./lib/cancel/CanceledError.js");
432 -
433 -/**
434 - * A `CancelToken` is an object that can be used to request cancellation of an operation.
435 - *
436 - * @class
437 - * @param {Function} executor The executor function.
438 - */
439 -function CancelToken(executor) {
440 - if (typeof executor !== 'function') {
441 - throw new TypeError('executor must be a function.');
442 - }
443 -
444 - var resolvePromise;
445 -
446 - this.promise = new Promise(function promiseExecutor(resolve) {
447 - resolvePromise = resolve;
448 - });
449 -
450 - var token = this;
451 -
452 - // eslint-disable-next-line func-names
453 - this.promise.then(function(cancel) {
454 - if (!token._listeners) return;
455 -
456 - var i;
457 - var l = token._listeners.length;
458 -
459 - for (i = 0; i < l; i++) {
460 - token._listeners[i](cancel);
461 - }
462 - token._listeners = null;
463 - });
464 -
465 - // eslint-disable-next-line func-names
466 - this.promise.then = function(onfulfilled) {
467 - var _resolve;
468 - // eslint-disable-next-line func-names
469 - var promise = new Promise(function(resolve) {
470 - token.subscribe(resolve);
471 - _resolve = resolve;
472 - }).then(onfulfilled);
473 -
474 - promise.cancel = function reject() {
475 - token.unsubscribe(_resolve);
476 - };
477 -
478 - return promise;
479 - };
480 -
481 - executor(function cancel(message) {
482 - if (token.reason) {
483 - // Cancellation has already been requested
484 - return;
485 - }
486 -
487 - token.reason = new CanceledError(message);
488 - resolvePromise(token.reason);
489 - });
490 -}
491 -
492 -/**
493 - * Throws a `CanceledError` if cancellation has been requested.
494 - */
495 -CancelToken.prototype.throwIfRequested = function throwIfRequested() {
496 - if (this.reason) {
497 - throw this.reason;
498 - }
499 -};
500 -
501 -/**
502 - * Subscribe to the cancel signal
503 - */
504 -
505 -CancelToken.prototype.subscribe = function subscribe(listener) {
506 - if (this.reason) {
507 - listener(this.reason);
508 - return;
509 - }
510 -
511 - if (this._listeners) {
512 - this._listeners.push(listener);
513 - } else {
514 - this._listeners = [listener];
515 - }
516 -};
517 -
518 -/**
519 - * Unsubscribe from the cancel signal
520 - */
521 -
522 -CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
523 - if (!this._listeners) {
524 - return;
525 - }
526 - var index = this._listeners.indexOf(listener);
527 - if (index !== -1) {
528 - this._listeners.splice(index, 1);
529 - }
530 -};
531 -
532 -/**
533 - * Returns an object that contains a new `CancelToken` and a function that, when called,
534 - * cancels the `CancelToken`.
535 - */
536 -CancelToken.source = function source() {
537 - var cancel;
538 - var token = new CancelToken(function executor(c) {
539 - cancel = c;
540 - });
541 - return {
542 - token: token,
543 - cancel: cancel
544 - };
545 -};
546 -
547 -module.exports = CancelToken;
548 -
549 -
550 -/***/ }),
551 -
552 -/***/ "./lib/cancel/CanceledError.js":
553 -/*!*************************************!*\
554 - !*** ./lib/cancel/CanceledError.js ***!
555 - \*************************************/
556 -/*! no static exports found */
557 -/***/ (function(module, exports, __webpack_require__) {
558 -
559 -"use strict";
560 -
561 -
562 -var AxiosError = __webpack_require__(/*! ../core/AxiosError */ "./lib/core/AxiosError.js");
563 -var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
564 -
565 -/**
566 - * A `CanceledError` is an object that is thrown when an operation is canceled.
567 - *
568 - * @class
569 - * @param {string=} message The message.
570 - */
571 -function CanceledError(message) {
572 - // eslint-disable-next-line no-eq-null,eqeqeq
573 - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED);
574 - this.name = 'CanceledError';
575 -}
576 -
577 -utils.inherits(CanceledError, AxiosError, {
578 - __CANCEL__: true
579 -});
580 -
581 -module.exports = CanceledError;
582 -
583 -
584 -/***/ }),
585 -
586 -/***/ "./lib/cancel/isCancel.js":
587 -/*!********************************!*\
588 - !*** ./lib/cancel/isCancel.js ***!
589 - \********************************/
590 -/*! no static exports found */
591 -/***/ (function(module, exports, __webpack_require__) {
592 -
593 -"use strict";
594 -
595 -
596 -module.exports = function isCancel(value) {
597 - return !!(value && value.__CANCEL__);
598 -};
599 -
600 -
601 -/***/ }),
602 -
603 -/***/ "./lib/core/Axios.js":
604 -/*!***************************!*\
605 - !*** ./lib/core/Axios.js ***!
606 - \***************************/
607 -/*! no static exports found */
608 -/***/ (function(module, exports, __webpack_require__) {
609 -
610 -"use strict";
611 -
612 -
613 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
614 -var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./lib/helpers/buildURL.js");
615 -var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./lib/core/InterceptorManager.js");
616 -var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./lib/core/dispatchRequest.js");
617 -var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./lib/core/mergeConfig.js");
618 -var buildFullPath = __webpack_require__(/*! ./buildFullPath */ "./lib/core/buildFullPath.js");
619 -var validator = __webpack_require__(/*! ../helpers/validator */ "./lib/helpers/validator.js");
620 -
621 -var validators = validator.validators;
622 -/**
623 - * Create a new instance of Axios
624 - *
625 - * @param {Object} instanceConfig The default config for the instance
626 - */
627 -function Axios(instanceConfig) {
628 - this.defaults = instanceConfig;
629 - this.interceptors = {
630 - request: new InterceptorManager(),
631 - response: new InterceptorManager()
632 - };
633 -}
634 -
635 -/**
636 - * Dispatch a request
637 - *
638 - * @param {Object} config The config specific for this request (merged with this.defaults)
639 - */
640 -Axios.prototype.request = function request(configOrUrl, config) {
641 - /*eslint no-param-reassign:0*/
642 - // Allow for axios('example/url'[, config]) a la fetch API
643 - if (typeof configOrUrl === 'string') {
644 - config = config || {};
645 - config.url = configOrUrl;
646 - } else {
647 - config = configOrUrl || {};
648 - }
649 -
650 - config = mergeConfig(this.defaults, config);
651 -
652 - // Set config.method
653 - if (config.method) {
654 - config.method = config.method.toLowerCase();
655 - } else if (this.defaults.method) {
656 - config.method = this.defaults.method.toLowerCase();
657 - } else {
658 - config.method = 'get';
659 - }
660 -
661 - var transitional = config.transitional;
662 -
663 - if (transitional !== undefined) {
664 - validator.assertOptions(transitional, {
665 - silentJSONParsing: validators.transitional(validators.boolean),
666 - forcedJSONParsing: validators.transitional(validators.boolean),
667 - clarifyTimeoutError: validators.transitional(validators.boolean)
668 - }, false);
669 - }
670 -
671 - // filter out skipped interceptors
672 - var requestInterceptorChain = [];
673 - var synchronousRequestInterceptors = true;
674 - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
675 - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
676 - return;
677 - }
678 -
679 - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
680 -
681 - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
682 - });
683 -
684 - var responseInterceptorChain = [];
685 - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
686 - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
687 - });
688 -
689 - var promise;
690 -
691 - if (!synchronousRequestInterceptors) {
692 - var chain = [dispatchRequest, undefined];
693 -
694 - Array.prototype.unshift.apply(chain, requestInterceptorChain);
695 - chain = chain.concat(responseInterceptorChain);
696 -
697 - promise = Promise.resolve(config);
698 - while (chain.length) {
699 - promise = promise.then(chain.shift(), chain.shift());
700 - }
701 -
702 - return promise;
703 - }
704 -
705 -
706 - var newConfig = config;
707 - while (requestInterceptorChain.length) {
708 - var onFulfilled = requestInterceptorChain.shift();
709 - var onRejected = requestInterceptorChain.shift();
710 - try {
711 - newConfig = onFulfilled(newConfig);
712 - } catch (error) {
713 - onRejected(error);
714 - break;
715 - }
716 - }
717 -
718 - try {
719 - promise = dispatchRequest(newConfig);
720 - } catch (error) {
721 - return Promise.reject(error);
722 - }
723 -
724 - while (responseInterceptorChain.length) {
725 - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
726 - }
727 -
728 - return promise;
729 -};
730 -
731 -Axios.prototype.getUri = function getUri(config) {
732 - config = mergeConfig(this.defaults, config);
733 - var fullPath = buildFullPath(config.baseURL, config.url);
734 - return buildURL(fullPath, config.params, config.paramsSerializer);
735 -};
736 -
737 -// Provide aliases for supported request methods
738 -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
739 - /*eslint func-names:0*/
740 - Axios.prototype[method] = function(url, config) {
741 - return this.request(mergeConfig(config || {}, {
742 - method: method,
743 - url: url,
744 - data: (config || {}).data
745 - }));
746 - };
747 -});
748 -
749 -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
750 - /*eslint func-names:0*/
751 -
752 - function generateHTTPMethod(isForm) {
753 - return function httpMethod(url, data, config) {
754 - return this.request(mergeConfig(config || {}, {
755 - method: method,
756 - headers: isForm ? {
757 - 'Content-Type': 'multipart/form-data'
758 - } : {},
759 - url: url,
760 - data: data
761 - }));
762 - };
763 - }
764 -
765 - Axios.prototype[method] = generateHTTPMethod();
766 -
767 - Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
768 -});
769 -
770 -module.exports = Axios;
771 -
772 -
773 -/***/ }),
774 -
775 -/***/ "./lib/core/AxiosError.js":
776 -/*!********************************!*\
777 - !*** ./lib/core/AxiosError.js ***!
778 - \********************************/
779 -/*! no static exports found */
780 -/***/ (function(module, exports, __webpack_require__) {
781 -
782 -"use strict";
783 -
784 -
785 -var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
786 -
787 -/**
788 - * Create an Error with the specified message, config, error code, request and response.
789 - *
790 - * @param {string} message The error message.
791 - * @param {string} [code] The error code (for example, 'ECONNABORTED').
792 - * @param {Object} [config] The config.
793 - * @param {Object} [request] The request.
794 - * @param {Object} [response] The response.
795 - * @returns {Error} The created error.
796 - */
797 -function AxiosError(message, code, config, request, response) {
798 - Error.call(this);
799 - this.message = message;
800 - this.name = 'AxiosError';
801 - code && (this.code = code);
802 - config && (this.config = config);
803 - request && (this.request = request);
804 - response && (this.response = response);
805 -}
806 -
807 -utils.inherits(AxiosError, Error, {
808 - toJSON: function toJSON() {
809 - return {
810 - // Standard
811 - message: this.message,
812 - name: this.name,
813 - // Microsoft
814 - description: this.description,
815 - number: this.number,
816 - // Mozilla
817 - fileName: this.fileName,
818 - lineNumber: this.lineNumber,
819 - columnNumber: this.columnNumber,
820 - stack: this.stack,
821 - // Axios
822 - config: this.config,
823 - code: this.code,
824 - status: this.response && this.response.status ? this.response.status : null
825 - };
826 - }
827 -});
828 -
829 -var prototype = AxiosError.prototype;
830 -var descriptors = {};
831 -
832 -[
833 - 'ERR_BAD_OPTION_VALUE',
834 - 'ERR_BAD_OPTION',
835 - 'ECONNABORTED',
836 - 'ETIMEDOUT',
837 - 'ERR_NETWORK',
838 - 'ERR_FR_TOO_MANY_REDIRECTS',
839 - 'ERR_DEPRECATED',
840 - 'ERR_BAD_RESPONSE',
841 - 'ERR_BAD_REQUEST',
842 - 'ERR_CANCELED'
843 -// eslint-disable-next-line func-names
844 -].forEach(function(code) {
845 - descriptors[code] = {value: code};
846 -});
847 -
848 -Object.defineProperties(AxiosError, descriptors);
849 -Object.defineProperty(prototype, 'isAxiosError', {value: true});
850 -
851 -// eslint-disable-next-line func-names
852 -AxiosError.from = function(error, code, config, request, response, customProps) {
853 - var axiosError = Object.create(prototype);
854 -
855 - utils.toFlatObject(error, axiosError, function filter(obj) {
856 - return obj !== Error.prototype;
857 - });
858 -
859 - AxiosError.call(axiosError, error.message, code, config, request, response);
860 -
861 - axiosError.name = error.name;
862 -
863 - customProps && Object.assign(axiosError, customProps);
864 -
865 - return axiosError;
866 -};
867 -
868 -module.exports = AxiosError;
869 -
870 -
871 -/***/ }),
872 -
873 -/***/ "./lib/core/InterceptorManager.js":
874 -/*!****************************************!*\
875 - !*** ./lib/core/InterceptorManager.js ***!
876 - \****************************************/
877 -/*! no static exports found */
878 -/***/ (function(module, exports, __webpack_require__) {
879 -
880 -"use strict";
881 -
882 -
883 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
884 -
885 -function InterceptorManager() {
886 - this.handlers = [];
887 -}
888 -
889 -/**
890 - * Add a new interceptor to the stack
891 - *
892 - * @param {Function} fulfilled The function to handle `then` for a `Promise`
893 - * @param {Function} rejected The function to handle `reject` for a `Promise`
894 - *
895 - * @return {Number} An ID used to remove interceptor later
896 - */
897 -InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
898 - this.handlers.push({
899 - fulfilled: fulfilled,
900 - rejected: rejected,
901 - synchronous: options ? options.synchronous : false,
902 - runWhen: options ? options.runWhen : null
903 - });
904 - return this.handlers.length - 1;
905 -};
906 -
907 -/**
908 - * Remove an interceptor from the stack
909 - *
910 - * @param {Number} id The ID that was returned by `use`
911 - */
912 -InterceptorManager.prototype.eject = function eject(id) {
913 - if (this.handlers[id]) {
914 - this.handlers[id] = null;
915 - }
916 -};
917 -
918 -/**
919 - * Iterate over all the registered interceptors
920 - *
921 - * This method is particularly useful for skipping over any
922 - * interceptors that may have become `null` calling `eject`.
923 - *
924 - * @param {Function} fn The function to call for each interceptor
925 - */
926 -InterceptorManager.prototype.forEach = function forEach(fn) {
927 - utils.forEach(this.handlers, function forEachHandler(h) {
928 - if (h !== null) {
929 - fn(h);
930 - }
931 - });
932 -};
933 -
934 -module.exports = InterceptorManager;
935 -
936 -
937 -/***/ }),
938 -
939 -/***/ "./lib/core/buildFullPath.js":
940 -/*!***********************************!*\
941 - !*** ./lib/core/buildFullPath.js ***!
942 - \***********************************/
943 -/*! no static exports found */
944 -/***/ (function(module, exports, __webpack_require__) {
945 -
946 -"use strict";
947 -
948 -
949 -var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./lib/helpers/isAbsoluteURL.js");
950 -var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./lib/helpers/combineURLs.js");
951 -
952 -/**
953 - * Creates a new URL by combining the baseURL with the requestedURL,
954 - * only when the requestedURL is not already an absolute URL.
955 - * If the requestURL is absolute, this function returns the requestedURL untouched.
956 - *
957 - * @param {string} baseURL The base URL
958 - * @param {string} requestedURL Absolute or relative URL to combine
959 - * @returns {string} The combined full path
960 - */
961 -module.exports = function buildFullPath(baseURL, requestedURL) {
962 - if (baseURL && !isAbsoluteURL(requestedURL)) {
963 - return combineURLs(baseURL, requestedURL);
964 - }
965 - return requestedURL;
966 -};
967 -
968 -
969 -/***/ }),
970 -
971 -/***/ "./lib/core/dispatchRequest.js":
972 -/*!*************************************!*\
973 - !*** ./lib/core/dispatchRequest.js ***!
974 - \*************************************/
975 -/*! no static exports found */
976 -/***/ (function(module, exports, __webpack_require__) {
977 -
978 -"use strict";
979 -
980 -
981 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
982 -var transformData = __webpack_require__(/*! ./transformData */ "./lib/core/transformData.js");
983 -var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./lib/cancel/isCancel.js");
984 -var defaults = __webpack_require__(/*! ../defaults */ "./lib/defaults/index.js");
985 -var CanceledError = __webpack_require__(/*! ../cancel/CanceledError */ "./lib/cancel/CanceledError.js");
986 -
987 -/**
988 - * Throws a `CanceledError` if cancellation has been requested.
989 - */
990 -function throwIfCancellationRequested(config) {
991 - if (config.cancelToken) {
992 - config.cancelToken.throwIfRequested();
993 - }
994 -
995 - if (config.signal && config.signal.aborted) {
996 - throw new CanceledError();
997 - }
998 -}
999 -
1000 -/**
1001 - * Dispatch a request to the server using the configured adapter.
1002 - *
1003 - * @param {object} config The config that is to be used for the request
1004 - * @returns {Promise} The Promise to be fulfilled
1005 - */
1006 -module.exports = function dispatchRequest(config) {
1007 - throwIfCancellationRequested(config);
1008 -
1009 - // Ensure headers exist
1010 - config.headers = config.headers || {};
1011 -
1012 - // Transform request data
1013 - config.data = transformData.call(
1014 - config,
1015 - config.data,
1016 - config.headers,
1017 - config.transformRequest
1018 - );
1019 -
1020 - // Flatten headers
1021 - config.headers = utils.merge(
1022 - config.headers.common || {},
1023 - config.headers[config.method] || {},
1024 - config.headers
1025 - );
1026 -
1027 - utils.forEach(
1028 - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
1029 - function cleanHeaderConfig(method) {
1030 - delete config.headers[method];
1031 - }
1032 - );
1033 -
1034 - var adapter = config.adapter || defaults.adapter;
1035 -
1036 - return adapter(config).then(function onAdapterResolution(response) {
1037 - throwIfCancellationRequested(config);
1038 -
1039 - // Transform response data
1040 - response.data = transformData.call(
1041 - config,
1042 - response.data,
1043 - response.headers,
1044 - config.transformResponse
1045 - );
1046 -
1047 - return response;
1048 - }, function onAdapterRejection(reason) {
1049 - if (!isCancel(reason)) {
1050 - throwIfCancellationRequested(config);
1051 -
1052 - // Transform response data
1053 - if (reason && reason.response) {
1054 - reason.response.data = transformData.call(
1055 - config,
1056 - reason.response.data,
1057 - reason.response.headers,
1058 - config.transformResponse
1059 - );
1060 - }
1061 - }
1062 -
1063 - return Promise.reject(reason);
1064 - });
1065 -};
1066 -
1067 -
1068 -/***/ }),
1069 -
1070 -/***/ "./lib/core/mergeConfig.js":
1071 -/*!*********************************!*\
1072 - !*** ./lib/core/mergeConfig.js ***!
1073 - \*********************************/
1074 -/*! no static exports found */
1075 -/***/ (function(module, exports, __webpack_require__) {
1076 -
1077 -"use strict";
1078 -
1079 -
1080 -var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
1081 -
1082 -/**
1083 - * Config-specific merge-function which creates a new config-object
1084 - * by merging two configuration objects together.
1085 - *
1086 - * @param {Object} config1
1087 - * @param {Object} config2
1088 - * @returns {Object} New object resulting from merging config2 to config1
1089 - */
1090 -module.exports = function mergeConfig(config1, config2) {
1091 - // eslint-disable-next-line no-param-reassign
1092 - config2 = config2 || {};
1093 - var config = {};
1094 -
1095 - function getMergedValue(target, source) {
1096 - if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
1097 - return utils.merge(target, source);
1098 - } else if (utils.isPlainObject(source)) {
1099 - return utils.merge({}, source);
1100 - } else if (utils.isArray(source)) {
1101 - return source.slice();
1102 - }
1103 - return source;
1104 - }
1105 -
1106 - // eslint-disable-next-line consistent-return
1107 - function mergeDeepProperties(prop) {
1108 - if (!utils.isUndefined(config2[prop])) {
1109 - return getMergedValue(config1[prop], config2[prop]);
1110 - } else if (!utils.isUndefined(config1[prop])) {
1111 - return getMergedValue(undefined, config1[prop]);
1112 - }
1113 - }
1114 -
1115 - // eslint-disable-next-line consistent-return
1116 - function valueFromConfig2(prop) {
1117 - if (!utils.isUndefined(config2[prop])) {
1118 - return getMergedValue(undefined, config2[prop]);
1119 - }
1120 - }
1121 -
1122 - // eslint-disable-next-line consistent-return
1123 - function defaultToConfig2(prop) {
1124 - if (!utils.isUndefined(config2[prop])) {
1125 - return getMergedValue(undefined, config2[prop]);
1126 - } else if (!utils.isUndefined(config1[prop])) {
1127 - return getMergedValue(undefined, config1[prop]);
1128 - }
1129 - }
1130 -
1131 - // eslint-disable-next-line consistent-return
1132 - function mergeDirectKeys(prop) {
1133 - if (prop in config2) {
1134 - return getMergedValue(config1[prop], config2[prop]);
1135 - } else if (prop in config1) {
1136 - return getMergedValue(undefined, config1[prop]);
1137 - }
1138 - }
1139 -
1140 - var mergeMap = {
1141 - 'url': valueFromConfig2,
1142 - 'method': valueFromConfig2,
1143 - 'data': valueFromConfig2,
1144 - 'baseURL': defaultToConfig2,
1145 - 'transformRequest': defaultToConfig2,
1146 - 'transformResponse': defaultToConfig2,
1147 - 'paramsSerializer': defaultToConfig2,
1148 - 'timeout': defaultToConfig2,
1149 - 'timeoutMessage': defaultToConfig2,
1150 - 'withCredentials': defaultToConfig2,
1151 - 'adapter': defaultToConfig2,
1152 - 'responseType': defaultToConfig2,
1153 - 'xsrfCookieName': defaultToConfig2,
1154 - 'xsrfHeaderName': defaultToConfig2,
1155 - 'onUploadProgress': defaultToConfig2,
1156 - 'onDownloadProgress': defaultToConfig2,
1157 - 'decompress': defaultToConfig2,
1158 - 'maxContentLength': defaultToConfig2,
1159 - 'maxBodyLength': defaultToConfig2,
1160 - 'beforeRedirect': defaultToConfig2,
1161 - 'transport': defaultToConfig2,
1162 - 'httpAgent': defaultToConfig2,
1163 - 'httpsAgent': defaultToConfig2,
1164 - 'cancelToken': defaultToConfig2,
1165 - 'socketPath': defaultToConfig2,
1166 - 'responseEncoding': defaultToConfig2,
1167 - 'validateStatus': mergeDirectKeys
1168 - };
1169 -
1170 - utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
1171 - var merge = mergeMap[prop] || mergeDeepProperties;
1172 - var configValue = merge(prop);
1173 - (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
1174 - });
1175 -
1176 - return config;
1177 -};
1178 -
1179 -
1180 -/***/ }),
1181 -
1182 -/***/ "./lib/core/settle.js":
1183 -/*!****************************!*\
1184 - !*** ./lib/core/settle.js ***!
1185 - \****************************/
1186 -/*! no static exports found */
1187 -/***/ (function(module, exports, __webpack_require__) {
1188 -
1189 -"use strict";
1190 -
1191 -
1192 -var AxiosError = __webpack_require__(/*! ./AxiosError */ "./lib/core/AxiosError.js");
1193 -
1194 -/**
1195 - * Resolve or reject a Promise based on response status.
1196 - *
1197 - * @param {Function} resolve A function that resolves the promise.
1198 - * @param {Function} reject A function that rejects the promise.
1199 - * @param {object} response The response.
1200 - */
1201 -module.exports = function settle(resolve, reject, response) {
1202 - var validateStatus = response.config.validateStatus;
1203 - if (!response.status || !validateStatus || validateStatus(response.status)) {
1204 - resolve(response);
1205 - } else {
1206 - reject(new AxiosError(
1207 - 'Request failed with status code ' + response.status,
1208 - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
1209 - response.config,
1210 - response.request,
1211 - response
1212 - ));
1213 - }
1214 -};
1215 -
1216 -
1217 -/***/ }),
1218 -
1219 -/***/ "./lib/core/transformData.js":
1220 -/*!***********************************!*\
1221 - !*** ./lib/core/transformData.js ***!
1222 - \***********************************/
1223 -/*! no static exports found */
1224 -/***/ (function(module, exports, __webpack_require__) {
1225 -
1226 -"use strict";
1227 -
1228 -
1229 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
1230 -var defaults = __webpack_require__(/*! ../defaults */ "./lib/defaults/index.js");
1231 -
1232 -/**
1233 - * Transform the data for a request or a response
1234 - *
1235 - * @param {Object|String} data The data to be transformed
1236 - * @param {Array} headers The headers for the request or response
1237 - * @param {Array|Function} fns A single function or Array of functions
1238 - * @returns {*} The resulting transformed data
1239 - */
1240 -module.exports = function transformData(data, headers, fns) {
1241 - var context = this || defaults;
1242 - /*eslint no-param-reassign:0*/
1243 - utils.forEach(fns, function transform(fn) {
1244 - data = fn.call(context, data, headers);
1245 - });
1246 -
1247 - return data;
1248 -};
1249 -
1250 -
1251 -/***/ }),
1252 -
1253 -/***/ "./lib/defaults/index.js":
1254 -/*!*******************************!*\
1255 - !*** ./lib/defaults/index.js ***!
1256 - \*******************************/
1257 -/*! no static exports found */
1258 -/***/ (function(module, exports, __webpack_require__) {
1259 -
1260 -"use strict";
1261 -
1262 -
1263 -var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
1264 -var normalizeHeaderName = __webpack_require__(/*! ../helpers/normalizeHeaderName */ "./lib/helpers/normalizeHeaderName.js");
1265 -var AxiosError = __webpack_require__(/*! ../core/AxiosError */ "./lib/core/AxiosError.js");
1266 -var transitionalDefaults = __webpack_require__(/*! ./transitional */ "./lib/defaults/transitional.js");
1267 -var toFormData = __webpack_require__(/*! ../helpers/toFormData */ "./lib/helpers/toFormData.js");
1268 -
1269 -var DEFAULT_CONTENT_TYPE = {
1270 - 'Content-Type': 'application/x-www-form-urlencoded'
1271 -};
1272 -
1273 -function setContentTypeIfUnset(headers, value) {
1274 - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
1275 - headers['Content-Type'] = value;
1276 - }
1277 -}
1278 -
1279 -function getDefaultAdapter() {
1280 - var adapter;
1281 - if (typeof XMLHttpRequest !== 'undefined') {
1282 - // For browsers use XHR adapter
1283 - adapter = __webpack_require__(/*! ../adapters/xhr */ "./lib/adapters/xhr.js");
1284 - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
1285 - // For node use HTTP adapter
1286 - adapter = __webpack_require__(/*! ../adapters/http */ "./lib/adapters/xhr.js");
1287 - }
1288 - return adapter;
1289 -}
1290 -
1291 -function stringifySafely(rawValue, parser, encoder) {
1292 - if (utils.isString(rawValue)) {
1293 - try {
1294 - (parser || JSON.parse)(rawValue);
1295 - return utils.trim(rawValue);
1296 - } catch (e) {
1297 - if (e.name !== 'SyntaxError') {
1298 - throw e;
1299 - }
1300 - }
1301 - }
1302 -
1303 - return (encoder || JSON.stringify)(rawValue);
1304 -}
1305 -
1306 -var defaults = {
1307 -
1308 - transitional: transitionalDefaults,
1309 -
1310 - adapter: getDefaultAdapter(),
1311 -
1312 - transformRequest: [function transformRequest(data, headers) {
1313 - normalizeHeaderName(headers, 'Accept');
1314 - normalizeHeaderName(headers, 'Content-Type');
1315 -
1316 - if (utils.isFormData(data) ||
1317 - utils.isArrayBuffer(data) ||
1318 - utils.isBuffer(data) ||
1319 - utils.isStream(data) ||
1320 - utils.isFile(data) ||
1321 - utils.isBlob(data)
1322 - ) {
1323 - return data;
1324 - }
1325 - if (utils.isArrayBufferView(data)) {
1326 - return data.buffer;
1327 - }
1328 - if (utils.isURLSearchParams(data)) {
1329 - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
1330 - return data.toString();
1331 - }
1332 -
1333 - var isObjectPayload = utils.isObject(data);
1334 - var contentType = headers && headers['Content-Type'];
1335 -
1336 - var isFileList;
1337 -
1338 - if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {
1339 - var _FormData = this.env && this.env.FormData;
1340 - return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData());
1341 - } else if (isObjectPayload || contentType === 'application/json') {
1342 - setContentTypeIfUnset(headers, 'application/json');
1343 - return stringifySafely(data);
1344 - }
1345 -
1346 - return data;
1347 - }],
1348 -
1349 - transformResponse: [function transformResponse(data) {
1350 - var transitional = this.transitional || defaults.transitional;
1351 - var silentJSONParsing = transitional && transitional.silentJSONParsing;
1352 - var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1353 - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
1354 -
1355 - if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
1356 - try {
1357 - return JSON.parse(data);
1358 - } catch (e) {
1359 - if (strictJSONParsing) {
1360 - if (e.name === 'SyntaxError') {
1361 - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
1362 - }
1363 - throw e;
1364 - }
1365 - }
1366 - }
1367 -
1368 - return data;
1369 - }],
1370 -
1371 - /**
1372 - * A timeout in milliseconds to abort a request. If set to 0 (default) a
1373 - * timeout is not created.
1374 - */
1375 - timeout: 0,
1376 -
1377 - xsrfCookieName: 'XSRF-TOKEN',
1378 - xsrfHeaderName: 'X-XSRF-TOKEN',
1379 -
1380 - maxContentLength: -1,
1381 - maxBodyLength: -1,
1382 -
1383 - env: {
1384 - FormData: __webpack_require__(/*! ./env/FormData */ "./lib/helpers/null.js")
1385 - },
1386 -
1387 - validateStatus: function validateStatus(status) {
1388 - return status >= 200 && status < 300;
1389 - },
1390 -
1391 - headers: {
1392 - common: {
1393 - 'Accept': 'application/json, text/plain, */*'
1394 - }
1395 - }
1396 -};
1397 -
1398 -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
1399 - defaults.headers[method] = {};
1400 -});
1401 -
1402 -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
1403 - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
1404 -});
1405 -
1406 -module.exports = defaults;
1407 -
1408 -
1409 -/***/ }),
1410 -
1411 -/***/ "./lib/defaults/transitional.js":
1412 -/*!**************************************!*\
1413 - !*** ./lib/defaults/transitional.js ***!
1414 - \**************************************/
1415 -/*! no static exports found */
1416 -/***/ (function(module, exports, __webpack_require__) {
1417 -
1418 -"use strict";
1419 -
1420 -
1421 -module.exports = {
1422 - silentJSONParsing: true,
1423 - forcedJSONParsing: true,
1424 - clarifyTimeoutError: false
1425 -};
1426 -
1427 -
1428 -/***/ }),
1429 -
1430 -/***/ "./lib/env/data.js":
1431 -/*!*************************!*\
1432 - !*** ./lib/env/data.js ***!
1433 - \*************************/
1434 -/*! no static exports found */
1435 -/***/ (function(module, exports) {
1436 -
1437 -module.exports = {
1438 - "version": "0.27.2"
1439 -};
1440 -
1441 -/***/ }),
1442 -
1443 -/***/ "./lib/helpers/bind.js":
1444 -/*!*****************************!*\
1445 - !*** ./lib/helpers/bind.js ***!
1446 - \*****************************/
1447 -/*! no static exports found */
1448 -/***/ (function(module, exports, __webpack_require__) {
1449 -
1450 -"use strict";
1451 -
1452 -
1453 -module.exports = function bind(fn, thisArg) {
1454 - return function wrap() {
1455 - var args = new Array(arguments.length);
1456 - for (var i = 0; i < args.length; i++) {
1457 - args[i] = arguments[i];
1458 - }
1459 - return fn.apply(thisArg, args);
1460 - };
1461 -};
1462 -
1463 -
1464 -/***/ }),
1465 -
1466 -/***/ "./lib/helpers/buildURL.js":
1467 -/*!*********************************!*\
1468 - !*** ./lib/helpers/buildURL.js ***!
1469 - \*********************************/
1470 -/*! no static exports found */
1471 -/***/ (function(module, exports, __webpack_require__) {
1472 -
1473 -"use strict";
1474 -
1475 -
1476 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
1477 -
1478 -function encode(val) {
1479 - return encodeURIComponent(val).
1480 - replace(/%3A/gi, ':').
1481 - replace(/%24/g, '$').
1482 - replace(/%2C/gi, ',').
1483 - replace(/%20/g, '+').
1484 - replace(/%5B/gi, '[').
1485 - replace(/%5D/gi, ']');
1486 -}
1487 -
1488 -/**
1489 - * Build a URL by appending params to the end
1490 - *
1491 - * @param {string} url The base of the url (e.g., http://www.google.com)
1492 - * @param {object} [params] The params to be appended
1493 - * @returns {string} The formatted url
1494 - */
1495 -module.exports = function buildURL(url, params, paramsSerializer) {
1496 - /*eslint no-param-reassign:0*/
1497 - if (!params) {
1498 - return url;
1499 - }
1500 -
1501 - var serializedParams;
1502 - if (paramsSerializer) {
1503 - serializedParams = paramsSerializer(params);
1504 - } else if (utils.isURLSearchParams(params)) {
1505 - serializedParams = params.toString();
1506 - } else {
1507 - var parts = [];
1508 -
1509 - utils.forEach(params, function serialize(val, key) {
1510 - if (val === null || typeof val === 'undefined') {
1511 - return;
1512 - }
1513 -
1514 - if (utils.isArray(val)) {
1515 - key = key + '[]';
1516 - } else {
1517 - val = [val];
1518 - }
1519 -
1520 - utils.forEach(val, function parseValue(v) {
1521 - if (utils.isDate(v)) {
1522 - v = v.toISOString();
1523 - } else if (utils.isObject(v)) {
1524 - v = JSON.stringify(v);
1525 - }
1526 - parts.push(encode(key) + '=' + encode(v));
1527 - });
1528 - });
1529 -
1530 - serializedParams = parts.join('&');
1531 - }
1532 -
1533 - if (serializedParams) {
1534 - var hashmarkIndex = url.indexOf('#');
1535 - if (hashmarkIndex !== -1) {
1536 - url = url.slice(0, hashmarkIndex);
1537 - }
1538 -
1539 - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1540 - }
1541 -
1542 - return url;
1543 -};
1544 -
1545 -
1546 -/***/ }),
1547 -
1548 -/***/ "./lib/helpers/combineURLs.js":
1549 -/*!************************************!*\
1550 - !*** ./lib/helpers/combineURLs.js ***!
1551 - \************************************/
1552 -/*! no static exports found */
1553 -/***/ (function(module, exports, __webpack_require__) {
1554 -
1555 -"use strict";
1556 -
1557 -
1558 -/**
1559 - * Creates a new URL by combining the specified URLs
1560 - *
1561 - * @param {string} baseURL The base URL
1562 - * @param {string} relativeURL The relative URL
1563 - * @returns {string} The combined URL
1564 - */
1565 -module.exports = function combineURLs(baseURL, relativeURL) {
1566 - return relativeURL
1567 - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
1568 - : baseURL;
1569 -};
1570 -
1571 -
1572 -/***/ }),
1573 -
1574 -/***/ "./lib/helpers/cookies.js":
1575 -/*!********************************!*\
1576 - !*** ./lib/helpers/cookies.js ***!
1577 - \********************************/
1578 -/*! no static exports found */
1579 -/***/ (function(module, exports, __webpack_require__) {
1580 -
1581 -"use strict";
1582 -
1583 -
1584 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
1585 -
1586 -module.exports = (
1587 - utils.isStandardBrowserEnv() ?
1588 -
1589 - // Standard browser envs support document.cookie
1590 - (function standardBrowserEnv() {
1591 - return {
1592 - write: function write(name, value, expires, path, domain, secure) {
1593 - var cookie = [];
1594 - cookie.push(name + '=' + encodeURIComponent(value));
1595 -
1596 - if (utils.isNumber(expires)) {
1597 - cookie.push('expires=' + new Date(expires).toGMTString());
1598 - }
1599 -
1600 - if (utils.isString(path)) {
1601 - cookie.push('path=' + path);
1602 - }
1603 -
1604 - if (utils.isString(domain)) {
1605 - cookie.push('domain=' + domain);
1606 - }
1607 -
1608 - if (secure === true) {
1609 - cookie.push('secure');
1610 - }
1611 -
1612 - document.cookie = cookie.join('; ');
1613 - },
1614 -
1615 - read: function read(name) {
1616 - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
1617 - return (match ? decodeURIComponent(match[3]) : null);
1618 - },
1619 -
1620 - remove: function remove(name) {
1621 - this.write(name, '', Date.now() - 86400000);
1622 - }
1623 - };
1624 - })() :
1625 -
1626 - // Non standard browser env (web workers, react-native) lack needed support.
1627 - (function nonStandardBrowserEnv() {
1628 - return {
1629 - write: function write() {},
1630 - read: function read() { return null; },
1631 - remove: function remove() {}
1632 - };
1633 - })()
1634 -);
1635 -
1636 -
1637 -/***/ }),
1638 -
1639 -/***/ "./lib/helpers/isAbsoluteURL.js":
1640 -/*!**************************************!*\
1641 - !*** ./lib/helpers/isAbsoluteURL.js ***!
1642 - \**************************************/
1643 -/*! no static exports found */
1644 -/***/ (function(module, exports, __webpack_require__) {
1645 -
1646 -"use strict";
1647 -
1648 -
1649 -/**
1650 - * Determines whether the specified URL is absolute
1651 - *
1652 - * @param {string} url The URL to test
1653 - * @returns {boolean} True if the specified URL is absolute, otherwise false
1654 - */
1655 -module.exports = function isAbsoluteURL(url) {
1656 - // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
1657 - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
1658 - // by any combination of letters, digits, plus, period, or hyphen.
1659 - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
1660 -};
1661 -
1662 -
1663 -/***/ }),
1664 -
1665 -/***/ "./lib/helpers/isAxiosError.js":
1666 -/*!*************************************!*\
1667 - !*** ./lib/helpers/isAxiosError.js ***!
1668 - \*************************************/
1669 -/*! no static exports found */
1670 -/***/ (function(module, exports, __webpack_require__) {
1671 -
1672 -"use strict";
1673 -
1674 -
1675 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
1676 -
1677 -/**
1678 - * Determines whether the payload is an error thrown by Axios
1679 - *
1680 - * @param {*} payload The value to test
1681 - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
1682 - */
1683 -module.exports = function isAxiosError(payload) {
1684 - return utils.isObject(payload) && (payload.isAxiosError === true);
1685 -};
1686 -
1687 -
1688 -/***/ }),
1689 -
1690 -/***/ "./lib/helpers/isURLSameOrigin.js":
1691 -/*!****************************************!*\
1692 - !*** ./lib/helpers/isURLSameOrigin.js ***!
1693 - \****************************************/
1694 -/*! no static exports found */
1695 -/***/ (function(module, exports, __webpack_require__) {
1696 -
1697 -"use strict";
1698 -
1699 -
1700 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
1701 -
1702 -module.exports = (
1703 - utils.isStandardBrowserEnv() ?
1704 -
1705 - // Standard browser envs have full support of the APIs needed to test
1706 - // whether the request URL is of the same origin as current location.
1707 - (function standardBrowserEnv() {
1708 - var msie = /(msie|trident)/i.test(navigator.userAgent);
1709 - var urlParsingNode = document.createElement('a');
1710 - var originURL;
1711 -
1712 - /**
1713 - * Parse a URL to discover it's components
1714 - *
1715 - * @param {String} url The URL to be parsed
1716 - * @returns {Object}
1717 - */
1718 - function resolveURL(url) {
1719 - var href = url;
1720 -
1721 - if (msie) {
1722 - // IE needs attribute set twice to normalize properties
1723 - urlParsingNode.setAttribute('href', href);
1724 - href = urlParsingNode.href;
1725 - }
1726 -
1727 - urlParsingNode.setAttribute('href', href);
1728 -
1729 - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
1730 - return {
1731 - href: urlParsingNode.href,
1732 - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
1733 - host: urlParsingNode.host,
1734 - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
1735 - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
1736 - hostname: urlParsingNode.hostname,
1737 - port: urlParsingNode.port,
1738 - pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
1739 - urlParsingNode.pathname :
1740 - '/' + urlParsingNode.pathname
1741 - };
1742 - }
1743 -
1744 - originURL = resolveURL(window.location.href);
1745 -
1746 - /**
1747 - * Determine if a URL shares the same origin as the current location
1748 - *
1749 - * @param {String} requestURL The URL to test
1750 - * @returns {boolean} True if URL shares the same origin, otherwise false
1751 - */
1752 - return function isURLSameOrigin(requestURL) {
1753 - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
1754 - return (parsed.protocol === originURL.protocol &&
1755 - parsed.host === originURL.host);
1756 - };
1757 - })() :
1758 -
1759 - // Non standard browser envs (web workers, react-native) lack needed support.
1760 - (function nonStandardBrowserEnv() {
1761 - return function isURLSameOrigin() {
1762 - return true;
1763 - };
1764 - })()
1765 -);
1766 -
1767 -
1768 -/***/ }),
1769 -
1770 -/***/ "./lib/helpers/normalizeHeaderName.js":
1771 -/*!********************************************!*\
1772 - !*** ./lib/helpers/normalizeHeaderName.js ***!
1773 - \********************************************/
1774 -/*! no static exports found */
1775 -/***/ (function(module, exports, __webpack_require__) {
1776 -
1777 -"use strict";
1778 -
1779 -
1780 -var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
1781 -
1782 -module.exports = function normalizeHeaderName(headers, normalizedName) {
1783 - utils.forEach(headers, function processHeader(value, name) {
1784 - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
1785 - headers[normalizedName] = value;
1786 - delete headers[name];
1787 - }
1788 - });
1789 -};
1790 -
1791 -
1792 -/***/ }),
1793 -
1794 -/***/ "./lib/helpers/null.js":
1795 -/*!*****************************!*\
1796 - !*** ./lib/helpers/null.js ***!
1797 - \*****************************/
1798 -/*! no static exports found */
1799 -/***/ (function(module, exports) {
1800 -
1801 -// eslint-disable-next-line strict
1802 -module.exports = null;
1803 -
1804 -
1805 -/***/ }),
1806 -
1807 -/***/ "./lib/helpers/parseHeaders.js":
1808 -/*!*************************************!*\
1809 - !*** ./lib/helpers/parseHeaders.js ***!
1810 - \*************************************/
1811 -/*! no static exports found */
1812 -/***/ (function(module, exports, __webpack_require__) {
1813 -
1814 -"use strict";
1815 -
1816 -
1817 -var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
1818 -
1819 -// Headers whose duplicates are ignored by node
1820 -// c.f. https://nodejs.org/api/http.html#http_message_headers
1821 -var ignoreDuplicateOf = [
1822 - 'age', 'authorization', 'content-length', 'content-type', 'etag',
1823 - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1824 - 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1825 - 'referer', 'retry-after', 'user-agent'
1826 -];
1827 -
1828 -/**
1829 - * Parse headers into an object
1830 - *
1831 - * ```
1832 - * Date: Wed, 27 Aug 2014 08:58:49 GMT
1833 - * Content-Type: application/json
1834 - * Connection: keep-alive
1835 - * Transfer-Encoding: chunked
1836 - * ```
1837 - *
1838 - * @param {String} headers Headers needing to be parsed
1839 - * @returns {Object} Headers parsed into an object
1840 - */
1841 -module.exports = function parseHeaders(headers) {
1842 - var parsed = {};
1843 - var key;
1844 - var val;
1845 - var i;
1846 -
1847 - if (!headers) { return parsed; }
1848 -
1849 - utils.forEach(headers.split('\n'), function parser(line) {
1850 - i = line.indexOf(':');
1851 - key = utils.trim(line.substr(0, i)).toLowerCase();
1852 - val = utils.trim(line.substr(i + 1));
1853 -
1854 - if (key) {
1855 - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
1856 - return;
1857 - }
1858 - if (key === 'set-cookie') {
1859 - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
1860 - } else {
1861 - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1862 - }
1863 - }
1864 - });
1865 -
1866 - return parsed;
1867 -};
1868 -
1869 -
1870 -/***/ }),
1871 -
1872 -/***/ "./lib/helpers/parseProtocol.js":
1873 -/*!**************************************!*\
1874 - !*** ./lib/helpers/parseProtocol.js ***!
1875 - \**************************************/
1876 -/*! no static exports found */
1877 -/***/ (function(module, exports, __webpack_require__) {
1878 -
1879 -"use strict";
1880 -
1881 -
1882 -module.exports = function parseProtocol(url) {
1883 - var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
1884 - return match && match[1] || '';
1885 -};
1886 -
1887 -
1888 -/***/ }),
1889 -
1890 -/***/ "./lib/helpers/spread.js":
1891 -/*!*******************************!*\
1892 - !*** ./lib/helpers/spread.js ***!
1893 - \*******************************/
1894 -/*! no static exports found */
1895 -/***/ (function(module, exports, __webpack_require__) {
1896 -
1897 -"use strict";
1898 -
1899 -
1900 -/**
1901 - * Syntactic sugar for invoking a function and expanding an array for arguments.
1902 - *
1903 - * Common use case would be to use `Function.prototype.apply`.
1904 - *
1905 - * ```js
1906 - * function f(x, y, z) {}
1907 - * var args = [1, 2, 3];
1908 - * f.apply(null, args);
1909 - * ```
1910 - *
1911 - * With `spread` this example can be re-written.
1912 - *
1913 - * ```js
1914 - * spread(function(x, y, z) {})([1, 2, 3]);
1915 - * ```
1916 - *
1917 - * @param {Function} callback
1918 - * @returns {Function}
1919 - */
1920 -module.exports = function spread(callback) {
1921 - return function wrap(arr) {
1922 - return callback.apply(null, arr);
1923 - };
1924 -};
1925 -
1926 -
1927 -/***/ }),
1928 -
1929 -/***/ "./lib/helpers/toFormData.js":
1930 -/*!***********************************!*\
1931 - !*** ./lib/helpers/toFormData.js ***!
1932 - \***********************************/
1933 -/*! no static exports found */
1934 -/***/ (function(module, exports, __webpack_require__) {
1935 -
1936 -"use strict";
1937 -
1938 -
1939 -var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
1940 -
1941 -/**
1942 - * Convert a data object to FormData
1943 - * @param {Object} obj
1944 - * @param {?Object} [formData]
1945 - * @returns {Object}
1946 - **/
1947 -
1948 -function toFormData(obj, formData) {
1949 - // eslint-disable-next-line no-param-reassign
1950 - formData = formData || new FormData();
1951 -
1952 - var stack = [];
1953 -
1954 - function convertValue(value) {
1955 - if (value === null) return '';
1956 -
1957 - if (utils.isDate(value)) {
1958 - return value.toISOString();
1959 - }
1960 -
1961 - if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
1962 - return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1963 - }
1964 -
1965 - return value;
1966 - }
1967 -
1968 - function build(data, parentKey) {
1969 - if (utils.isPlainObject(data) || utils.isArray(data)) {
1970 - if (stack.indexOf(data) !== -1) {
1971 - throw Error('Circular reference detected in ' + parentKey);
1972 - }
1973 -
1974 - stack.push(data);
1975 -
1976 - utils.forEach(data, function each(value, key) {
1977 - if (utils.isUndefined(value)) return;
1978 - var fullKey = parentKey ? parentKey + '.' + key : key;
1979 - var arr;
1980 -
1981 - if (value && !parentKey && typeof value === 'object') {
1982 - if (utils.endsWith(key, '{}')) {
1983 - // eslint-disable-next-line no-param-reassign
1984 - value = JSON.stringify(value);
1985 - } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {
1986 - // eslint-disable-next-line func-names
1987 - arr.forEach(function(el) {
1988 - !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));
1989 - });
1990 - return;
1991 - }
1992 - }
1993 -
1994 - build(value, fullKey);
1995 - });
1996 -
1997 - stack.pop();
1998 - } else {
1999 - formData.append(parentKey, convertValue(data));
2000 - }
2001 - }
2002 -
2003 - build(obj);
2004 -
2005 - return formData;
2006 -}
2007 -
2008 -module.exports = toFormData;
2009 -
2010 -
2011 -/***/ }),
2012 -
2013 -/***/ "./lib/helpers/validator.js":
2014 -/*!**********************************!*\
2015 - !*** ./lib/helpers/validator.js ***!
2016 - \**********************************/
2017 -/*! no static exports found */
2018 -/***/ (function(module, exports, __webpack_require__) {
2019 -
2020 -"use strict";
2021 -
2022 -
2023 -var VERSION = __webpack_require__(/*! ../env/data */ "./lib/env/data.js").version;
2024 -var AxiosError = __webpack_require__(/*! ../core/AxiosError */ "./lib/core/AxiosError.js");
2025 -
2026 -var validators = {};
2027 -
2028 -// eslint-disable-next-line func-names
2029 -['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
2030 - validators[type] = function validator(thing) {
2031 - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
2032 - };
2033 -});
2034 -
2035 -var deprecatedWarnings = {};
2036 -
2037 -/**
2038 - * Transitional option validator
2039 - * @param {function|boolean?} validator - set to false if the transitional option has been removed
2040 - * @param {string?} version - deprecated version / removed since version
2041 - * @param {string?} message - some message with additional info
2042 - * @returns {function}
2043 - */
2044 -validators.transitional = function transitional(validator, version, message) {
2045 - function formatMessage(opt, desc) {
2046 - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
2047 - }
2048 -
2049 - // eslint-disable-next-line func-names
2050 - return function(value, opt, opts) {
2051 - if (validator === false) {
2052 - throw new AxiosError(
2053 - formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
2054 - AxiosError.ERR_DEPRECATED
2055 - );
2056 - }
2057 -
2058 - if (version && !deprecatedWarnings[opt]) {
2059 - deprecatedWarnings[opt] = true;
2060 - // eslint-disable-next-line no-console
2061 - console.warn(
2062 - formatMessage(
2063 - opt,
2064 - ' has been deprecated since v' + version + ' and will be removed in the near future'
2065 - )
2066 - );
2067 - }
2068 -
2069 - return validator ? validator(value, opt, opts) : true;
2070 - };
2071 -};
2072 -
2073 -/**
2074 - * Assert object's properties type
2075 - * @param {object} options
2076 - * @param {object} schema
2077 - * @param {boolean?} allowUnknown
2078 - */
2079 -
2080 -function assertOptions(options, schema, allowUnknown) {
2081 - if (typeof options !== 'object') {
2082 - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
2083 - }
2084 - var keys = Object.keys(options);
2085 - var i = keys.length;
2086 - while (i-- > 0) {
2087 - var opt = keys[i];
2088 - var validator = schema[opt];
2089 - if (validator) {
2090 - var value = options[opt];
2091 - var result = value === undefined || validator(value, opt, options);
2092 - if (result !== true) {
2093 - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
2094 - }
2095 - continue;
2096 - }
2097 - if (allowUnknown !== true) {
2098 - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
2099 - }
2100 - }
2101 -}
2102 -
2103 -module.exports = {
2104 - assertOptions: assertOptions,
2105 - validators: validators
2106 -};
2107 -
2108 -
2109 -/***/ }),
2110 -
2111 -/***/ "./lib/utils.js":
2112 -/*!**********************!*\
2113 - !*** ./lib/utils.js ***!
2114 - \**********************/
2115 -/*! no static exports found */
2116 -/***/ (function(module, exports, __webpack_require__) {
2117 -
2118 -"use strict";
2119 -
2120 -
2121 -var bind = __webpack_require__(/*! ./helpers/bind */ "./lib/helpers/bind.js");
2122 -
2123 -// utils is a library of generic helper functions non-specific to axios
2124 -
2125 -var toString = Object.prototype.toString;
2126 -
2127 -// eslint-disable-next-line func-names
2128 -var kindOf = (function(cache) {
2129 - // eslint-disable-next-line func-names
2130 - return function(thing) {
2131 - var str = toString.call(thing);
2132 - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
2133 - };
2134 -})(Object.create(null));
2135 -
2136 -function kindOfTest(type) {
2137 - type = type.toLowerCase();
2138 - return function isKindOf(thing) {
2139 - return kindOf(thing) === type;
2140 - };
2141 -}
2142 -
2143 -/**
2144 - * Determine if a value is an Array
2145 - *
2146 - * @param {Object} val The value to test
2147 - * @returns {boolean} True if value is an Array, otherwise false
2148 - */
2149 -function isArray(val) {
2150 - return Array.isArray(val);
2151 -}
2152 -
2153 -/**
2154 - * Determine if a value is undefined
2155 - *
2156 - * @param {Object} val The value to test
2157 - * @returns {boolean} True if the value is undefined, otherwise false
2158 - */
2159 -function isUndefined(val) {
2160 - return typeof val === 'undefined';
2161 -}
2162 -
2163 -/**
2164 - * Determine if a value is a Buffer
2165 - *
2166 - * @param {Object} val The value to test
2167 - * @returns {boolean} True if value is a Buffer, otherwise false
2168 - */
2169 -function isBuffer(val) {
2170 - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
2171 - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
2172 -}
2173 -
2174 -/**
2175 - * Determine if a value is an ArrayBuffer
2176 - *
2177 - * @function
2178 - * @param {Object} val The value to test
2179 - * @returns {boolean} True if value is an ArrayBuffer, otherwise false
2180 - */
2181 -var isArrayBuffer = kindOfTest('ArrayBuffer');
2182 -
2183 -
2184 -/**
2185 - * Determine if a value is a view on an ArrayBuffer
2186 - *
2187 - * @param {Object} val The value to test
2188 - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
2189 - */
2190 -function isArrayBufferView(val) {
2191 - var result;
2192 - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
2193 - result = ArrayBuffer.isView(val);
2194 - } else {
2195 - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
2196 - }
2197 - return result;
2198 -}
2199 -
2200 -/**
2201 - * Determine if a value is a String
2202 - *
2203 - * @param {Object} val The value to test
2204 - * @returns {boolean} True if value is a String, otherwise false
2205 - */
2206 -function isString(val) {
2207 - return typeof val === 'string';
2208 -}
2209 -
2210 -/**
2211 - * Determine if a value is a Number
2212 - *
2213 - * @param {Object} val The value to test
2214 - * @returns {boolean} True if value is a Number, otherwise false
2215 - */
2216 -function isNumber(val) {
2217 - return typeof val === 'number';
2218 -}
2219 -
2220 -/**
2221 - * Determine if a value is an Object
2222 - *
2223 - * @param {Object} val The value to test
2224 - * @returns {boolean} True if value is an Object, otherwise false
2225 - */
2226 -function isObject(val) {
2227 - return val !== null && typeof val === 'object';
2228 -}
2229 -
2230 -/**
2231 - * Determine if a value is a plain Object
2232 - *
2233 - * @param {Object} val The value to test
2234 - * @return {boolean} True if value is a plain Object, otherwise false
2235 - */
2236 -function isPlainObject(val) {
2237 - if (kindOf(val) !== 'object') {
2238 - return false;
2239 - }
2240 -
2241 - var prototype = Object.getPrototypeOf(val);
2242 - return prototype === null || prototype === Object.prototype;
2243 -}
2244 -
2245 -/**
2246 - * Determine if a value is a Date
2247 - *
2248 - * @function
2249 - * @param {Object} val The value to test
2250 - * @returns {boolean} True if value is a Date, otherwise false
2251 - */
2252 -var isDate = kindOfTest('Date');
2253 -
2254 -/**
2255 - * Determine if a value is a File
2256 - *
2257 - * @function
2258 - * @param {Object} val The value to test
2259 - * @returns {boolean} True if value is a File, otherwise false
2260 - */
2261 -var isFile = kindOfTest('File');
2262 -
2263 -/**
2264 - * Determine if a value is a Blob
2265 - *
2266 - * @function
2267 - * @param {Object} val The value to test
2268 - * @returns {boolean} True if value is a Blob, otherwise false
2269 - */
2270 -var isBlob = kindOfTest('Blob');
2271 -
2272 -/**
2273 - * Determine if a value is a FileList
2274 - *
2275 - * @function
2276 - * @param {Object} val The value to test
2277 - * @returns {boolean} True if value is a File, otherwise false
2278 - */
2279 -var isFileList = kindOfTest('FileList');
2280 -
2281 -/**
2282 - * Determine if a value is a Function
2283 - *
2284 - * @param {Object} val The value to test
2285 - * @returns {boolean} True if value is a Function, otherwise false
2286 - */
2287 -function isFunction(val) {
2288 - return toString.call(val) === '[object Function]';
2289 -}
2290 -
2291 -/**
2292 - * Determine if a value is a Stream
2293 - *
2294 - * @param {Object} val The value to test
2295 - * @returns {boolean} True if value is a Stream, otherwise false
2296 - */
2297 -function isStream(val) {
2298 - return isObject(val) && isFunction(val.pipe);
2299 -}
2300 -
2301 -/**
2302 - * Determine if a value is a FormData
2303 - *
2304 - * @param {Object} thing The value to test
2305 - * @returns {boolean} True if value is an FormData, otherwise false
2306 - */
2307 -function isFormData(thing) {
2308 - var pattern = '[object FormData]';
2309 - return thing && (
2310 - (typeof FormData === 'function' && thing instanceof FormData) ||
2311 - toString.call(thing) === pattern ||
2312 - (isFunction(thing.toString) && thing.toString() === pattern)
2313 - );
2314 -}
2315 -
2316 -/**
2317 - * Determine if a value is a URLSearchParams object
2318 - * @function
2319 - * @param {Object} val The value to test
2320 - * @returns {boolean} True if value is a URLSearchParams object, otherwise false
2321 - */
2322 -var isURLSearchParams = kindOfTest('URLSearchParams');
2323 -
2324 -/**
2325 - * Trim excess whitespace off the beginning and end of a string
2326 - *
2327 - * @param {String} str The String to trim
2328 - * @returns {String} The String freed of excess whitespace
2329 - */
2330 -function trim(str) {
2331 - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
2332 -}
2333 -
2334 -/**
2335 - * Determine if we're running in a standard browser environment
2336 - *
2337 - * This allows axios to run in a web worker, and react-native.
2338 - * Both environments support XMLHttpRequest, but not fully standard globals.
2339 - *
2340 - * web workers:
2341 - * typeof window -> undefined
2342 - * typeof document -> undefined
2343 - *
2344 - * react-native:
2345 - * navigator.product -> 'ReactNative'
2346 - * nativescript
2347 - * navigator.product -> 'NativeScript' or 'NS'
2348 - */
2349 -function isStandardBrowserEnv() {
2350 - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
2351 - navigator.product === 'NativeScript' ||
2352 - navigator.product === 'NS')) {
2353 - return false;
2354 - }
2355 - return (
2356 - typeof window !== 'undefined' &&
2357 - typeof document !== 'undefined'
2358 - );
2359 -}
2360 -
2361 -/**
2362 - * Iterate over an Array or an Object invoking a function for each item.
2363 - *
2364 - * If `obj` is an Array callback will be called passing
2365 - * the value, index, and complete array for each item.
2366 - *
2367 - * If 'obj' is an Object callback will be called passing
2368 - * the value, key, and complete object for each property.
2369 - *
2370 - * @param {Object|Array} obj The object to iterate
2371 - * @param {Function} fn The callback to invoke for each item
2372 - */
2373 -function forEach(obj, fn) {
2374 - // Don't bother if no value provided
2375 - if (obj === null || typeof obj === 'undefined') {
2376 - return;
2377 - }
2378 -
2379 - // Force an array if not already something iterable
2380 - if (typeof obj !== 'object') {
2381 - /*eslint no-param-reassign:0*/
2382 - obj = [obj];
2383 - }
2384 -
2385 - if (isArray(obj)) {
2386 - // Iterate over array values
2387 - for (var i = 0, l = obj.length; i < l; i++) {
2388 - fn.call(null, obj[i], i, obj);
2389 - }
2390 - } else {
2391 - // Iterate over object keys
2392 - for (var key in obj) {
2393 - if (Object.prototype.hasOwnProperty.call(obj, key)) {
2394 - fn.call(null, obj[key], key, obj);
2395 - }
2396 - }
2397 - }
2398 -}
2399 -
2400 -/**
2401 - * Accepts varargs expecting each argument to be an object, then
2402 - * immutably merges the properties of each object and returns result.
2403 - *
2404 - * When multiple objects contain the same key the later object in
2405 - * the arguments list will take precedence.
2406 - *
2407 - * Example:
2408 - *
2409 - * ```js
2410 - * var result = merge({foo: 123}, {foo: 456});
2411 - * console.log(result.foo); // outputs 456
2412 - * ```
2413 - *
2414 - * @param {Object} obj1 Object to merge
2415 - * @returns {Object} Result of all merge properties
2416 - */
2417 -function merge(/* obj1, obj2, obj3, ... */) {
2418 - var result = {};
2419 - function assignValue(val, key) {
2420 - if (isPlainObject(result[key]) && isPlainObject(val)) {
2421 - result[key] = merge(result[key], val);
2422 - } else if (isPlainObject(val)) {
2423 - result[key] = merge({}, val);
2424 - } else if (isArray(val)) {
2425 - result[key] = val.slice();
2426 - } else {
2427 - result[key] = val;
2428 - }
2429 - }
2430 -
2431 - for (var i = 0, l = arguments.length; i < l; i++) {
2432 - forEach(arguments[i], assignValue);
2433 - }
2434 - return result;
2435 -}
2436 -
2437 -/**
2438 - * Extends object a by mutably adding to it the properties of object b.
2439 - *
2440 - * @param {Object} a The object to be extended
2441 - * @param {Object} b The object to copy properties from
2442 - * @param {Object} thisArg The object to bind function to
2443 - * @return {Object} The resulting value of object a
2444 - */
2445 -function extend(a, b, thisArg) {
2446 - forEach(b, function assignValue(val, key) {
2447 - if (thisArg && typeof val === 'function') {
2448 - a[key] = bind(val, thisArg);
2449 - } else {
2450 - a[key] = val;
2451 - }
2452 - });
2453 - return a;
2454 -}
2455 -
2456 -/**
2457 - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
2458 - *
2459 - * @param {string} content with BOM
2460 - * @return {string} content value without BOM
2461 - */
2462 -function stripBOM(content) {
2463 - if (content.charCodeAt(0) === 0xFEFF) {
2464 - content = content.slice(1);
2465 - }
2466 - return content;
2467 -}
2468 -
2469 -/**
2470 - * Inherit the prototype methods from one constructor into another
2471 - * @param {function} constructor
2472 - * @param {function} superConstructor
2473 - * @param {object} [props]
2474 - * @param {object} [descriptors]
2475 - */
2476 -
2477 -function inherits(constructor, superConstructor, props, descriptors) {
2478 - constructor.prototype = Object.create(superConstructor.prototype, descriptors);
2479 - constructor.prototype.constructor = constructor;
2480 - props && Object.assign(constructor.prototype, props);
2481 -}
2482 -
2483 -/**
2484 - * Resolve object with deep prototype chain to a flat object
2485 - * @param {Object} sourceObj source object
2486 - * @param {Object} [destObj]
2487 - * @param {Function} [filter]
2488 - * @returns {Object}
2489 - */
2490 -
2491 -function toFlatObject(sourceObj, destObj, filter) {
2492 - var props;
2493 - var i;
2494 - var prop;
2495 - var merged = {};
2496 -
2497 - destObj = destObj || {};
2498 -
2499 - do {
2500 - props = Object.getOwnPropertyNames(sourceObj);
2501 - i = props.length;
2502 - while (i-- > 0) {
2503 - prop = props[i];
2504 - if (!merged[prop]) {
2505 - destObj[prop] = sourceObj[prop];
2506 - merged[prop] = true;
2507 - }
2508 - }
2509 - sourceObj = Object.getPrototypeOf(sourceObj);
2510 - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
2511 -
2512 - return destObj;
2513 -}
2514 -
2515 -/*
2516 - * determines whether a string ends with the characters of a specified string
2517 - * @param {String} str
2518 - * @param {String} searchString
2519 - * @param {Number} [position= 0]
2520 - * @returns {boolean}
2521 - */
2522 -function endsWith(str, searchString, position) {
2523 - str = String(str);
2524 - if (position === undefined || position > str.length) {
2525 - position = str.length;
2526 - }
2527 - position -= searchString.length;
2528 - var lastIndex = str.indexOf(searchString, position);
2529 - return lastIndex !== -1 && lastIndex === position;
2530 -}
2531 -
2532 -
2533 -/**
2534 - * Returns new array from array like object
2535 - * @param {*} [thing]
2536 - * @returns {Array}
2537 - */
2538 -function toArray(thing) {
2539 - if (!thing) return null;
2540 - var i = thing.length;
2541 - if (isUndefined(i)) return null;
2542 - var arr = new Array(i);
2543 - while (i-- > 0) {
2544 - arr[i] = thing[i];
2545 - }
2546 - return arr;
2547 -}
2548 -
2549 -// eslint-disable-next-line func-names
2550 -var isTypedArray = (function(TypedArray) {
2551 - // eslint-disable-next-line func-names
2552 - return function(thing) {
2553 - return TypedArray && thing instanceof TypedArray;
2554 - };
2555 -})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
2556 -
2557 -module.exports = {
2558 - isArray: isArray,
2559 - isArrayBuffer: isArrayBuffer,
2560 - isBuffer: isBuffer,
2561 - isFormData: isFormData,
2562 - isArrayBufferView: isArrayBufferView,
2563 - isString: isString,
2564 - isNumber: isNumber,
2565 - isObject: isObject,
2566 - isPlainObject: isPlainObject,
2567 - isUndefined: isUndefined,
2568 - isDate: isDate,
2569 - isFile: isFile,
2570 - isBlob: isBlob,
2571 - isFunction: isFunction,
2572 - isStream: isStream,
2573 - isURLSearchParams: isURLSearchParams,
2574 - isStandardBrowserEnv: isStandardBrowserEnv,
2575 - forEach: forEach,
2576 - merge: merge,
2577 - extend: extend,
2578 - trim: trim,
2579 - stripBOM: stripBOM,
2580 - inherits: inherits,
2581 - toFlatObject: toFlatObject,
2582 - kindOf: kindOf,
2583 - kindOfTest: kindOfTest,
2584 - endsWith: endsWith,
2585 - toArray: toArray,
2586 - isTypedArray: isTypedArray,
2587 - isFileList: isFileList
2588 -};
2589 -
2590 -
2591 -/***/ })
2592 -
2593 -/******/ });
2594 -});
2595 -//# sourceMappingURL=axios.map
...\ No newline at end of file ...\ No newline at end of file
1 -{"version":3,"sources":["webpack://axios/webpack/universalModuleDefinition","webpack://axios/webpack/bootstrap","webpack://axios/./index.js","webpack://axios/./lib/adapters/xhr.js","webpack://axios/./lib/axios.js","webpack://axios/./lib/cancel/CancelToken.js","webpack://axios/./lib/cancel/CanceledError.js","webpack://axios/./lib/cancel/isCancel.js","webpack://axios/./lib/core/Axios.js","webpack://axios/./lib/core/AxiosError.js","webpack://axios/./lib/core/InterceptorManager.js","webpack://axios/./lib/core/buildFullPath.js","webpack://axios/./lib/core/dispatchRequest.js","webpack://axios/./lib/core/mergeConfig.js","webpack://axios/./lib/core/settle.js","webpack://axios/./lib/core/transformData.js","webpack://axios/./lib/defaults/index.js","webpack://axios/./lib/defaults/transitional.js","webpack://axios/./lib/env/data.js","webpack://axios/./lib/helpers/bind.js","webpack://axios/./lib/helpers/buildURL.js","webpack://axios/./lib/helpers/combineURLs.js","webpack://axios/./lib/helpers/cookies.js","webpack://axios/./lib/helpers/isAbsoluteURL.js","webpack://axios/./lib/helpers/isAxiosError.js","webpack://axios/./lib/helpers/isURLSameOrigin.js","webpack://axios/./lib/helpers/normalizeHeaderName.js","webpack://axios/./lib/helpers/null.js","webpack://axios/./lib/helpers/parseHeaders.js","webpack://axios/./lib/helpers/parseProtocol.js","webpack://axios/./lib/helpers/spread.js","webpack://axios/./lib/helpers/toFormData.js","webpack://axios/./lib/helpers/validator.js","webpack://axios/./lib/utils.js"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBAAmB,EAAE;QACrI;QACA;;QAEA;QACA;QACA;QACA,2BAA2B,0BAA0B,EAAE;QACvD,iCAAiC,eAAe;QAChD;QACA;QACA;;QAEA;QACA,sDAAsD,+DAA+D;;QAErH;QACA;;;QAGA;QACA;;;;;;;;;;;;AClFA,iBAAiB,mBAAO,CAAC,mCAAa,E;;;;;;;;;;;;ACAzB;;AAEb,YAAY,mBAAO,CAAC,kCAAY;AAChC,aAAa,mBAAO,CAAC,8CAAkB;AACvC,cAAc,mBAAO,CAAC,sDAAsB;AAC5C,eAAe,mBAAO,CAAC,wDAAuB;AAC9C,oBAAoB,mBAAO,CAAC,0DAAuB;AACnD,mBAAmB,mBAAO,CAAC,gEAA2B;AACtD,sBAAsB,mBAAO,CAAC,sEAA8B;AAC5D,2BAA2B,mBAAO,CAAC,gEAA0B;AAC7D,iBAAiB,mBAAO,CAAC,oDAAoB;AAC7C,oBAAoB,mBAAO,CAAC,8DAAyB;AACrD,oBAAoB,mBAAO,CAAC,gEAA0B;;AAEtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,4CAA4C;AAC5C;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,OAAO;;AAEP;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA,GAAG;AACH;;;;;;;;;;;;;AC7Na;;AAEb,YAAY,mBAAO,CAAC,+BAAS;AAC7B,WAAW,mBAAO,CAAC,6CAAgB;AACnC,YAAY,mBAAO,CAAC,yCAAc;AAClC,kBAAkB,mBAAO,CAAC,qDAAoB;AAC9C,eAAe,mBAAO,CAAC,2CAAY;;AAEnC;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,MAAM;AAClB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,sBAAsB,mBAAO,CAAC,6DAAwB;AACtD,oBAAoB,mBAAO,CAAC,yDAAsB;AAClD,iBAAiB,mBAAO,CAAC,mDAAmB;AAC5C,gBAAgB,mBAAO,CAAC,qCAAY;AACpC,mBAAmB,mBAAO,CAAC,yDAAsB;;AAEjD;AACA,mBAAmB,mBAAO,CAAC,wDAAwB;;AAEnD;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,mBAAO,CAAC,iDAAkB;;AAEzC;AACA,qBAAqB,mBAAO,CAAC,6DAAwB;;AAErD;;AAEA;AACA;;;;;;;;;;;;;AC/Da;;AAEb,oBAAoB,mBAAO,CAAC,sDAAiB;;AAE7C;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,GAAG;;AAEH;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA,eAAe,OAAO;AACtB;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;;;;;;;;;;;;;ACtHa;;AAEb,iBAAiB,mBAAO,CAAC,oDAAoB;AAC7C,YAAY,mBAAO,CAAC,gCAAU;;AAE9B;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,CAAC;;AAED;;;;;;;;;;;;;ACrBa;;AAEb;AACA;AACA;;;;;;;;;;;;;ACJa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;AAChC,eAAe,mBAAO,CAAC,sDAAqB;AAC5C,yBAAyB,mBAAO,CAAC,8DAAsB;AACvD,sBAAsB,mBAAO,CAAC,wDAAmB;AACjD,kBAAkB,mBAAO,CAAC,gDAAe;AACzC,oBAAoB,mBAAO,CAAC,oDAAiB;AAC7C,gBAAgB,mBAAO,CAAC,wDAAsB;;AAE9C;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,GAAG;;AAEH;AACA;AACA;AACA,GAAG;;AAEH;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gDAAgD;AAChD;AACA;AACA,yBAAyB;AACzB,KAAK;AACL;AACA,CAAC;;AAED;AACA;;AAEA;AACA;AACA,kDAAkD;AAClD;AACA;AACA;AACA,SAAS,KAAK;AACd;AACA;AACA,OAAO;AACP;AACA;;AAEA;;AAEA;AACA,CAAC;;AAED;;;;;;;;;;;;;AC/Ja;;AAEb,YAAY,mBAAO,CAAC,gCAAU;;AAE9B;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,MAAM;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB,CAAC;;AAED;AACA,kDAAkD,YAAY;;AAE9D;AACA;AACA;;AAEA;AACA;AACA,GAAG;;AAEH;;AAEA;;AAEA;;AAEA;AACA;;AAEA;;;;;;;;;;;;;ACrFa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB;AACA,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;;;;;;;;;;;;;ACrDa;;AAEb,oBAAoB,mBAAO,CAAC,gEAA0B;AACtD,kBAAkB,mBAAO,CAAC,4DAAwB;;AAElD;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACnBa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;AAChC,oBAAoB,mBAAO,CAAC,oDAAiB;AAC7C,eAAe,mBAAO,CAAC,oDAAoB;AAC3C,eAAe,mBAAO,CAAC,4CAAa;AACpC,oBAAoB,mBAAO,CAAC,8DAAyB;;AAErD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,+BAA+B;AAC/B,uCAAuC;AACvC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;AACH;;;;;;;;;;;;;ACtFa;;AAEb,YAAY,mBAAO,CAAC,gCAAU;;AAE9B;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL,2BAA2B;AAC3B,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;;;;;;;;;;;;;ACnGa;;AAEb,iBAAiB,mBAAO,CAAC,8CAAc;;AAEvC;AACA;AACA;AACA,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACxBa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;AAChC,eAAe,mBAAO,CAAC,4CAAa;;AAEpC;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,MAAM;AACjB,WAAW,eAAe;AAC1B,aAAa,EAAE;AACf;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;;;;;;;;;;;;;ACrBa;;AAEb,YAAY,mBAAO,CAAC,gCAAU;AAC9B,0BAA0B,mBAAO,CAAC,4EAAgC;AAClE,iBAAiB,mBAAO,CAAC,oDAAoB;AAC7C,2BAA2B,mBAAO,CAAC,sDAAgB;AACnD,iBAAiB,mBAAO,CAAC,0DAAuB;;AAEhD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc,mBAAO,CAAC,8CAAiB;AACvC,GAAG;AACH;AACA,cAAc,mBAAO,CAAC,+CAAkB;AACxC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wEAAwE;AACxE;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA,sCAAsC,gBAAgB;AACtD,KAAK;AACL;AACA;AACA;;AAEA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,cAAc,mBAAO,CAAC,6CAAgB;AACtC,GAAG;;AAEH;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,CAAC;;AAED;AACA;AACA,CAAC;;AAED;;;;;;;;;;;;;ACjJa;;AAEb;AACA;AACA;AACA;AACA;;;;;;;;;;;;ACNA;AACA;AACA,E;;;;;;;;;;;;ACFa;;AAEb;AACA;AACA;AACA,mBAAmB,iBAAiB;AACpC;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACVa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,OAAO;AACP,KAAK;;AAEL;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;ACrEa;;AAEb;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACba;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,0CAA0C;AAC1C,SAAS;;AAET;AACA,4DAA4D,wBAAwB;AACpF;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA,kCAAkC;AAClC,+BAA+B,aAAa,EAAE;AAC9C;AACA;AACA,KAAK;AACL;;;;;;;;;;;;;ACpDa;;AAEb;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACba;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;AACA;AACA,WAAW,EAAE;AACb,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;;;;;;;;;;;;ACZa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc,OAAO;AACrB,gBAAgB;AAChB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,cAAc,OAAO;AACrB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;;;;;;;;;;;;ACnEa;;AAEb,YAAY,mBAAO,CAAC,gCAAU;;AAE9B;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;;;;;;;;;;;ACXA;AACA;;;;;;;;;;;;;ACDa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA,iBAAiB,eAAe;;AAEhC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,GAAG;;AAEH;AACA;;;;;;;;;;;;;ACpDa;;AAEb;AACA,wBAAwB,KAAK;AAC7B;AACA;;;;;;;;;;;;;ACLa;;AAEb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B;AAC/B;AACA;AACA,WAAW,SAAS;AACpB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;AC1Ba;;AAEb,YAAY,mBAAO,CAAC,gCAAU;;AAE9B;AACA;AACA,WAAW,OAAO;AAClB,WAAW,QAAQ;AACnB,aAAa;AACb;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,qCAAqC;AACrC;AACA;AACA,WAAW;AACX;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;;AAEA;AACA,OAAO;;AAEP;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;;;;;;;;;;;;;ACvEa;;AAEb,cAAc,mBAAO,CAAC,sCAAa;AACnC,iBAAiB,mBAAO,CAAC,oDAAoB;;AAE7C;;AAEA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;;AAEA;AACA;AACA,WAAW,kBAAkB;AAC7B,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa;AACb;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,SAAS;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;;;;;;;ACrFa;;AAEb,WAAW,mBAAO,CAAC,6CAAgB;;AAEnC;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;;;AAGA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,aAAa;AACxB,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mCAAmC,OAAO;AAC1C;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,SAAS,GAAG,SAAS;AAC5C,2BAA2B;AAC3B;AACA;AACA,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,4BAA4B;AAC5B,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;;AAEA,uCAAuC,OAAO;AAC9C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,SAAS;AACpB,aAAa;AACb;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,EAAE;AACb,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"axios.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"axios\"] = factory();\n\telse\n\t\troot[\"axios\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = \"./index.js\");\n","module.exports = require('./lib/axios');","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar transitionalDefaults = require('../defaults/transitional');\nvar AxiosError = require('../core/AxiosError');\nvar CanceledError = require('../cancel/CanceledError');\nvar parseProtocol = require('../helpers/parseProtocol');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n var onCanceled;\n function done() {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', onCanceled);\n }\n }\n\n if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';\n var transitional = config.transitional || transitionalDefaults;\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken || config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = function(cancel) {\n if (!request) {\n return;\n }\n reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);\n request.abort();\n request = null;\n };\n\n config.cancelToken && config.cancelToken.subscribe(onCanceled);\n if (config.signal) {\n config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n var protocol = parseProtocol(fullPath);\n\n if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = require('./cancel/CanceledError');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\naxios.VERSION = require('./env/data').version;\naxios.toFormData = require('./helpers/toFormData');\n\n// Expose AxiosError class\naxios.AxiosError = require('../lib/core/AxiosError');\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","'use strict';\n\nvar CanceledError = require('./CanceledError');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(function(cancel) {\n if (!token._listeners) return;\n\n var i;\n var l = token._listeners.length;\n\n for (i = 0; i < l; i++) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = function(onfulfilled) {\n var _resolve;\n // eslint-disable-next-line func-names\n var promise = new Promise(function(resolve) {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Subscribe to the cancel signal\n */\n\nCancelToken.prototype.subscribe = function subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n};\n\n/**\n * Unsubscribe from the cancel signal\n */\n\nCancelToken.prototype.unsubscribe = function unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n var index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\nvar AxiosError = require('../core/AxiosError');\nvar utils = require('../utils');\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction CanceledError(message) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nmodule.exports = CanceledError;\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar buildFullPath = require('./buildFullPath');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n var fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url: url,\n data: data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nmodule.exports = Axios;\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n response && (this.response = response);\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n }\n});\n\nvar prototype = AxiosError.prototype;\nvar descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED'\n// eslint-disable-next-line func-names\n].forEach(function(code) {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = function(error, code, config, request, response, customProps) {\n var axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nmodule.exports = AxiosError;\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\nvar CanceledError = require('../cancel/CanceledError');\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(prop) {\n if (prop in config2) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n var mergeMap = {\n 'url': valueFromConfig2,\n 'method': valueFromConfig2,\n 'data': valueFromConfig2,\n 'baseURL': defaultToConfig2,\n 'transformRequest': defaultToConfig2,\n 'transformResponse': defaultToConfig2,\n 'paramsSerializer': defaultToConfig2,\n 'timeout': defaultToConfig2,\n 'timeoutMessage': defaultToConfig2,\n 'withCredentials': defaultToConfig2,\n 'adapter': defaultToConfig2,\n 'responseType': defaultToConfig2,\n 'xsrfCookieName': defaultToConfig2,\n 'xsrfHeaderName': defaultToConfig2,\n 'onUploadProgress': defaultToConfig2,\n 'onDownloadProgress': defaultToConfig2,\n 'decompress': defaultToConfig2,\n 'maxContentLength': defaultToConfig2,\n 'maxBodyLength': defaultToConfig2,\n 'beforeRedirect': defaultToConfig2,\n 'transport': defaultToConfig2,\n 'httpAgent': defaultToConfig2,\n 'httpsAgent': defaultToConfig2,\n 'cancelToken': defaultToConfig2,\n 'socketPath': defaultToConfig2,\n 'responseEncoding': defaultToConfig2,\n 'validateStatus': mergeDirectKeys\n };\n\n utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {\n var merge = mergeMap[prop] || mergeDeepProperties;\n var configValue = merge(prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n};\n","'use strict';\n\nvar AxiosError = require('./AxiosError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar normalizeHeaderName = require('../helpers/normalizeHeaderName');\nvar AxiosError = require('../core/AxiosError');\nvar transitionalDefaults = require('./transitional');\nvar toFormData = require('../helpers/toFormData');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('../adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('../adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n\n var isObjectPayload = utils.isObject(data);\n var contentType = headers && headers['Content-Type'];\n\n var isFileList;\n\n if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {\n var _FormData = this.env && this.env.FormData;\n return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData());\n } else if (isObjectPayload || contentType === 'application/json') {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional || defaults.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: require('./env/FormData')\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nmodule.exports = {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","module.exports = {\n \"version\": \"0.27.2\"\n};","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"<scheme>://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","// eslint-disable-next-line strict\nmodule.exports = null;\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nmodule.exports = function parseProtocol(url) {\n var match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n};\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Convert a data object to FormData\n * @param {Object} obj\n * @param {?Object} [formData]\n * @returns {Object}\n **/\n\nfunction toFormData(obj, formData) {\n // eslint-disable-next-line no-param-reassign\n formData = formData || new FormData();\n\n var stack = [];\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n function build(data, parentKey) {\n if (utils.isPlainObject(data) || utils.isArray(data)) {\n if (stack.indexOf(data) !== -1) {\n throw Error('Circular reference detected in ' + parentKey);\n }\n\n stack.push(data);\n\n utils.forEach(data, function each(value, key) {\n if (utils.isUndefined(value)) return;\n var fullKey = parentKey ? parentKey + '.' + key : key;\n var arr;\n\n if (value && !parentKey && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {\n // eslint-disable-next-line func-names\n arr.forEach(function(el) {\n !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));\n });\n return;\n }\n }\n\n build(value, fullKey);\n });\n\n stack.pop();\n } else {\n formData.append(parentKey, convertValue(data));\n }\n }\n\n build(obj);\n\n return formData;\n}\n\nmodule.exports = toFormData;\n","'use strict';\n\nvar VERSION = require('../env/data').version;\nvar AxiosError = require('../core/AxiosError');\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nmodule.exports = {\n assertOptions: assertOptions,\n validators: validators\n};\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n// eslint-disable-next-line func-names\nvar kindOf = (function(cache) {\n // eslint-disable-next-line func-names\n return function(thing) {\n var str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n };\n})(Object.create(null));\n\nfunction kindOfTest(type) {\n type = type.toLowerCase();\n return function isKindOf(thing) {\n return kindOf(thing) === type;\n };\n}\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return Array.isArray(val);\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nvar isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nvar isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nvar isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nvar isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nvar isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} thing The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(thing) {\n var pattern = '[object FormData]';\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) ||\n toString.call(thing) === pattern ||\n (isFunction(thing.toString) && thing.toString() === pattern)\n );\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nvar isURLSearchParams = kindOfTest('URLSearchParams');\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n */\n\nfunction inherits(constructor, superConstructor, props, descriptors) {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function} [filter]\n * @returns {Object}\n */\n\nfunction toFlatObject(sourceObj, destObj, filter) {\n var props;\n var i;\n var prop;\n var merged = {};\n\n destObj = destObj || {};\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if (!merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = Object.getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/*\n * determines whether a string ends with the characters of a specified string\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n * @returns {boolean}\n */\nfunction endsWith(str, searchString, position) {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n var lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object\n * @param {*} [thing]\n * @returns {Array}\n */\nfunction toArray(thing) {\n if (!thing) return null;\n var i = thing.length;\n if (isUndefined(i)) return null;\n var arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n// eslint-disable-next-line func-names\nvar isTypedArray = (function(TypedArray) {\n // eslint-disable-next-line func-names\n return function(thing) {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM,\n inherits: inherits,\n toFlatObject: toFlatObject,\n kindOf: kindOf,\n kindOfTest: kindOfTest,\n endsWith: endsWith,\n toArray: toArray,\n isTypedArray: isTypedArray,\n isFileList: isFileList\n};\n"],"sourceRoot":""}
...\ No newline at end of file ...\ No newline at end of file
1 -/* axios v0.27.2 | (c) 2022 by Matt Zabriskie */
2 -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=13)}([function(e,t,n){"use strict";var r,o=n(4),i=Object.prototype.toString,s=(r=Object.create(null),function(e){var t=i.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())});function a(e){return e=e.toLowerCase(),function(t){return s(t)===e}}function u(e){return Array.isArray(e)}function c(e){return void 0===e}var f=a("ArrayBuffer");function l(e){return null!==e&&"object"==typeof e}function p(e){if("object"!==s(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var d=a("Date"),h=a("File"),m=a("Blob"),v=a("FileList");function y(e){return"[object Function]"===i.call(e)}var g=a("URLSearchParams");function E(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),u(e))for(var n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.call(null,e[o],o,e)}var b,O=(b="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return b&&e instanceof b});e.exports={isArray:u,isArrayBuffer:f,isBuffer:function(e){return null!==e&&!c(e)&&null!==e.constructor&&!c(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return e&&("function"==typeof FormData&&e instanceof FormData||"[object FormData]"===i.call(e)||y(e.toString)&&"[object FormData]"===e.toString())},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&f(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:l,isPlainObject:p,isUndefined:c,isDate:d,isFile:h,isBlob:m,isFunction:y,isStream:function(e){return l(e)&&y(e.pipe)},isURLSearchParams:g,isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:E,merge:function e(){var t={};function n(n,r){p(t[r])&&p(n)?t[r]=e(t[r],n):p(n)?t[r]=e({},n):u(n)?t[r]=n.slice():t[r]=n}for(var r=0,o=arguments.length;r<o;r++)E(arguments[r],n);return t},extend:function(e,t,n){return E(t,(function(t,r){e[r]=n&&"function"==typeof t?o(t,n):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,n,r){e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,n&&Object.assign(e.prototype,n)},toFlatObject:function(e,t,n){var r,o,i,s={};t=t||{};do{for(o=(r=Object.getOwnPropertyNames(e)).length;o-- >0;)s[i=r[o]]||(t[i]=e[i],s[i]=!0);e=Object.getPrototypeOf(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:s,kindOfTest:a,endsWith:function(e,t,n){e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;var r=e.indexOf(t,n);return-1!==r&&r===n},toArray:function(e){if(!e)return null;var t=e.length;if(c(t))return null;for(var n=new Array(t);t-- >0;)n[t]=e[t];return n},isTypedArray:O,isFileList:v}},function(e,t,n){"use strict";var r=n(0);function o(e,t,n,r,o){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}r.inherits(o,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var i=o.prototype,s={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){s[e]={value:e}})),Object.defineProperties(o,s),Object.defineProperty(i,"isAxiosError",{value:!0}),o.from=function(e,t,n,s,a,u){var c=Object.create(i);return r.toFlatObject(e,c,(function(e){return e!==Error.prototype})),o.call(c,e.message,t,n,s,a),c.name=e.name,u&&Object.assign(c,u),c},e.exports=o},function(e,t,n){"use strict";var r=n(1);function o(e){r.call(this,null==e?"canceled":e,r.ERR_CANCELED),this.name="CanceledError"}n(0).inherits(o,r,{__CANCEL__:!0}),e.exports=o},function(e,t,n){"use strict";var r=n(0),o=n(19),i=n(1),s=n(6),a=n(7),u={"Content-Type":"application/x-www-form-urlencoded"};function c(e,t){!r.isUndefined(e)&&r.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var f,l={transitional:s,adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(f=n(8)),f),transformRequest:[function(e,t){if(o(t,"Accept"),o(t,"Content-Type"),r.isFormData(e)||r.isArrayBuffer(e)||r.isBuffer(e)||r.isStream(e)||r.isFile(e)||r.isBlob(e))return e;if(r.isArrayBufferView(e))return e.buffer;if(r.isURLSearchParams(e))return c(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var n,i=r.isObject(e),s=t&&t["Content-Type"];if((n=r.isFileList(e))||i&&"multipart/form-data"===s){var u=this.env&&this.env.FormData;return a(n?{"files[]":e}:e,u&&new u)}return i||"application/json"===s?(c(t,"application/json"),function(e,t,n){if(r.isString(e))try{return(t||JSON.parse)(e),r.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||l.transitional,n=t&&t.silentJSONParsing,o=t&&t.forcedJSONParsing,s=!n&&"json"===this.responseType;if(s||o&&r.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(s){if("SyntaxError"===e.name)throw i.from(e,i.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:n(27)},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};r.forEach(["delete","get","head"],(function(e){l.headers[e]={}})),r.forEach(["post","put","patch"],(function(e){l.headers[e]=r.merge(u)})),e.exports=l},function(e,t,n){"use strict";e.exports=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}}},function(e,t,n){"use strict";var r=n(0);function o(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}e.exports=function(e,t,n){if(!t)return e;var i;if(n)i=n(t);else if(r.isURLSearchParams(t))i=t.toString();else{var s=[];r.forEach(t,(function(e,t){null!=e&&(r.isArray(e)?t+="[]":e=[e],r.forEach(e,(function(e){r.isDate(e)?e=e.toISOString():r.isObject(e)&&(e=JSON.stringify(e)),s.push(o(t)+"="+o(e))})))})),i=s.join("&")}if(i){var a=e.indexOf("#");-1!==a&&(e=e.slice(0,a)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}},function(e,t,n){"use strict";e.exports={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e,t){t=t||new FormData;var n=[];function o(e){return null===e?"":r.isDate(e)?e.toISOString():r.isArrayBuffer(e)||r.isTypedArray(e)?"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}return function e(i,s){if(r.isPlainObject(i)||r.isArray(i)){if(-1!==n.indexOf(i))throw Error("Circular reference detected in "+s);n.push(i),r.forEach(i,(function(n,i){if(!r.isUndefined(n)){var a,u=s?s+"."+i:i;if(n&&!s&&"object"==typeof n)if(r.endsWith(i,"{}"))n=JSON.stringify(n);else if(r.endsWith(i,"[]")&&(a=r.toArray(n)))return void a.forEach((function(e){!r.isUndefined(e)&&t.append(u,o(e))}));e(n,u)}})),n.pop()}else t.append(s,o(i))}(e),t}},function(e,t,n){"use strict";var r=n(0),o=n(20),i=n(21),s=n(5),a=n(9),u=n(24),c=n(25),f=n(6),l=n(1),p=n(2),d=n(26);e.exports=function(e){return new Promise((function(t,n){var h,m=e.data,v=e.headers,y=e.responseType;function g(){e.cancelToken&&e.cancelToken.unsubscribe(h),e.signal&&e.signal.removeEventListener("abort",h)}r.isFormData(m)&&r.isStandardBrowserEnv()&&delete v["Content-Type"];var E=new XMLHttpRequest;if(e.auth){var b=e.auth.username||"",O=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";v.Authorization="Basic "+btoa(b+":"+O)}var x=a(e.baseURL,e.url);function w(){if(E){var r="getAllResponseHeaders"in E?u(E.getAllResponseHeaders()):null,i={data:y&&"text"!==y&&"json"!==y?E.response:E.responseText,status:E.status,statusText:E.statusText,headers:r,config:e,request:E};o((function(e){t(e),g()}),(function(e){n(e),g()}),i),E=null}}if(E.open(e.method.toUpperCase(),s(x,e.params,e.paramsSerializer),!0),E.timeout=e.timeout,"onloadend"in E?E.onloadend=w:E.onreadystatechange=function(){E&&4===E.readyState&&(0!==E.status||E.responseURL&&0===E.responseURL.indexOf("file:"))&&setTimeout(w)},E.onabort=function(){E&&(n(new l("Request aborted",l.ECONNABORTED,e,E)),E=null)},E.onerror=function(){n(new l("Network Error",l.ERR_NETWORK,e,E,E)),E=null},E.ontimeout=function(){var t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",r=e.transitional||f;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(new l(t,r.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,e,E)),E=null},r.isStandardBrowserEnv()){var R=(e.withCredentials||c(x))&&e.xsrfCookieName?i.read(e.xsrfCookieName):void 0;R&&(v[e.xsrfHeaderName]=R)}"setRequestHeader"in E&&r.forEach(v,(function(e,t){void 0===m&&"content-type"===t.toLowerCase()?delete v[t]:E.setRequestHeader(t,e)})),r.isUndefined(e.withCredentials)||(E.withCredentials=!!e.withCredentials),y&&"json"!==y&&(E.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&E.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&E.upload&&E.upload.addEventListener("progress",e.onUploadProgress),(e.cancelToken||e.signal)&&(h=function(e){E&&(n(!e||e&&e.type?new p:e),E.abort(),E=null)},e.cancelToken&&e.cancelToken.subscribe(h),e.signal&&(e.signal.aborted?h():e.signal.addEventListener("abort",h))),m||(m=null);var S=d(x);S&&-1===["http","https","file"].indexOf(S)?n(new l("Unsupported protocol "+S+":",l.ERR_BAD_REQUEST,e)):E.send(m)}))}},function(e,t,n){"use strict";var r=n(22),o=n(23);e.exports=function(e,t){return e&&!r(t)?o(e,t):t}},function(e,t,n){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e,t){t=t||{};var n={};function o(e,t){return r.isPlainObject(e)&&r.isPlainObject(t)?r.merge(e,t):r.isPlainObject(t)?r.merge({},t):r.isArray(t)?t.slice():t}function i(n){return r.isUndefined(t[n])?r.isUndefined(e[n])?void 0:o(void 0,e[n]):o(e[n],t[n])}function s(e){if(!r.isUndefined(t[e]))return o(void 0,t[e])}function a(n){return r.isUndefined(t[n])?r.isUndefined(e[n])?void 0:o(void 0,e[n]):o(void 0,t[n])}function u(n){return n in t?o(e[n],t[n]):n in e?o(void 0,e[n]):void 0}var c={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:u};return r.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=c[e]||i,o=t(e);r.isUndefined(o)&&t!==u||(n[e]=o)})),n}},function(e,t){e.exports={version:"0.27.2"}},function(e,t,n){e.exports=n(14)},function(e,t,n){"use strict";var r=n(0),o=n(4),i=n(15),s=n(11);var a=function e(t){var n=new i(t),a=o(i.prototype.request,n);return r.extend(a,i.prototype,n),r.extend(a,n),a.create=function(n){return e(s(t,n))},a}(n(3));a.Axios=i,a.CanceledError=n(2),a.CancelToken=n(29),a.isCancel=n(10),a.VERSION=n(12).version,a.toFormData=n(7),a.AxiosError=n(1),a.Cancel=a.CanceledError,a.all=function(e){return Promise.all(e)},a.spread=n(30),a.isAxiosError=n(31),e.exports=a,e.exports.default=a},function(e,t,n){"use strict";var r=n(0),o=n(5),i=n(16),s=n(17),a=n(11),u=n(9),c=n(28),f=c.validators;function l(e){this.defaults=e,this.interceptors={request:new i,response:new i}}l.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=a(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var n=t.transitional;void 0!==n&&c.assertOptions(n,{silentJSONParsing:f.transitional(f.boolean),forcedJSONParsing:f.transitional(f.boolean),clarifyTimeoutError:f.transitional(f.boolean)},!1);var r=[],o=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,r.unshift(e.fulfilled,e.rejected))}));var i,u=[];if(this.interceptors.response.forEach((function(e){u.push(e.fulfilled,e.rejected)})),!o){var l=[s,void 0];for(Array.prototype.unshift.apply(l,r),l=l.concat(u),i=Promise.resolve(t);l.length;)i=i.then(l.shift(),l.shift());return i}for(var p=t;r.length;){var d=r.shift(),h=r.shift();try{p=d(p)}catch(e){h(e);break}}try{i=s(p)}catch(e){return Promise.reject(e)}for(;u.length;)i=i.then(u.shift(),u.shift());return i},l.prototype.getUri=function(e){e=a(this.defaults,e);var t=u(e.baseURL,e.url);return o(t,e.params,e.paramsSerializer)},r.forEach(["delete","get","head","options"],(function(e){l.prototype[e]=function(t,n){return this.request(a(n||{},{method:e,url:t,data:(n||{}).data}))}})),r.forEach(["post","put","patch"],(function(e){function t(t){return function(n,r,o){return this.request(a(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}l.prototype[e]=t(),l.prototype[e+"Form"]=t(!0)})),e.exports=l},function(e,t,n){"use strict";var r=n(0);function o(){this.handlers=[]}o.prototype.use=function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1},o.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},o.prototype.forEach=function(e){r.forEach(this.handlers,(function(t){null!==t&&e(t)}))},e.exports=o},function(e,t,n){"use strict";var r=n(0),o=n(18),i=n(10),s=n(3),a=n(2);function u(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new a}e.exports=function(e){return u(e),e.headers=e.headers||{},e.data=o.call(e,e.data,e.headers,e.transformRequest),e.headers=r.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),r.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||s.adapter)(e).then((function(t){return u(e),t.data=o.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return i(t)||(u(e),t&&t.response&&(t.response.data=o.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))}},function(e,t,n){"use strict";var r=n(0),o=n(3);e.exports=function(e,t,n){var i=this||o;return r.forEach(n,(function(n){e=n.call(i,e,t)})),e}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e,t){r.forEach(e,(function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])}))}},function(e,t,n){"use strict";var r=n(1);e.exports=function(e,t,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(new r("Request failed with status code "+n.status,[r.ERR_BAD_REQUEST,r.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}},function(e,t,n){"use strict";var r=n(0);e.exports=r.isStandardBrowserEnv()?{write:function(e,t,n,o,i,s){var a=[];a.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),r.isString(o)&&a.push("path="+o),r.isString(i)&&a.push("domain="+i),!0===s&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(e,t,n){"use strict";e.exports=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}},function(e,t,n){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t,n){"use strict";var r=n(0),o=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];e.exports=function(e){var t,n,i,s={};return e?(r.forEach(e.split("\n"),(function(e){if(i=e.indexOf(":"),t=r.trim(e.substr(0,i)).toLowerCase(),n=r.trim(e.substr(i+1)),t){if(s[t]&&o.indexOf(t)>=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([n]):s[t]?s[t]+", "+n:n}})),s):s}},function(e,t,n){"use strict";var r=n(0);e.exports=r.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function o(e){var r=e;return t&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return e=o(window.location.href),function(t){var n=r.isString(t)?o(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0}},function(e,t,n){"use strict";e.exports=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}},function(e,t){e.exports=null},function(e,t,n){"use strict";var r=n(12).version,o=n(1),i={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){i[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));var s={};i.transitional=function(e,t,n){function i(e,t){return"[Axios v"+r+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return function(n,r,a){if(!1===e)throw new o(i(r," has been removed"+(t?" in "+t:"")),o.ERR_DEPRECATED);return t&&!s[r]&&(s[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,a)}},e.exports={assertOptions:function(e,t,n){if("object"!=typeof e)throw new o("options must be an object",o.ERR_BAD_OPTION_VALUE);for(var r=Object.keys(e),i=r.length;i-- >0;){var s=r[i],a=t[s];if(a){var u=e[s],c=void 0===u||a(u,s,e);if(!0!==c)throw new o("option "+s+" must be "+c,o.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new o("Unknown option "+s,o.ERR_BAD_OPTION)}},validators:i}},function(e,t,n){"use strict";var r=n(2);function o(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var n=this;this.promise.then((function(e){if(n._listeners){var t,r=n._listeners.length;for(t=0;t<r;t++)n._listeners[t](e);n._listeners=null}})),this.promise.then=function(e){var t,r=new Promise((function(e){n.subscribe(e),t=e})).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e((function(e){n.reason||(n.reason=new r(e),t(n.reason))}))}o.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},o.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},o.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},o.source=function(){var e;return{token:new o((function(t){e=t})),cancel:e}},e.exports=o},function(e,t,n){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){return r.isObject(e)&&!0===e.isAxiosError}}])}));
3 -//# sourceMappingURL=axios.min.map
...\ No newline at end of file ...\ No newline at end of file
1 -{"version":3,"sources":["webpack://axios/webpack/universalModuleDefinition","webpack://axios/webpack/bootstrap","webpack://axios/./lib/utils.js","webpack://axios/./lib/core/AxiosError.js","webpack://axios/./lib/cancel/CanceledError.js","webpack://axios/./lib/defaults/index.js","webpack://axios/./lib/helpers/bind.js","webpack://axios/./lib/helpers/buildURL.js","webpack://axios/./lib/defaults/transitional.js","webpack://axios/./lib/helpers/toFormData.js","webpack://axios/./lib/adapters/xhr.js","webpack://axios/./lib/core/buildFullPath.js","webpack://axios/./lib/cancel/isCancel.js","webpack://axios/./lib/core/mergeConfig.js","webpack://axios/./lib/env/data.js","webpack://axios/./index.js","webpack://axios/./lib/axios.js","webpack://axios/./lib/core/Axios.js","webpack://axios/./lib/core/InterceptorManager.js","webpack://axios/./lib/core/dispatchRequest.js","webpack://axios/./lib/core/transformData.js","webpack://axios/./lib/helpers/normalizeHeaderName.js","webpack://axios/./lib/core/settle.js","webpack://axios/./lib/helpers/cookies.js","webpack://axios/./lib/helpers/isAbsoluteURL.js","webpack://axios/./lib/helpers/combineURLs.js","webpack://axios/./lib/helpers/parseHeaders.js","webpack://axios/./lib/helpers/isURLSameOrigin.js","webpack://axios/./lib/helpers/parseProtocol.js","webpack://axios/./lib/helpers/null.js","webpack://axios/./lib/helpers/validator.js","webpack://axios/./lib/cancel/CancelToken.js","webpack://axios/./lib/helpers/spread.js","webpack://axios/./lib/helpers/isAxiosError.js"],"names":["root","factory","exports","module","define","amd","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","cache","toString","kindOf","thing","str","slice","toLowerCase","kindOfTest","type","isArray","val","Array","isUndefined","isArrayBuffer","isObject","isPlainObject","getPrototypeOf","isDate","isFile","isBlob","isFileList","isFunction","isURLSearchParams","forEach","obj","fn","length","TypedArray","isTypedArray","Uint8Array","isBuffer","constructor","isFormData","FormData","isArrayBufferView","ArrayBuffer","isView","buffer","isString","isNumber","isStream","pipe","isStandardBrowserEnv","navigator","product","window","document","merge","result","assignValue","arguments","extend","a","b","thisArg","trim","replace","stripBOM","content","charCodeAt","inherits","superConstructor","props","descriptors","assign","toFlatObject","sourceObj","destObj","filter","prop","merged","getOwnPropertyNames","endsWith","searchString","position","String","undefined","lastIndex","indexOf","toArray","arr","utils","AxiosError","message","code","config","request","response","Error","toJSON","description","number","fileName","lineNumber","columnNumber","stack","status","defineProperties","from","error","customProps","axiosError","CanceledError","ERR_CANCELED","__CANCEL__","normalizeHeaderName","transitionalDefaults","toFormData","DEFAULT_CONTENT_TYPE","setContentTypeIfUnset","headers","adapter","defaults","transitional","XMLHttpRequest","process","transformRequest","data","isObjectPayload","contentType","_FormData","env","rawValue","parser","encoder","JSON","parse","e","stringify","stringifySafely","transformResponse","silentJSONParsing","forcedJSONParsing","strictJSONParsing","responseType","ERR_BAD_RESPONSE","timeout","xsrfCookieName","xsrfHeaderName","maxContentLength","maxBodyLength","validateStatus","common","method","args","apply","encode","encodeURIComponent","url","params","paramsSerializer","serializedParams","parts","v","toISOString","push","join","hashmarkIndex","clarifyTimeoutError","formData","convertValue","Blob","Buffer","build","parentKey","fullKey","el","append","pop","settle","cookies","buildURL","buildFullPath","parseHeaders","isURLSameOrigin","parseProtocol","Promise","resolve","reject","onCanceled","requestData","requestHeaders","done","cancelToken","unsubscribe","signal","removeEventListener","auth","username","password","unescape","Authorization","btoa","fullPath","baseURL","onloadend","responseHeaders","getAllResponseHeaders","responseText","statusText","err","open","toUpperCase","onreadystatechange","readyState","responseURL","setTimeout","onabort","ECONNABORTED","onerror","ERR_NETWORK","ontimeout","timeoutErrorMessage","ETIMEDOUT","xsrfValue","withCredentials","read","setRequestHeader","onDownloadProgress","addEventListener","onUploadProgress","upload","cancel","abort","subscribe","aborted","protocol","ERR_BAD_REQUEST","send","isAbsoluteURL","combineURLs","requestedURL","config1","config2","getMergedValue","target","source","mergeDeepProperties","valueFromConfig2","defaultToConfig2","mergeDirectKeys","mergeMap","keys","concat","configValue","Axios","mergeConfig","axios","createInstance","defaultConfig","context","instance","instanceConfig","CancelToken","isCancel","VERSION","version","Cancel","all","promises","spread","isAxiosError","default","InterceptorManager","dispatchRequest","validator","validators","interceptors","configOrUrl","assertOptions","boolean","requestInterceptorChain","synchronousRequestInterceptors","interceptor","runWhen","synchronous","unshift","fulfilled","rejected","promise","responseInterceptorChain","chain","then","shift","newConfig","onFulfilled","onRejected","getUri","generateHTTPMethod","isForm","handlers","use","options","eject","id","h","transformData","throwIfCancellationRequested","throwIfRequested","reason","fns","normalizedName","Math","floor","write","expires","path","domain","secure","cookie","Date","toGMTString","match","RegExp","decodeURIComponent","remove","now","test","relativeURL","ignoreDuplicateOf","parsed","split","line","substr","originURL","msie","userAgent","urlParsingNode","createElement","resolveURL","href","setAttribute","host","search","hash","hostname","port","pathname","charAt","location","requestURL","exec","deprecatedWarnings","formatMessage","opt","desc","opts","ERR_DEPRECATED","console","warn","schema","allowUnknown","ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","executor","TypeError","resolvePromise","token","_listeners","onfulfilled","_resolve","listener","index","splice","callback","payload"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAe,MAAID,IAEnBD,EAAY,MAAIC,IARlB,CASGK,MAAM,WACT,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFAxB,EAAoBgB,EAAEO,GACtBX,OAAOC,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,iBAATF,EAAmB,IAAI,IAAIM,KAAON,EAAOnB,EAAoBQ,EAAEe,EAAIE,EAAK,SAASA,GAAO,OAAON,EAAMM,IAAQC,KAAK,KAAMD,IAC9I,OAAOF,GAIRvB,EAAoB2B,EAAI,SAAShC,GAChC,IAAIe,EAASf,GAAUA,EAAO2B,WAC7B,WAAwB,OAAO3B,EAAgB,SAC/C,WAA8B,OAAOA,GAEtC,OADAK,EAAoBQ,EAAEE,EAAQ,IAAKA,GAC5BA,GAIRV,EAAoBW,EAAI,SAASiB,EAAQC,GAAY,OAAOjB,OAAOkB,UAAUC,eAAe1B,KAAKuB,EAAQC,IAGzG7B,EAAoBgC,EAAI,GAIjBhC,EAAoBA,EAAoBiC,EAAI,I,+BChFrD,IAOuBC,EAPnBR,EAAO,EAAQ,GAIfS,EAAWvB,OAAOkB,UAAUK,SAG5BC,GAAmBF,EAMpBtB,OAAOY,OAAO,MAJR,SAASa,GACd,IAAIC,EAAMH,EAAS9B,KAAKgC,GACxB,OAAOH,EAAMI,KAASJ,EAAMI,GAAOA,EAAIC,MAAM,GAAI,GAAGC,iBAIxD,SAASC,EAAWC,GAElB,OADAA,EAAOA,EAAKF,cACL,SAAkBH,GACvB,OAAOD,EAAOC,KAAWK,GAU7B,SAASC,EAAQC,GACf,OAAOC,MAAMF,QAAQC,GASvB,SAASE,EAAYF,GACnB,YAAsB,IAARA,EAqBhB,IAAIG,EAAgBN,EAAW,eA6C/B,SAASO,EAASJ,GAChB,OAAe,OAARA,GAA+B,iBAARA,EAShC,SAASK,EAAcL,GACrB,GAAoB,WAAhBR,EAAOQ,GACT,OAAO,EAGT,IAAId,EAAYlB,OAAOsC,eAAeN,GACtC,OAAqB,OAAdd,GAAsBA,IAAclB,OAAOkB,UAUpD,IAAIqB,EAASV,EAAW,QASpBW,EAASX,EAAW,QASpBY,EAASZ,EAAW,QASpBa,EAAab,EAAW,YAQ5B,SAASc,EAAWX,GAClB,MAA8B,sBAAvBT,EAAS9B,KAAKuC,GAkCvB,IAAIY,EAAoBf,EAAW,mBAmDnC,SAASgB,EAAQC,EAAKC,GAEpB,GAAID,QAUJ,GALmB,iBAARA,IAETA,EAAM,CAACA,IAGLf,EAAQe,GAEV,IAAK,IAAIxD,EAAI,EAAGC,EAAIuD,EAAIE,OAAQ1D,EAAIC,EAAGD,IACrCyD,EAAGtD,KAAK,KAAMqD,EAAIxD,GAAIA,EAAGwD,QAI3B,IAAK,IAAIjC,KAAOiC,EACV9C,OAAOkB,UAAUC,eAAe1B,KAAKqD,EAAKjC,IAC5CkC,EAAGtD,KAAK,KAAMqD,EAAIjC,GAAMA,EAAKiC,GA4JrC,IAA6BG,EAAzBC,GAAyBD,EAKJ,oBAAfE,YAA8BnD,OAAOsC,eAAea,YAHrD,SAAS1B,GACd,OAAOwB,GAAcxB,aAAiBwB,IAI1ClE,EAAOD,QAAU,CACfiD,QAASA,EACTI,cAAeA,EACfiB,SAvYF,SAAkBpB,GAChB,OAAe,OAARA,IAAiBE,EAAYF,IAA4B,OAApBA,EAAIqB,cAAyBnB,EAAYF,EAAIqB,cAChD,mBAA7BrB,EAAIqB,YAAYD,UAA2BpB,EAAIqB,YAAYD,SAASpB,IAsYhFsB,WA9PF,SAAoB7B,GAElB,OAAOA,IACgB,mBAAb8B,UAA2B9B,aAAiB8B,UAFxC,sBAGZhC,EAAS9B,KAAKgC,IACbkB,EAAWlB,EAAMF,WAJN,sBAImBE,EAAMF,aA0PvCiC,kBApXF,SAA2BxB,GAOzB,MAL4B,oBAAhByB,aAAiCA,YAAkB,OACpDA,YAAYC,OAAO1B,GAEnB,GAAUA,EAAU,QAAMG,EAAcH,EAAI2B,SAgXvDC,SArWF,SAAkB5B,GAChB,MAAsB,iBAARA,GAqWd6B,SA5VF,SAAkB7B,GAChB,MAAsB,iBAARA,GA4VdI,SAAUA,EACVC,cAAeA,EACfH,YAAaA,EACbK,OAAQA,EACRC,OAAQA,EACRC,OAAQA,EACRE,WAAYA,EACZmB,SAnRF,SAAkB9B,GAChB,OAAOI,EAASJ,IAAQW,EAAWX,EAAI+B,OAmRvCnB,kBAAmBA,EACnBoB,qBAjOF,WACE,OAAyB,oBAAdC,WAAoD,gBAAtBA,UAAUC,SACY,iBAAtBD,UAAUC,SACY,OAAtBD,UAAUC,WAI/B,oBAAXC,QACa,oBAAbC,WA0NTvB,QAASA,EACTwB,MA/JF,SAASA,IACP,IAAIC,EAAS,GACb,SAASC,EAAYvC,EAAKnB,GACpBwB,EAAciC,EAAOzD,KAASwB,EAAcL,GAC9CsC,EAAOzD,GAAOwD,EAAMC,EAAOzD,GAAMmB,GACxBK,EAAcL,GACvBsC,EAAOzD,GAAOwD,EAAM,GAAIrC,GACfD,EAAQC,GACjBsC,EAAOzD,GAAOmB,EAAIL,QAElB2C,EAAOzD,GAAOmB,EAIlB,IAAK,IAAI1C,EAAI,EAAGC,EAAIiF,UAAUxB,OAAQ1D,EAAIC,EAAGD,IAC3CuD,EAAQ2B,UAAUlF,GAAIiF,GAExB,OAAOD,GA+IPG,OApIF,SAAgBC,EAAGC,EAAGC,GAQpB,OAPA/B,EAAQ8B,GAAG,SAAqB3C,EAAKnB,GAEjC6D,EAAE7D,GADA+D,GAA0B,mBAAR5C,EACXlB,EAAKkB,EAAK4C,GAEV5C,KAGN0C,GA6HPG,KAxPF,SAAcnD,GACZ,OAAOA,EAAImD,KAAOnD,EAAImD,OAASnD,EAAIoD,QAAQ,aAAc,KAwPzDC,SArHF,SAAkBC,GAIhB,OAH8B,QAA1BA,EAAQC,WAAW,KACrBD,EAAUA,EAAQrD,MAAM,IAEnBqD,GAkHPE,SAvGF,SAAkB7B,EAAa8B,EAAkBC,EAAOC,GACtDhC,EAAYnC,UAAYlB,OAAOY,OAAOuE,EAAiBjE,UAAWmE,GAClEhC,EAAYnC,UAAUmC,YAAcA,EACpC+B,GAASpF,OAAOsF,OAAOjC,EAAYnC,UAAWkE,IAqG9CG,aA1FF,SAAsBC,EAAWC,EAASC,GACxC,IAAIN,EACA9F,EACAqG,EACAC,EAAS,GAEbH,EAAUA,GAAW,GAErB,EAAG,CAGD,IADAnG,GADA8F,EAAQpF,OAAO6F,oBAAoBL,IACzBxC,OACH1D,KAAM,GAENsG,EADLD,EAAOP,EAAM9F,MAEXmG,EAAQE,GAAQH,EAAUG,GAC1BC,EAAOD,IAAQ,GAGnBH,EAAYxF,OAAOsC,eAAekD,SAC3BA,KAAeE,GAAUA,EAAOF,EAAWC,KAAaD,IAAcxF,OAAOkB,WAEtF,OAAOuE,GAsEPjE,OAAQA,EACRK,WAAYA,EACZiE,SA9DF,SAAkBpE,EAAKqE,EAAcC,GACnCtE,EAAMuE,OAAOvE,SACIwE,IAAbF,GAA0BA,EAAWtE,EAAIsB,UAC3CgD,EAAWtE,EAAIsB,QAEjBgD,GAAYD,EAAa/C,OACzB,IAAImD,EAAYzE,EAAI0E,QAAQL,EAAcC,GAC1C,OAAsB,IAAfG,GAAoBA,IAAcH,GAwDzCK,QA/CF,SAAiB5E,GACf,IAAKA,EAAO,OAAO,KACnB,IAAInC,EAAImC,EAAMuB,OACd,GAAId,EAAY5C,GAAI,OAAO,KAE3B,IADA,IAAIgH,EAAM,IAAIrE,MAAM3C,GACbA,KAAM,GACXgH,EAAIhH,GAAKmC,EAAMnC,GAEjB,OAAOgH,GAwCPpD,aAAcA,EACdR,WAAYA,I,6BCldd,IAAI6D,EAAQ,EAAQ,GAYpB,SAASC,EAAWC,EAASC,EAAMC,EAAQC,EAASC,GAClDC,MAAMrH,KAAKP,MACXA,KAAKuH,QAAUA,EACfvH,KAAKW,KAAO,aACZ6G,IAASxH,KAAKwH,KAAOA,GACrBC,IAAWzH,KAAKyH,OAASA,GACzBC,IAAY1H,KAAK0H,QAAUA,GAC3BC,IAAa3H,KAAK2H,SAAWA,GAG/BN,EAAMrB,SAASsB,EAAYM,MAAO,CAChCC,OAAQ,WACN,MAAO,CAELN,QAASvH,KAAKuH,QACd5G,KAAMX,KAAKW,KAEXmH,YAAa9H,KAAK8H,YAClBC,OAAQ/H,KAAK+H,OAEbC,SAAUhI,KAAKgI,SACfC,WAAYjI,KAAKiI,WACjBC,aAAclI,KAAKkI,aACnBC,MAAOnI,KAAKmI,MAEZV,OAAQzH,KAAKyH,OACbD,KAAMxH,KAAKwH,KACXY,OAAQpI,KAAK2H,UAAY3H,KAAK2H,SAASS,OAASpI,KAAK2H,SAASS,OAAS,SAK7E,IAAIpG,EAAYsF,EAAWtF,UACvBmE,EAAc,GAElB,CACE,uBACA,iBACA,eACA,YACA,cACA,4BACA,iBACA,mBACA,kBACA,gBAEAxC,SAAQ,SAAS6D,GACjBrB,EAAYqB,GAAQ,CAACnG,MAAOmG,MAG9B1G,OAAOuH,iBAAiBf,EAAYnB,GACpCrF,OAAOC,eAAeiB,EAAW,eAAgB,CAACX,OAAO,IAGzDiG,EAAWgB,KAAO,SAASC,EAAOf,EAAMC,EAAQC,EAASC,EAAUa,GACjE,IAAIC,EAAa3H,OAAOY,OAAOM,GAY/B,OAVAqF,EAAMhB,aAAakC,EAAOE,GAAY,SAAgB7E,GACpD,OAAOA,IAAQgE,MAAM5F,aAGvBsF,EAAW/G,KAAKkI,EAAYF,EAAMhB,QAASC,EAAMC,EAAQC,EAASC,GAElEc,EAAW9H,KAAO4H,EAAM5H,KAExB6H,GAAe1H,OAAOsF,OAAOqC,EAAYD,GAElCC,GAGT5I,EAAOD,QAAU0H,G,6BCnFjB,IAAIA,EAAa,EAAQ,GASzB,SAASoB,EAAcnB,GAErBD,EAAW/G,KAAKP,KAAiB,MAAXuH,EAAkB,WAAaA,EAASD,EAAWqB,cACzE3I,KAAKW,KAAO,gBAXF,EAAQ,GAcdqF,SAAS0C,EAAepB,EAAY,CACxCsB,YAAY,IAGd/I,EAAOD,QAAU8I,G,6BCnBjB,IAAIrB,EAAQ,EAAQ,GAChBwB,EAAsB,EAAQ,IAC9BvB,EAAa,EAAQ,GACrBwB,EAAuB,EAAQ,GAC/BC,EAAa,EAAQ,GAErBC,EAAuB,CACzB,eAAgB,qCAGlB,SAASC,EAAsBC,EAAS7H,IACjCgG,EAAMrE,YAAYkG,IAAY7B,EAAMrE,YAAYkG,EAAQ,mBAC3DA,EAAQ,gBAAkB7H,GA+B9B,IA1BM8H,EA0BFC,EAAW,CAEbC,aAAcP,EAEdK,UA7B8B,oBAAnBG,gBAGmB,oBAAZC,SAAuE,qBAA5CzI,OAAOkB,UAAUK,SAAS9B,KAAKgJ,YAD1EJ,EAAU,EAAQ,IAKbA,GAwBPK,iBAAkB,CAAC,SAA0BC,EAAMP,GAIjD,GAHAL,EAAoBK,EAAS,UAC7BL,EAAoBK,EAAS,gBAEzB7B,EAAMjD,WAAWqF,IACnBpC,EAAMpE,cAAcwG,IACpBpC,EAAMnD,SAASuF,IACfpC,EAAMzC,SAAS6E,IACfpC,EAAM/D,OAAOmG,IACbpC,EAAM9D,OAAOkG,GAEb,OAAOA,EAET,GAAIpC,EAAM/C,kBAAkBmF,GAC1B,OAAOA,EAAKhF,OAEd,GAAI4C,EAAM3D,kBAAkB+F,GAE1B,OADAR,EAAsBC,EAAS,mDACxBO,EAAKpH,WAGd,IAGImB,EAHAkG,EAAkBrC,EAAMnE,SAASuG,GACjCE,EAAcT,GAAWA,EAAQ,gBAIrC,IAAK1F,EAAa6D,EAAM7D,WAAWiG,KAAWC,GAAmC,wBAAhBC,EAAwC,CACvG,IAAIC,EAAY5J,KAAK6J,KAAO7J,KAAK6J,IAAIxF,SACrC,OAAO0E,EAAWvF,EAAa,CAAC,UAAWiG,GAAQA,EAAMG,GAAa,IAAIA,GACrE,OAAIF,GAAmC,qBAAhBC,GAC5BV,EAAsBC,EAAS,oBAnDrC,SAAyBY,EAAUC,EAAQC,GACzC,GAAI3C,EAAM3C,SAASoF,GACjB,IAEE,OADCC,GAAUE,KAAKC,OAAOJ,GAChBzC,EAAM1B,KAAKmE,GAClB,MAAOK,GACP,GAAe,gBAAXA,EAAExJ,KACJ,MAAMwJ,EAKZ,OAAQH,GAAWC,KAAKG,WAAWN,GAwCxBO,CAAgBZ,IAGlBA,IAGTa,kBAAmB,CAAC,SAA2Bb,GAC7C,IAAIJ,EAAerJ,KAAKqJ,cAAgBD,EAASC,aAC7CkB,EAAoBlB,GAAgBA,EAAakB,kBACjDC,EAAoBnB,GAAgBA,EAAamB,kBACjDC,GAAqBF,GAA2C,SAAtBvK,KAAK0K,aAEnD,GAAID,GAAsBD,GAAqBnD,EAAM3C,SAAS+E,IAASA,EAAK3F,OAC1E,IACE,OAAOmG,KAAKC,MAAMT,GAClB,MAAOU,GACP,GAAIM,EAAmB,CACrB,GAAe,gBAAXN,EAAExJ,KACJ,MAAM2G,EAAWgB,KAAK6B,EAAG7C,EAAWqD,iBAAkB3K,KAAM,KAAMA,KAAK2H,UAEzE,MAAMwC,GAKZ,OAAOV,IAOTmB,QAAS,EAETC,eAAgB,aAChBC,eAAgB,eAEhBC,kBAAmB,EACnBC,eAAgB,EAEhBnB,IAAK,CACHxF,SAAU,EAAQ,KAGpB4G,eAAgB,SAAwB7C,GACtC,OAAOA,GAAU,KAAOA,EAAS,KAGnCc,QAAS,CACPgC,OAAQ,CACN,OAAU,uCAKhB7D,EAAM1D,QAAQ,CAAC,SAAU,MAAO,SAAS,SAA6BwH,GACpE/B,EAASF,QAAQiC,GAAU,MAG7B9D,EAAM1D,QAAQ,CAAC,OAAQ,MAAO,UAAU,SAA+BwH,GACrE/B,EAASF,QAAQiC,GAAU9D,EAAMlC,MAAM6D,MAGzCnJ,EAAOD,QAAUwJ,G,6BC/IjBvJ,EAAOD,QAAU,SAAciE,EAAI6B,GACjC,OAAO,WAEL,IADA,IAAI0F,EAAO,IAAIrI,MAAMuC,UAAUxB,QACtB1D,EAAI,EAAGA,EAAIgL,EAAKtH,OAAQ1D,IAC/BgL,EAAKhL,GAAKkF,UAAUlF,GAEtB,OAAOyD,EAAGwH,MAAM3F,EAAS0F,M,6BCN7B,IAAI/D,EAAQ,EAAQ,GAEpB,SAASiE,EAAOxI,GACd,OAAOyI,mBAAmBzI,GACxB8C,QAAQ,QAAS,KACjBA,QAAQ,OAAQ,KAChBA,QAAQ,QAAS,KACjBA,QAAQ,OAAQ,KAChBA,QAAQ,QAAS,KACjBA,QAAQ,QAAS,KAUrB/F,EAAOD,QAAU,SAAkB4L,EAAKC,EAAQC,GAE9C,IAAKD,EACH,OAAOD,EAGT,IAAIG,EACJ,GAAID,EACFC,EAAmBD,EAAiBD,QAC/B,GAAIpE,EAAM3D,kBAAkB+H,GACjCE,EAAmBF,EAAOpJ,eACrB,CACL,IAAIuJ,EAAQ,GAEZvE,EAAM1D,QAAQ8H,GAAQ,SAAmB3I,EAAKnB,GACxCmB,UAIAuE,EAAMxE,QAAQC,GAChBnB,GAAY,KAEZmB,EAAM,CAACA,GAGTuE,EAAM1D,QAAQb,GAAK,SAAoB+I,GACjCxE,EAAMhE,OAAOwI,GACfA,EAAIA,EAAEC,cACGzE,EAAMnE,SAAS2I,KACxBA,EAAI5B,KAAKG,UAAUyB,IAErBD,EAAMG,KAAKT,EAAO3J,GAAO,IAAM2J,EAAOO,WAI1CF,EAAmBC,EAAMI,KAAK,KAGhC,GAAIL,EAAkB,CACpB,IAAIM,EAAgBT,EAAItE,QAAQ,MACT,IAAnB+E,IACFT,EAAMA,EAAI/I,MAAM,EAAGwJ,IAGrBT,KAA8B,IAAtBA,EAAItE,QAAQ,KAAc,IAAM,KAAOyE,EAGjD,OAAOH,I,6BClET3L,EAAOD,QAAU,CACf2K,mBAAmB,EACnBC,mBAAmB,EACnB0B,qBAAqB,I,6BCHvB,IAAI7E,EAAQ,EAAQ,GAqEpBxH,EAAOD,QA5DP,SAAoBgE,EAAKuI,GAEvBA,EAAWA,GAAY,IAAI9H,SAE3B,IAAI8D,EAAQ,GAEZ,SAASiE,EAAa/K,GACpB,OAAc,OAAVA,EAAuB,GAEvBgG,EAAMhE,OAAOhC,GACRA,EAAMyK,cAGXzE,EAAMpE,cAAc5B,IAAUgG,EAAMrD,aAAa3C,GAC5B,mBAATgL,KAAsB,IAAIA,KAAK,CAAChL,IAAUiL,OAAOhE,KAAKjH,GAG/DA,EAwCT,OArCA,SAASkL,EAAM9C,EAAM+C,GACnB,GAAInF,EAAMlE,cAAcsG,IAASpC,EAAMxE,QAAQ4G,GAAO,CACpD,IAA6B,IAAzBtB,EAAMjB,QAAQuC,GAChB,MAAM7B,MAAM,kCAAoC4E,GAGlDrE,EAAM4D,KAAKtC,GAEXpC,EAAM1D,QAAQ8F,GAAM,SAAcpI,EAAOM,GACvC,IAAI0F,EAAMrE,YAAY3B,GAAtB,CACA,IACI+F,EADAqF,EAAUD,EAAYA,EAAY,IAAM7K,EAAMA,EAGlD,GAAIN,IAAUmL,GAA8B,iBAAVnL,EAChC,GAAIgG,EAAMT,SAASjF,EAAK,MAEtBN,EAAQ4I,KAAKG,UAAU/I,QAClB,GAAIgG,EAAMT,SAASjF,EAAK,QAAUyF,EAAMC,EAAMF,QAAQ9F,IAK3D,YAHA+F,EAAIzD,SAAQ,SAAS+I,IAClBrF,EAAMrE,YAAY0J,IAAOP,EAASQ,OAAOF,EAASL,EAAaM,OAMtEH,EAAMlL,EAAOoL,OAGftE,EAAMyE,WAENT,EAASQ,OAAOH,EAAWJ,EAAa3C,IAI5C8C,CAAM3I,GAECuI,I,6BClET,IAAI9E,EAAQ,EAAQ,GAChBwF,EAAS,EAAQ,IACjBC,EAAU,EAAQ,IAClBC,EAAW,EAAQ,GACnBC,EAAgB,EAAQ,GACxBC,EAAe,EAAQ,IACvBC,EAAkB,EAAQ,IAC1BpE,EAAuB,EAAQ,GAC/BxB,EAAa,EAAQ,GACrBoB,EAAgB,EAAQ,GACxByE,EAAgB,EAAQ,IAE5BtN,EAAOD,QAAU,SAAoB6H,GACnC,OAAO,IAAI2F,SAAQ,SAA4BC,EAASC,GACtD,IAGIC,EAHAC,EAAc/F,EAAOgC,KACrBgE,EAAiBhG,EAAOyB,QACxBwB,EAAejD,EAAOiD,aAE1B,SAASgD,IACHjG,EAAOkG,aACTlG,EAAOkG,YAAYC,YAAYL,GAG7B9F,EAAOoG,QACTpG,EAAOoG,OAAOC,oBAAoB,QAASP,GAI3ClG,EAAMjD,WAAWoJ,IAAgBnG,EAAMvC,+BAClC2I,EAAe,gBAGxB,IAAI/F,EAAU,IAAI4B,eAGlB,GAAI7B,EAAOsG,KAAM,CACf,IAAIC,EAAWvG,EAAOsG,KAAKC,UAAY,GACnCC,EAAWxG,EAAOsG,KAAKE,SAAWC,SAAS3C,mBAAmB9D,EAAOsG,KAAKE,WAAa,GAC3FR,EAAeU,cAAgB,SAAWC,KAAKJ,EAAW,IAAMC,GAGlE,IAAII,EAAWrB,EAAcvF,EAAO6G,QAAS7G,EAAO+D,KAOpD,SAAS+C,IACP,GAAK7G,EAAL,CAIA,IAAI8G,EAAkB,0BAA2B9G,EAAUuF,EAAavF,EAAQ+G,yBAA2B,KAGvG9G,EAAW,CACb8B,KAHkBiB,GAAiC,SAAjBA,GAA6C,SAAjBA,EACvChD,EAAQC,SAA/BD,EAAQgH,aAGRtG,OAAQV,EAAQU,OAChBuG,WAAYjH,EAAQiH,WACpBzF,QAASsF,EACT/G,OAAQA,EACRC,QAASA,GAGXmF,GAAO,SAAkBxL,GACvBgM,EAAQhM,GACRqM,OACC,SAAiBkB,GAClBtB,EAAOsB,GACPlB,MACC/F,GAGHD,EAAU,MAoEZ,GAnGAA,EAAQmH,KAAKpH,EAAO0D,OAAO2D,cAAe/B,EAASsB,EAAU5G,EAAOgE,OAAQhE,EAAOiE,mBAAmB,GAGtGhE,EAAQkD,QAAUnD,EAAOmD,QA+BrB,cAAelD,EAEjBA,EAAQ6G,UAAYA,EAGpB7G,EAAQqH,mBAAqB,WACtBrH,GAAkC,IAAvBA,EAAQsH,aAQD,IAAnBtH,EAAQU,QAAkBV,EAAQuH,aAAwD,IAAzCvH,EAAQuH,YAAY/H,QAAQ,WAKjFgI,WAAWX,IAKf7G,EAAQyH,QAAU,WACXzH,IAIL4F,EAAO,IAAIhG,EAAW,kBAAmBA,EAAW8H,aAAc3H,EAAQC,IAG1EA,EAAU,OAIZA,EAAQ2H,QAAU,WAGhB/B,EAAO,IAAIhG,EAAW,gBAAiBA,EAAWgI,YAAa7H,EAAQC,EAASA,IAGhFA,EAAU,MAIZA,EAAQ6H,UAAY,WAClB,IAAIC,EAAsB/H,EAAOmD,QAAU,cAAgBnD,EAAOmD,QAAU,cAAgB,mBACxFvB,EAAe5B,EAAO4B,cAAgBP,EACtCrB,EAAO+H,sBACTA,EAAsB/H,EAAO+H,qBAE/BlC,EAAO,IAAIhG,EACTkI,EACAnG,EAAa6C,oBAAsB5E,EAAWmI,UAAYnI,EAAW8H,aACrE3H,EACAC,IAGFA,EAAU,MAMRL,EAAMvC,uBAAwB,CAEhC,IAAI4K,GAAajI,EAAOkI,iBAAmBzC,EAAgBmB,KAAc5G,EAAOoD,eAC9EiC,EAAQ8C,KAAKnI,EAAOoD,qBACpB7D,EAEE0I,IACFjC,EAAehG,EAAOqD,gBAAkB4E,GAKxC,qBAAsBhI,GACxBL,EAAM1D,QAAQ8J,GAAgB,SAA0B3K,EAAKnB,QAChC,IAAhB6L,GAAqD,iBAAtB7L,EAAIe,qBAErC+K,EAAe9L,GAGtB+F,EAAQmI,iBAAiBlO,EAAKmB,MAM/BuE,EAAMrE,YAAYyE,EAAOkI,mBAC5BjI,EAAQiI,kBAAoBlI,EAAOkI,iBAIjCjF,GAAiC,SAAjBA,IAClBhD,EAAQgD,aAAejD,EAAOiD,cAIS,mBAA9BjD,EAAOqI,oBAChBpI,EAAQqI,iBAAiB,WAAYtI,EAAOqI,oBAIP,mBAA5BrI,EAAOuI,kBAAmCtI,EAAQuI,QAC3DvI,EAAQuI,OAAOF,iBAAiB,WAAYtI,EAAOuI,mBAGjDvI,EAAOkG,aAAelG,EAAOoG,UAG/BN,EAAa,SAAS2C,GACfxI,IAGL4F,GAAQ4C,GAAWA,GAAUA,EAAOtN,KAAQ,IAAI8F,EAAkBwH,GAClExI,EAAQyI,QACRzI,EAAU,OAGZD,EAAOkG,aAAelG,EAAOkG,YAAYyC,UAAU7C,GAC/C9F,EAAOoG,SACTpG,EAAOoG,OAAOwC,QAAU9C,IAAe9F,EAAOoG,OAAOkC,iBAAiB,QAASxC,KAI9EC,IACHA,EAAc,MAGhB,IAAI8C,EAAWnD,EAAckB,GAEzBiC,IAA+D,IAAnD,CAAE,OAAQ,QAAS,QAASpJ,QAAQoJ,GAClDhD,EAAO,IAAIhG,EAAW,wBAA0BgJ,EAAW,IAAKhJ,EAAWiJ,gBAAiB9I,IAM9FC,EAAQ8I,KAAKhD,Q,6BCzNjB,IAAIiD,EAAgB,EAAQ,IACxBC,EAAc,EAAQ,IAW1B7Q,EAAOD,QAAU,SAAuB0O,EAASqC,GAC/C,OAAIrC,IAAYmC,EAAcE,GACrBD,EAAYpC,EAASqC,GAEvBA,I,6BChBT9Q,EAAOD,QAAU,SAAkByB,GACjC,SAAUA,IAASA,EAAMuH,c,6BCD3B,IAAIvB,EAAQ,EAAQ,GAUpBxH,EAAOD,QAAU,SAAqBgR,EAASC,GAE7CA,EAAUA,GAAW,GACrB,IAAIpJ,EAAS,GAEb,SAASqJ,EAAeC,EAAQC,GAC9B,OAAI3J,EAAMlE,cAAc4N,IAAW1J,EAAMlE,cAAc6N,GAC9C3J,EAAMlC,MAAM4L,EAAQC,GAClB3J,EAAMlE,cAAc6N,GACtB3J,EAAMlC,MAAM,GAAI6L,GACd3J,EAAMxE,QAAQmO,GAChBA,EAAOvO,QAETuO,EAIT,SAASC,EAAoBxK,GAC3B,OAAKY,EAAMrE,YAAY6N,EAAQpK,IAEnBY,EAAMrE,YAAY4N,EAAQnK,SAA/B,EACEqK,OAAe9J,EAAW4J,EAAQnK,IAFlCqK,EAAeF,EAAQnK,GAAOoK,EAAQpK,IAOjD,SAASyK,EAAiBzK,GACxB,IAAKY,EAAMrE,YAAY6N,EAAQpK,IAC7B,OAAOqK,OAAe9J,EAAW6J,EAAQpK,IAK7C,SAAS0K,EAAiB1K,GACxB,OAAKY,EAAMrE,YAAY6N,EAAQpK,IAEnBY,EAAMrE,YAAY4N,EAAQnK,SAA/B,EACEqK,OAAe9J,EAAW4J,EAAQnK,IAFlCqK,OAAe9J,EAAW6J,EAAQpK,IAO7C,SAAS2K,EAAgB3K,GACvB,OAAIA,KAAQoK,EACHC,EAAeF,EAAQnK,GAAOoK,EAAQpK,IACpCA,KAAQmK,EACVE,OAAe9J,EAAW4J,EAAQnK,SADpC,EAKT,IAAI4K,EAAW,CACb,IAAOH,EACP,OAAUA,EACV,KAAQA,EACR,QAAWC,EACX,iBAAoBA,EACpB,kBAAqBA,EACrB,iBAAoBA,EACpB,QAAWA,EACX,eAAkBA,EAClB,gBAAmBA,EACnB,QAAWA,EACX,aAAgBA,EAChB,eAAkBA,EAClB,eAAkBA,EAClB,iBAAoBA,EACpB,mBAAsBA,EACtB,WAAcA,EACd,iBAAoBA,EACpB,cAAiBA,EACjB,eAAkBA,EAClB,UAAaA,EACb,UAAaA,EACb,WAAcA,EACd,YAAeA,EACf,WAAcA,EACd,iBAAoBA,EACpB,eAAkBC,GASpB,OANA/J,EAAM1D,QAAQ7C,OAAOwQ,KAAKV,GAASW,OAAOzQ,OAAOwQ,KAAKT,KAAW,SAA4BpK,GAC3F,IAAItB,EAAQkM,EAAS5K,IAASwK,EAC1BO,EAAcrM,EAAMsB,GACvBY,EAAMrE,YAAYwO,IAAgBrM,IAAUiM,IAAqB3J,EAAOhB,GAAQ+K,MAG5E/J,I,cClGT5H,EAAOD,QAAU,CACf,QAAW,W,gBCDbC,EAAOD,QAAU,EAAQ,K,6BCEzB,IAAIyH,EAAQ,EAAQ,GAChBzF,EAAO,EAAQ,GACf6P,EAAQ,EAAQ,IAChBC,EAAc,EAAQ,IA4B1B,IAAIC,EAnBJ,SAASC,EAAeC,GACtB,IAAIC,EAAU,IAAIL,EAAMI,GACpBE,EAAWnQ,EAAK6P,EAAMzP,UAAU0F,QAASoK,GAa7C,OAVAzK,EAAM9B,OAAOwM,EAAUN,EAAMzP,UAAW8P,GAGxCzK,EAAM9B,OAAOwM,EAAUD,GAGvBC,EAASrQ,OAAS,SAAgBsQ,GAChC,OAAOJ,EAAeF,EAAYG,EAAeG,KAG5CD,EAIGH,CA3BG,EAAQ,IA8BvBD,EAAMF,MAAQA,EAGdE,EAAMjJ,cAAgB,EAAQ,GAC9BiJ,EAAMM,YAAc,EAAQ,IAC5BN,EAAMO,SAAW,EAAQ,IACzBP,EAAMQ,QAAU,EAAQ,IAAcC,QACtCT,EAAM5I,WAAa,EAAQ,GAG3B4I,EAAMrK,WAAa,EAAQ,GAG3BqK,EAAMU,OAASV,EAAMjJ,cAGrBiJ,EAAMW,IAAM,SAAaC,GACvB,OAAOnF,QAAQkF,IAAIC,IAErBZ,EAAMa,OAAS,EAAQ,IAGvBb,EAAMc,aAAe,EAAQ,IAE7B5S,EAAOD,QAAU+R,EAGjB9R,EAAOD,QAAQ8S,QAAUf,G,6BC7DzB,IAAItK,EAAQ,EAAQ,GAChB0F,EAAW,EAAQ,GACnB4F,EAAqB,EAAQ,IAC7BC,EAAkB,EAAQ,IAC1BlB,EAAc,EAAQ,IACtB1E,EAAgB,EAAQ,GACxB6F,EAAY,EAAQ,IAEpBC,EAAaD,EAAUC,WAM3B,SAASrB,EAAMO,GACbhS,KAAKoJ,SAAW4I,EAChBhS,KAAK+S,aAAe,CAClBrL,QAAS,IAAIiL,EACbhL,SAAU,IAAIgL,GASlBlB,EAAMzP,UAAU0F,QAAU,SAAiBsL,EAAavL,GAG3B,iBAAhBuL,GACTvL,EAASA,GAAU,IACZ+D,IAAMwH,EAEbvL,EAASuL,GAAe,IAG1BvL,EAASiK,EAAY1R,KAAKoJ,SAAU3B,IAGzB0D,OACT1D,EAAO0D,OAAS1D,EAAO0D,OAAOzI,cACrB1C,KAAKoJ,SAAS+B,OACvB1D,EAAO0D,OAASnL,KAAKoJ,SAAS+B,OAAOzI,cAErC+E,EAAO0D,OAAS,MAGlB,IAAI9B,EAAe5B,EAAO4B,kBAELrC,IAAjBqC,GACFwJ,EAAUI,cAAc5J,EAAc,CACpCkB,kBAAmBuI,EAAWzJ,aAAayJ,EAAWI,SACtD1I,kBAAmBsI,EAAWzJ,aAAayJ,EAAWI,SACtDhH,oBAAqB4G,EAAWzJ,aAAayJ,EAAWI,WACvD,GAIL,IAAIC,EAA0B,GAC1BC,GAAiC,EACrCpT,KAAK+S,aAAarL,QAAQ/D,SAAQ,SAAoC0P,GACjC,mBAAxBA,EAAYC,UAA0D,IAAhCD,EAAYC,QAAQ7L,KAIrE2L,EAAiCA,GAAkCC,EAAYE,YAE/EJ,EAAwBK,QAAQH,EAAYI,UAAWJ,EAAYK,cAGrE,IAKIC,EALAC,EAA2B,GAO/B,GANA5T,KAAK+S,aAAapL,SAAShE,SAAQ,SAAkC0P,GACnEO,EAAyB7H,KAAKsH,EAAYI,UAAWJ,EAAYK,cAK9DN,EAAgC,CACnC,IAAIS,EAAQ,CAACjB,OAAiB5L,GAM9B,IAJAjE,MAAMf,UAAUwR,QAAQnI,MAAMwI,EAAOV,GACrCU,EAAQA,EAAMtC,OAAOqC,GAErBD,EAAUvG,QAAQC,QAAQ5F,GACnBoM,EAAM/P,QACX6P,EAAUA,EAAQG,KAAKD,EAAME,QAASF,EAAME,SAG9C,OAAOJ,EAKT,IADA,IAAIK,EAAYvM,EACT0L,EAAwBrP,QAAQ,CACrC,IAAImQ,EAAcd,EAAwBY,QACtCG,EAAaf,EAAwBY,QACzC,IACEC,EAAYC,EAAYD,GACxB,MAAOzL,GACP2L,EAAW3L,GACX,OAIJ,IACEoL,EAAUf,EAAgBoB,GAC1B,MAAOzL,GACP,OAAO6E,QAAQE,OAAO/E,GAGxB,KAAOqL,EAAyB9P,QAC9B6P,EAAUA,EAAQG,KAAKF,EAAyBG,QAASH,EAAyBG,SAGpF,OAAOJ,GAGTlC,EAAMzP,UAAUmS,OAAS,SAAgB1M,GACvCA,EAASiK,EAAY1R,KAAKoJ,SAAU3B,GACpC,IAAI4G,EAAWrB,EAAcvF,EAAO6G,QAAS7G,EAAO+D,KACpD,OAAOuB,EAASsB,EAAU5G,EAAOgE,OAAQhE,EAAOiE,mBAIlDrE,EAAM1D,QAAQ,CAAC,SAAU,MAAO,OAAQ,YAAY,SAA6BwH,GAE/EsG,EAAMzP,UAAUmJ,GAAU,SAASK,EAAK/D,GACtC,OAAOzH,KAAK0H,QAAQgK,EAAYjK,GAAU,GAAI,CAC5C0D,OAAQA,EACRK,IAAKA,EACL/B,MAAOhC,GAAU,IAAIgC,YAK3BpC,EAAM1D,QAAQ,CAAC,OAAQ,MAAO,UAAU,SAA+BwH,GAGrE,SAASiJ,EAAmBC,GAC1B,OAAO,SAAoB7I,EAAK/B,EAAMhC,GACpC,OAAOzH,KAAK0H,QAAQgK,EAAYjK,GAAU,GAAI,CAC5C0D,OAAQA,EACRjC,QAASmL,EAAS,CAChB,eAAgB,uBACd,GACJ7I,IAAKA,EACL/B,KAAMA,MAKZgI,EAAMzP,UAAUmJ,GAAUiJ,IAE1B3C,EAAMzP,UAAUmJ,EAAS,QAAUiJ,GAAmB,MAGxDvU,EAAOD,QAAU6R,G,6BC7JjB,IAAIpK,EAAQ,EAAQ,GAEpB,SAASsL,IACP3S,KAAKsU,SAAW,GAWlB3B,EAAmB3Q,UAAUuS,IAAM,SAAad,EAAWC,EAAUc,GAOnE,OANAxU,KAAKsU,SAASvI,KAAK,CACjB0H,UAAWA,EACXC,SAAUA,EACVH,cAAaiB,GAAUA,EAAQjB,YAC/BD,QAASkB,EAAUA,EAAQlB,QAAU,OAEhCtT,KAAKsU,SAASxQ,OAAS,GAQhC6O,EAAmB3Q,UAAUyS,MAAQ,SAAeC,GAC9C1U,KAAKsU,SAASI,KAChB1U,KAAKsU,SAASI,GAAM,OAYxB/B,EAAmB3Q,UAAU2B,QAAU,SAAiBE,GACtDwD,EAAM1D,QAAQ3D,KAAKsU,UAAU,SAAwBK,GACzC,OAANA,GACF9Q,EAAG8Q,OAKT9U,EAAOD,QAAU+S,G,6BCnDjB,IAAItL,EAAQ,EAAQ,GAChBuN,EAAgB,EAAQ,IACxB1C,EAAW,EAAQ,IACnB9I,EAAW,EAAQ,GACnBV,EAAgB,EAAQ,GAK5B,SAASmM,EAA6BpN,GAKpC,GAJIA,EAAOkG,aACTlG,EAAOkG,YAAYmH,mBAGjBrN,EAAOoG,QAAUpG,EAAOoG,OAAOwC,QACjC,MAAM,IAAI3H,EAUd7I,EAAOD,QAAU,SAAyB6H,GA8BxC,OA7BAoN,EAA6BpN,GAG7BA,EAAOyB,QAAUzB,EAAOyB,SAAW,GAGnCzB,EAAOgC,KAAOmL,EAAcrU,KAC1BkH,EACAA,EAAOgC,KACPhC,EAAOyB,QACPzB,EAAO+B,kBAIT/B,EAAOyB,QAAU7B,EAAMlC,MACrBsC,EAAOyB,QAAQgC,QAAU,GACzBzD,EAAOyB,QAAQzB,EAAO0D,SAAW,GACjC1D,EAAOyB,SAGT7B,EAAM1D,QACJ,CAAC,SAAU,MAAO,OAAQ,OAAQ,MAAO,QAAS,WAClD,SAA2BwH,UAClB1D,EAAOyB,QAAQiC,OAIZ1D,EAAO0B,SAAWC,EAASD,SAE1B1B,GAAQqM,MAAK,SAA6BnM,GAWvD,OAVAkN,EAA6BpN,GAG7BE,EAAS8B,KAAOmL,EAAcrU,KAC5BkH,EACAE,EAAS8B,KACT9B,EAASuB,QACTzB,EAAO6C,mBAGF3C,KACN,SAA4BoN,GAe7B,OAdK7C,EAAS6C,KACZF,EAA6BpN,GAGzBsN,GAAUA,EAAOpN,WACnBoN,EAAOpN,SAAS8B,KAAOmL,EAAcrU,KACnCkH,EACAsN,EAAOpN,SAAS8B,KAChBsL,EAAOpN,SAASuB,QAChBzB,EAAO6C,qBAKN8C,QAAQE,OAAOyH,Q,6BClF1B,IAAI1N,EAAQ,EAAQ,GAChB+B,EAAW,EAAQ,GAUvBvJ,EAAOD,QAAU,SAAuB6J,EAAMP,EAAS8L,GACrD,IAAIlD,EAAU9R,MAAQoJ,EAMtB,OAJA/B,EAAM1D,QAAQqR,GAAK,SAAmBnR,GACpC4F,EAAO5F,EAAGtD,KAAKuR,EAASrI,EAAMP,MAGzBO,I,6BClBT,IAAIpC,EAAQ,EAAQ,GAEpBxH,EAAOD,QAAU,SAA6BsJ,EAAS+L,GACrD5N,EAAM1D,QAAQuF,GAAS,SAAuB7H,EAAOV,GAC/CA,IAASsU,GAAkBtU,EAAKmO,gBAAkBmG,EAAenG,gBACnE5F,EAAQ+L,GAAkB5T,SACnB6H,EAAQvI,S,6BCNrB,IAAI2G,EAAa,EAAQ,GASzBzH,EAAOD,QAAU,SAAgByN,EAASC,EAAQ3F,GAChD,IAAIsD,EAAiBtD,EAASF,OAAOwD,eAChCtD,EAASS,QAAW6C,IAAkBA,EAAetD,EAASS,QAGjEkF,EAAO,IAAIhG,EACT,mCAAqCK,EAASS,OAC9C,CAACd,EAAWiJ,gBAAiBjJ,EAAWqD,kBAAkBuK,KAAKC,MAAMxN,EAASS,OAAS,KAAO,GAC9FT,EAASF,OACTE,EAASD,QACTC,IAPF0F,EAAQ1F,K,6BCZZ,IAAIN,EAAQ,EAAQ,GAEpBxH,EAAOD,QACLyH,EAAMvC,uBAIK,CACLsQ,MAAO,SAAezU,EAAMU,EAAOgU,EAASC,EAAMC,EAAQC,GACxD,IAAIC,EAAS,GACbA,EAAO1J,KAAKpL,EAAO,IAAM4K,mBAAmBlK,IAExCgG,EAAM1C,SAAS0Q,IACjBI,EAAO1J,KAAK,WAAa,IAAI2J,KAAKL,GAASM,eAGzCtO,EAAM3C,SAAS4Q,IACjBG,EAAO1J,KAAK,QAAUuJ,GAGpBjO,EAAM3C,SAAS6Q,IACjBE,EAAO1J,KAAK,UAAYwJ,IAGX,IAAXC,GACFC,EAAO1J,KAAK,UAGd7G,SAASuQ,OAASA,EAAOzJ,KAAK,OAGhC4D,KAAM,SAAcjP,GAClB,IAAIiV,EAAQ1Q,SAASuQ,OAAOG,MAAM,IAAIC,OAAO,aAAelV,EAAO,cACnE,OAAQiV,EAAQE,mBAAmBF,EAAM,IAAM,MAGjDG,OAAQ,SAAgBpV,GACtBX,KAAKoV,MAAMzU,EAAM,GAAI+U,KAAKM,MAAQ,SAO/B,CACLZ,MAAO,aACPxF,KAAM,WAAkB,OAAO,MAC/BmG,OAAQ,e,6BCzChBlW,EAAOD,QAAU,SAAuB4L,GAItC,MAAO,8BAA8ByK,KAAKzK,K,6BCH5C3L,EAAOD,QAAU,SAAqB0O,EAAS4H,GAC7C,OAAOA,EACH5H,EAAQ1I,QAAQ,OAAQ,IAAM,IAAMsQ,EAAYtQ,QAAQ,OAAQ,IAChE0I,I,6BCVN,IAAIjH,EAAQ,EAAQ,GAIhB8O,EAAoB,CACtB,MAAO,gBAAiB,iBAAkB,eAAgB,OAC1D,UAAW,OAAQ,OAAQ,oBAAqB,sBAChD,gBAAiB,WAAY,eAAgB,sBAC7C,UAAW,cAAe,cAgB5BtW,EAAOD,QAAU,SAAsBsJ,GACrC,IACIvH,EACAmB,EACA1C,EAHAgW,EAAS,GAKb,OAAKlN,GAEL7B,EAAM1D,QAAQuF,EAAQmN,MAAM,OAAO,SAAgBC,GAKjD,GAJAlW,EAAIkW,EAAKpP,QAAQ,KACjBvF,EAAM0F,EAAM1B,KAAK2Q,EAAKC,OAAO,EAAGnW,IAAIsC,cACpCI,EAAMuE,EAAM1B,KAAK2Q,EAAKC,OAAOnW,EAAI,IAE7BuB,EAAK,CACP,GAAIyU,EAAOzU,IAAQwU,EAAkBjP,QAAQvF,IAAQ,EACnD,OAGAyU,EAAOzU,GADG,eAARA,GACayU,EAAOzU,GAAOyU,EAAOzU,GAAO,IAAI4P,OAAO,CAACzO,IAEzCsT,EAAOzU,GAAOyU,EAAOzU,GAAO,KAAOmB,EAAMA,MAKtDsT,GAnBgBA,I,6BC9BzB,IAAI/O,EAAQ,EAAQ,GAEpBxH,EAAOD,QACLyH,EAAMvC,uBAIJ,WACE,IAEI0R,EAFAC,EAAO,kBAAkBR,KAAKlR,UAAU2R,WACxCC,EAAiBzR,SAAS0R,cAAc,KAS5C,SAASC,EAAWrL,GAClB,IAAIsL,EAAOtL,EAWX,OATIiL,IAEFE,EAAeI,aAAa,OAAQD,GACpCA,EAAOH,EAAeG,MAGxBH,EAAeI,aAAa,OAAQD,GAG7B,CACLA,KAAMH,EAAeG,KACrBxG,SAAUqG,EAAerG,SAAWqG,EAAerG,SAAS1K,QAAQ,KAAM,IAAM,GAChFoR,KAAML,EAAeK,KACrBC,OAAQN,EAAeM,OAASN,EAAeM,OAAOrR,QAAQ,MAAO,IAAM,GAC3EsR,KAAMP,EAAeO,KAAOP,EAAeO,KAAKtR,QAAQ,KAAM,IAAM,GACpEuR,SAAUR,EAAeQ,SACzBC,KAAMT,EAAeS,KACrBC,SAAiD,MAAtCV,EAAeU,SAASC,OAAO,GACxCX,EAAeU,SACf,IAAMV,EAAeU,UAY3B,OARAb,EAAYK,EAAW5R,OAAOsS,SAAST,MAQhC,SAAyBU,GAC9B,IAAIpB,EAAU/O,EAAM3C,SAAS8S,GAAeX,EAAWW,GAAcA,EACrE,OAAQpB,EAAO9F,WAAakG,EAAUlG,UAClC8F,EAAOY,OAASR,EAAUQ,MAhDlC,GAsDS,WACL,OAAO,I,6BC9DfnX,EAAOD,QAAU,SAAuB4L,GACtC,IAAIoK,EAAQ,4BAA4B6B,KAAKjM,GAC7C,OAAOoK,GAASA,EAAM,IAAM,K,cCH9B/V,EAAOD,QAAU,M,6BCCjB,IAAIuS,EAAU,EAAQ,IAAeC,QACjC9K,EAAa,EAAQ,GAErBwL,EAAa,GAGjB,CAAC,SAAU,UAAW,SAAU,WAAY,SAAU,UAAUnP,SAAQ,SAASf,EAAMxC,GACrF0S,EAAWlQ,GAAQ,SAAmBL,GACpC,cAAcA,IAAUK,GAAQ,KAAOxC,EAAI,EAAI,KAAO,KAAOwC,MAIjE,IAAI8U,EAAqB,GASzB5E,EAAWzJ,aAAe,SAAsBwJ,EAAWT,EAAS7K,GAClE,SAASoQ,EAAcC,EAAKC,GAC1B,MAAO,WAAa1F,EAAU,0BAA6ByF,EAAM,IAAOC,GAAQtQ,EAAU,KAAOA,EAAU,IAI7G,OAAO,SAASlG,EAAOuW,EAAKE,GAC1B,IAAkB,IAAdjF,EACF,MAAM,IAAIvL,EACRqQ,EAAcC,EAAK,qBAAuBxF,EAAU,OAASA,EAAU,KACvE9K,EAAWyQ,gBAef,OAXI3F,IAAYsF,EAAmBE,KACjCF,EAAmBE,IAAO,EAE1BI,QAAQC,KACNN,EACEC,EACA,+BAAiCxF,EAAU,8CAK1CS,GAAYA,EAAUxR,EAAOuW,EAAKE,KAkC7CjY,EAAOD,QAAU,CACfqT,cAxBF,SAAuBuB,EAAS0D,EAAQC,GACtC,GAAuB,iBAAZ3D,EACT,MAAM,IAAIlN,EAAW,4BAA6BA,EAAW8Q,sBAI/D,IAFA,IAAI9G,EAAOxQ,OAAOwQ,KAAKkD,GACnBpU,EAAIkR,EAAKxN,OACN1D,KAAM,GAAG,CACd,IAAIwX,EAAMtG,EAAKlR,GACXyS,EAAYqF,EAAON,GACvB,GAAI/E,EAAJ,CACE,IAAIxR,EAAQmT,EAAQoD,GAChBxS,OAAmB4B,IAAV3F,GAAuBwR,EAAUxR,EAAOuW,EAAKpD,GAC1D,IAAe,IAAXpP,EACF,MAAM,IAAIkC,EAAW,UAAYsQ,EAAM,YAAcxS,EAAQkC,EAAW8Q,2BAI5E,IAAqB,IAAjBD,EACF,MAAM,IAAI7Q,EAAW,kBAAoBsQ,EAAKtQ,EAAW+Q,kBAO7DvF,WAAYA,I,6BClFd,IAAIpK,EAAgB,EAAQ,GAQ5B,SAASuJ,EAAYqG,GACnB,GAAwB,mBAAbA,EACT,MAAM,IAAIC,UAAU,gCAGtB,IAAIC,EAEJxY,KAAK2T,QAAU,IAAIvG,SAAQ,SAAyBC,GAClDmL,EAAiBnL,KAGnB,IAAIoL,EAAQzY,KAGZA,KAAK2T,QAAQG,MAAK,SAAS5D,GACzB,GAAKuI,EAAMC,WAAX,CAEA,IAAItY,EACAC,EAAIoY,EAAMC,WAAW5U,OAEzB,IAAK1D,EAAI,EAAGA,EAAIC,EAAGD,IACjBqY,EAAMC,WAAWtY,GAAG8P,GAEtBuI,EAAMC,WAAa,SAIrB1Y,KAAK2T,QAAQG,KAAO,SAAS6E,GAC3B,IAAIC,EAEAjF,EAAU,IAAIvG,SAAQ,SAASC,GACjCoL,EAAMrI,UAAU/C,GAChBuL,EAAWvL,KACVyG,KAAK6E,GAMR,OAJAhF,EAAQzD,OAAS,WACfuI,EAAM7K,YAAYgL,IAGbjF,GAGT2E,GAAS,SAAgB/Q,GACnBkR,EAAM1D,SAKV0D,EAAM1D,OAAS,IAAIrM,EAAcnB,GACjCiR,EAAeC,EAAM1D,YAOzB9C,EAAYjQ,UAAU8S,iBAAmB,WACvC,GAAI9U,KAAK+U,OACP,MAAM/U,KAAK+U,QAQf9C,EAAYjQ,UAAUoO,UAAY,SAAmByI,GAC/C7Y,KAAK+U,OACP8D,EAAS7Y,KAAK+U,QAIZ/U,KAAK0Y,WACP1Y,KAAK0Y,WAAW3M,KAAK8M,GAErB7Y,KAAK0Y,WAAa,CAACG,IAQvB5G,EAAYjQ,UAAU4L,YAAc,SAAqBiL,GACvD,GAAK7Y,KAAK0Y,WAAV,CAGA,IAAII,EAAQ9Y,KAAK0Y,WAAWxR,QAAQ2R,IACrB,IAAXC,GACF9Y,KAAK0Y,WAAWK,OAAOD,EAAO,KAQlC7G,EAAYjB,OAAS,WACnB,IAAId,EAIJ,MAAO,CACLuI,MAJU,IAAIxG,GAAY,SAAkBxR,GAC5CyP,EAASzP,KAITyP,OAAQA,IAIZrQ,EAAOD,QAAUqS,G,6BChGjBpS,EAAOD,QAAU,SAAgBoZ,GAC/B,OAAO,SAAc5R,GACnB,OAAO4R,EAAS3N,MAAM,KAAMjE,M,6BCtBhC,IAAIC,EAAQ,EAAQ,GAQpBxH,EAAOD,QAAU,SAAsBqZ,GACrC,OAAO5R,EAAMnE,SAAS+V,KAAsC,IAAzBA,EAAQxG","file":"axios.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"axios\"] = factory();\n\telse\n\t\troot[\"axios\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 13);\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n// eslint-disable-next-line func-names\nvar kindOf = (function(cache) {\n // eslint-disable-next-line func-names\n return function(thing) {\n var str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n };\n})(Object.create(null));\n\nfunction kindOfTest(type) {\n type = type.toLowerCase();\n return function isKindOf(thing) {\n return kindOf(thing) === type;\n };\n}\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return Array.isArray(val);\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nvar isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nvar isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nvar isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nvar isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nvar isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} thing The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(thing) {\n var pattern = '[object FormData]';\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) ||\n toString.call(thing) === pattern ||\n (isFunction(thing.toString) && thing.toString() === pattern)\n );\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nvar isURLSearchParams = kindOfTest('URLSearchParams');\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n */\n\nfunction inherits(constructor, superConstructor, props, descriptors) {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function} [filter]\n * @returns {Object}\n */\n\nfunction toFlatObject(sourceObj, destObj, filter) {\n var props;\n var i;\n var prop;\n var merged = {};\n\n destObj = destObj || {};\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if (!merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = Object.getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/*\n * determines whether a string ends with the characters of a specified string\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n * @returns {boolean}\n */\nfunction endsWith(str, searchString, position) {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n var lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object\n * @param {*} [thing]\n * @returns {Array}\n */\nfunction toArray(thing) {\n if (!thing) return null;\n var i = thing.length;\n if (isUndefined(i)) return null;\n var arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n// eslint-disable-next-line func-names\nvar isTypedArray = (function(TypedArray) {\n // eslint-disable-next-line func-names\n return function(thing) {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM,\n inherits: inherits,\n toFlatObject: toFlatObject,\n kindOf: kindOf,\n kindOfTest: kindOfTest,\n endsWith: endsWith,\n toArray: toArray,\n isTypedArray: isTypedArray,\n isFileList: isFileList\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n response && (this.response = response);\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n }\n});\n\nvar prototype = AxiosError.prototype;\nvar descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED'\n// eslint-disable-next-line func-names\n].forEach(function(code) {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = function(error, code, config, request, response, customProps) {\n var axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nmodule.exports = AxiosError;\n","'use strict';\n\nvar AxiosError = require('../core/AxiosError');\nvar utils = require('../utils');\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction CanceledError(message) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nmodule.exports = CanceledError;\n","'use strict';\n\nvar utils = require('../utils');\nvar normalizeHeaderName = require('../helpers/normalizeHeaderName');\nvar AxiosError = require('../core/AxiosError');\nvar transitionalDefaults = require('./transitional');\nvar toFormData = require('../helpers/toFormData');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('../adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('../adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n\n var isObjectPayload = utils.isObject(data);\n var contentType = headers && headers['Content-Type'];\n\n var isFileList;\n\n if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {\n var _FormData = this.env && this.env.FormData;\n return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData());\n } else if (isObjectPayload || contentType === 'application/json') {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional || defaults.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: require('./env/FormData')\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\nmodule.exports = {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Convert a data object to FormData\n * @param {Object} obj\n * @param {?Object} [formData]\n * @returns {Object}\n **/\n\nfunction toFormData(obj, formData) {\n // eslint-disable-next-line no-param-reassign\n formData = formData || new FormData();\n\n var stack = [];\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n function build(data, parentKey) {\n if (utils.isPlainObject(data) || utils.isArray(data)) {\n if (stack.indexOf(data) !== -1) {\n throw Error('Circular reference detected in ' + parentKey);\n }\n\n stack.push(data);\n\n utils.forEach(data, function each(value, key) {\n if (utils.isUndefined(value)) return;\n var fullKey = parentKey ? parentKey + '.' + key : key;\n var arr;\n\n if (value && !parentKey && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {\n // eslint-disable-next-line func-names\n arr.forEach(function(el) {\n !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));\n });\n return;\n }\n }\n\n build(value, fullKey);\n });\n\n stack.pop();\n } else {\n formData.append(parentKey, convertValue(data));\n }\n }\n\n build(obj);\n\n return formData;\n}\n\nmodule.exports = toFormData;\n","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar transitionalDefaults = require('../defaults/transitional');\nvar AxiosError = require('../core/AxiosError');\nvar CanceledError = require('../cancel/CanceledError');\nvar parseProtocol = require('../helpers/parseProtocol');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n var onCanceled;\n function done() {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', onCanceled);\n }\n }\n\n if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';\n var transitional = config.transitional || transitionalDefaults;\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken || config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = function(cancel) {\n if (!request) {\n return;\n }\n reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);\n request.abort();\n request = null;\n };\n\n config.cancelToken && config.cancelToken.subscribe(onCanceled);\n if (config.signal) {\n config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n var protocol = parseProtocol(fullPath);\n\n if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(prop) {\n if (prop in config2) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n var mergeMap = {\n 'url': valueFromConfig2,\n 'method': valueFromConfig2,\n 'data': valueFromConfig2,\n 'baseURL': defaultToConfig2,\n 'transformRequest': defaultToConfig2,\n 'transformResponse': defaultToConfig2,\n 'paramsSerializer': defaultToConfig2,\n 'timeout': defaultToConfig2,\n 'timeoutMessage': defaultToConfig2,\n 'withCredentials': defaultToConfig2,\n 'adapter': defaultToConfig2,\n 'responseType': defaultToConfig2,\n 'xsrfCookieName': defaultToConfig2,\n 'xsrfHeaderName': defaultToConfig2,\n 'onUploadProgress': defaultToConfig2,\n 'onDownloadProgress': defaultToConfig2,\n 'decompress': defaultToConfig2,\n 'maxContentLength': defaultToConfig2,\n 'maxBodyLength': defaultToConfig2,\n 'beforeRedirect': defaultToConfig2,\n 'transport': defaultToConfig2,\n 'httpAgent': defaultToConfig2,\n 'httpsAgent': defaultToConfig2,\n 'cancelToken': defaultToConfig2,\n 'socketPath': defaultToConfig2,\n 'responseEncoding': defaultToConfig2,\n 'validateStatus': mergeDirectKeys\n };\n\n utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {\n var merge = mergeMap[prop] || mergeDeepProperties;\n var configValue = merge(prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n};\n","module.exports = {\n \"version\": \"0.27.2\"\n};","module.exports = require('./lib/axios');","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = require('./cancel/CanceledError');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\naxios.VERSION = require('./env/data').version;\naxios.toFormData = require('./helpers/toFormData');\n\n// Expose AxiosError class\naxios.AxiosError = require('../lib/core/AxiosError');\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar buildFullPath = require('./buildFullPath');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n var fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url: url,\n data: data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nmodule.exports = Axios;\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\nvar CanceledError = require('../cancel/CanceledError');\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","'use strict';\n\nvar AxiosError = require('./AxiosError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"<scheme>://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\nmodule.exports = function parseProtocol(url) {\n var match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n};\n","// eslint-disable-next-line strict\nmodule.exports = null;\n","'use strict';\n\nvar VERSION = require('../env/data').version;\nvar AxiosError = require('../core/AxiosError');\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nmodule.exports = {\n assertOptions: assertOptions,\n validators: validators\n};\n","'use strict';\n\nvar CanceledError = require('./CanceledError');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(function(cancel) {\n if (!token._listeners) return;\n\n var i;\n var l = token._listeners.length;\n\n for (i = 0; i < l; i++) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = function(onfulfilled) {\n var _resolve;\n // eslint-disable-next-line func-names\n var promise = new Promise(function(resolve) {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Subscribe to the cancel signal\n */\n\nCancelToken.prototype.subscribe = function subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n};\n\n/**\n * Unsubscribe from the cancel signal\n */\n\nCancelToken.prototype.unsubscribe = function unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n var index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n};\n"],"sourceRoot":""}
...\ No newline at end of file ...\ No newline at end of file
1 -// TypeScript Version: 3.0
2 -export type AxiosRequestHeaders = Record<string, string | number | boolean>;
3 -
4 -export type AxiosResponseHeaders = Record<string, string> & {
5 - "set-cookie"?: string[]
6 -};
7 -
8 -export interface AxiosRequestTransformer {
9 - (data: any, headers?: AxiosRequestHeaders): any;
10 -}
11 -
12 -export interface AxiosResponseTransformer {
13 - (data: any, headers?: AxiosResponseHeaders): any;
14 -}
15 -
16 -export interface AxiosAdapter {
17 - (config: AxiosRequestConfig): AxiosPromise;
18 -}
19 -
20 -export interface AxiosBasicCredentials {
21 - username: string;
22 - password: string;
23 -}
24 -
25 -export interface AxiosProxyConfig {
26 - host: string;
27 - port: number;
28 - auth?: {
29 - username: string;
30 - password: string;
31 - };
32 - protocol?: string;
33 -}
34 -
35 -export type Method =
36 - | 'get' | 'GET'
37 - | 'delete' | 'DELETE'
38 - | 'head' | 'HEAD'
39 - | 'options' | 'OPTIONS'
40 - | 'post' | 'POST'
41 - | 'put' | 'PUT'
42 - | 'patch' | 'PATCH'
43 - | 'purge' | 'PURGE'
44 - | 'link' | 'LINK'
45 - | 'unlink' | 'UNLINK';
46 -
47 -export type ResponseType =
48 - | 'arraybuffer'
49 - | 'blob'
50 - | 'document'
51 - | 'json'
52 - | 'text'
53 - | 'stream';
54 -
55 - export type responseEncoding =
56 - | 'ascii' | 'ASCII'
57 - | 'ansi' | 'ANSI'
58 - | 'binary' | 'BINARY'
59 - | 'base64' | 'BASE64'
60 - | 'base64url' | 'BASE64URL'
61 - | 'hex' | 'HEX'
62 - | 'latin1' | 'LATIN1'
63 - | 'ucs-2' | 'UCS-2'
64 - | 'ucs2' | 'UCS2'
65 - | 'utf-8' | 'UTF-8'
66 - | 'utf8' | 'UTF8'
67 - | 'utf16le' | 'UTF16LE';
68 -
69 -export interface TransitionalOptions {
70 - silentJSONParsing?: boolean;
71 - forcedJSONParsing?: boolean;
72 - clarifyTimeoutError?: boolean;
73 -}
74 -
75 -export interface AxiosRequestConfig<D = any> {
76 - url?: string;
77 - method?: Method | string;
78 - baseURL?: string;
79 - transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
80 - transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
81 - headers?: AxiosRequestHeaders;
82 - params?: any;
83 - paramsSerializer?: (params: any) => string;
84 - data?: D;
85 - timeout?: number;
86 - timeoutErrorMessage?: string;
87 - withCredentials?: boolean;
88 - adapter?: AxiosAdapter;
89 - auth?: AxiosBasicCredentials;
90 - responseType?: ResponseType;
91 - responseEncoding?: responseEncoding | string;
92 - xsrfCookieName?: string;
93 - xsrfHeaderName?: string;
94 - onUploadProgress?: (progressEvent: any) => void;
95 - onDownloadProgress?: (progressEvent: any) => void;
96 - maxContentLength?: number;
97 - validateStatus?: ((status: number) => boolean) | null;
98 - maxBodyLength?: number;
99 - maxRedirects?: number;
100 - beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
101 - socketPath?: string | null;
102 - httpAgent?: any;
103 - httpsAgent?: any;
104 - proxy?: AxiosProxyConfig | false;
105 - cancelToken?: CancelToken;
106 - decompress?: boolean;
107 - transitional?: TransitionalOptions;
108 - signal?: AbortSignal;
109 - insecureHTTPParser?: boolean;
110 - env?: {
111 - FormData?: new (...args: any[]) => object;
112 - };
113 -}
114 -
115 -export interface HeadersDefaults {
116 - common: AxiosRequestHeaders;
117 - delete: AxiosRequestHeaders;
118 - get: AxiosRequestHeaders;
119 - head: AxiosRequestHeaders;
120 - post: AxiosRequestHeaders;
121 - put: AxiosRequestHeaders;
122 - patch: AxiosRequestHeaders;
123 - options?: AxiosRequestHeaders;
124 - purge?: AxiosRequestHeaders;
125 - link?: AxiosRequestHeaders;
126 - unlink?: AxiosRequestHeaders;
127 -}
128 -
129 -export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
130 - headers: HeadersDefaults;
131 -}
132 -
133 -export interface AxiosResponse<T = any, D = any> {
134 - data: T;
135 - status: number;
136 - statusText: string;
137 - headers: AxiosResponseHeaders;
138 - config: AxiosRequestConfig<D>;
139 - request?: any;
140 -}
141 -
142 -export class AxiosError<T = unknown, D = any> extends Error {
143 - constructor(
144 - message?: string,
145 - code?: string,
146 - config?: AxiosRequestConfig<D>,
147 - request?: any,
148 - response?: AxiosResponse<T, D>
149 - );
150 -
151 - config: AxiosRequestConfig<D>;
152 - code?: string;
153 - request?: any;
154 - response?: AxiosResponse<T, D>;
155 - isAxiosError: boolean;
156 - status?: string;
157 - toJSON: () => object;
158 - static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
159 - static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
160 - static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
161 - static readonly ERR_NETWORK = "ERR_NETWORK";
162 - static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
163 - static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
164 - static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
165 - static readonly ERR_CANCELED = "ERR_CANCELED";
166 - static readonly ECONNABORTED = "ECONNABORTED";
167 - static readonly ETIMEDOUT = "ETIMEDOUT";
168 -}
169 -
170 -export class CanceledError<T> extends AxiosError<T> {
171 -}
172 -
173 -export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
174 -}
175 -
176 -export interface CancelStatic {
177 - new (message?: string): Cancel;
178 -}
179 -
180 -export interface Cancel {
181 - message: string | undefined;
182 -}
183 -
184 -export interface Canceler {
185 - (message?: string): void;
186 -}
187 -
188 -export interface CancelTokenStatic {
189 - new (executor: (cancel: Canceler) => void): CancelToken;
190 - source(): CancelTokenSource;
191 -}
192 -
193 -export interface CancelToken {
194 - promise: Promise<Cancel>;
195 - reason?: Cancel;
196 - throwIfRequested(): void;
197 -}
198 -
199 -export interface CancelTokenSource {
200 - token: CancelToken;
201 - cancel: Canceler;
202 -}
203 -
204 -export interface AxiosInterceptorOptions {
205 - synchronous?: boolean;
206 - runWhen?: (config: AxiosRequestConfig) => boolean;
207 -}
208 -
209 -export interface AxiosInterceptorManager<V> {
210 - use<T = V>(onFulfilled?: (value: V) => T | Promise<T>, onRejected?: (error: any) => any, options?: AxiosInterceptorOptions): number;
211 - eject(id: number): void;
212 -}
213 -
214 -export class Axios {
215 - constructor(config?: AxiosRequestConfig);
216 - defaults: AxiosDefaults;
217 - interceptors: {
218 - request: AxiosInterceptorManager<AxiosRequestConfig>;
219 - response: AxiosInterceptorManager<AxiosResponse>;
220 - };
221 - getUri(config?: AxiosRequestConfig): string;
222 - request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
223 - get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
224 - delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
225 - head<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
226 - options<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
227 - post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
228 - put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
229 - patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
230 - postForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
231 - putForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
232 - patchForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
233 -}
234 -
235 -export interface AxiosInstance extends Axios {
236 - (config: AxiosRequestConfig): AxiosPromise;
237 - (url: string, config?: AxiosRequestConfig): AxiosPromise;
238 -}
239 -
240 -export interface AxiosStatic extends AxiosInstance {
241 - create(config?: AxiosRequestConfig): AxiosInstance;
242 - Cancel: CancelStatic;
243 - CancelToken: CancelTokenStatic;
244 - Axios: typeof Axios;
245 - readonly VERSION: string;
246 - isCancel(value: any): boolean;
247 - all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
248 - spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
249 - isAxiosError(payload: any): payload is AxiosError;
250 -}
251 -
252 -declare const axios: AxiosStatic;
253 -
254 -export default axios;
1 -module.exports = require('./lib/axios');
...\ No newline at end of file ...\ No newline at end of file
1 -# axios // adapters
2 -
3 -The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.
4 -
5 -## Example
6 -
7 -```js
8 -var settle = require('./../core/settle');
9 -
10 -module.exports = function myAdapter(config) {
11 - // At this point:
12 - // - config has been merged with defaults
13 - // - request transformers have already run
14 - // - request interceptors have already run
15 -
16 - // Make the request using config provided
17 - // Upon response settle the Promise
18 -
19 - return new Promise(function(resolve, reject) {
20 -
21 - var response = {
22 - data: responseData,
23 - status: request.status,
24 - statusText: request.statusText,
25 - headers: responseHeaders,
26 - config: config,
27 - request: request
28 - };
29 -
30 - settle(resolve, reject, response);
31 -
32 - // From here:
33 - // - response transformers will run
34 - // - response interceptors will run
35 - });
36 -}
37 -```
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -var settle = require('./../core/settle');
5 -var buildFullPath = require('../core/buildFullPath');
6 -var buildURL = require('./../helpers/buildURL');
7 -var http = require('http');
8 -var https = require('https');
9 -var httpFollow = require('follow-redirects').http;
10 -var httpsFollow = require('follow-redirects').https;
11 -var url = require('url');
12 -var zlib = require('zlib');
13 -var VERSION = require('./../env/data').version;
14 -var transitionalDefaults = require('../defaults/transitional');
15 -var AxiosError = require('../core/AxiosError');
16 -var CanceledError = require('../cancel/CanceledError');
17 -
18 -var isHttps = /https:?/;
19 -
20 -var supportedProtocols = [ 'http:', 'https:', 'file:' ];
21 -
22 -/**
23 - *
24 - * @param {http.ClientRequestArgs} options
25 - * @param {AxiosProxyConfig} proxy
26 - * @param {string} location
27 - */
28 -function setProxy(options, proxy, location) {
29 - options.hostname = proxy.host;
30 - options.host = proxy.host;
31 - options.port = proxy.port;
32 - options.path = location;
33 -
34 - // Basic proxy authorization
35 - if (proxy.auth) {
36 - var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
37 - options.headers['Proxy-Authorization'] = 'Basic ' + base64;
38 - }
39 -
40 - // If a proxy is used, any redirects must also pass through the proxy
41 - options.beforeRedirect = function beforeRedirect(redirection) {
42 - redirection.headers.host = redirection.host;
43 - setProxy(redirection, proxy, redirection.href);
44 - };
45 -}
46 -
47 -/*eslint consistent-return:0*/
48 -module.exports = function httpAdapter(config) {
49 - return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
50 - var onCanceled;
51 - function done() {
52 - if (config.cancelToken) {
53 - config.cancelToken.unsubscribe(onCanceled);
54 - }
55 -
56 - if (config.signal) {
57 - config.signal.removeEventListener('abort', onCanceled);
58 - }
59 - }
60 - var resolve = function resolve(value) {
61 - done();
62 - resolvePromise(value);
63 - };
64 - var rejected = false;
65 - var reject = function reject(value) {
66 - done();
67 - rejected = true;
68 - rejectPromise(value);
69 - };
70 - var data = config.data;
71 - var headers = config.headers;
72 - var headerNames = {};
73 -
74 - Object.keys(headers).forEach(function storeLowerName(name) {
75 - headerNames[name.toLowerCase()] = name;
76 - });
77 -
78 - // Set User-Agent (required by some servers)
79 - // See https://github.com/axios/axios/issues/69
80 - if ('user-agent' in headerNames) {
81 - // User-Agent is specified; handle case where no UA header is desired
82 - if (!headers[headerNames['user-agent']]) {
83 - delete headers[headerNames['user-agent']];
84 - }
85 - // Otherwise, use specified value
86 - } else {
87 - // Only set header if it hasn't been set in config
88 - headers['User-Agent'] = 'axios/' + VERSION;
89 - }
90 -
91 - // support for https://www.npmjs.com/package/form-data api
92 - if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
93 - Object.assign(headers, data.getHeaders());
94 - } else if (data && !utils.isStream(data)) {
95 - if (Buffer.isBuffer(data)) {
96 - // Nothing to do...
97 - } else if (utils.isArrayBuffer(data)) {
98 - data = Buffer.from(new Uint8Array(data));
99 - } else if (utils.isString(data)) {
100 - data = Buffer.from(data, 'utf-8');
101 - } else {
102 - return reject(new AxiosError(
103 - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
104 - AxiosError.ERR_BAD_REQUEST,
105 - config
106 - ));
107 - }
108 -
109 - if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
110 - return reject(new AxiosError(
111 - 'Request body larger than maxBodyLength limit',
112 - AxiosError.ERR_BAD_REQUEST,
113 - config
114 - ));
115 - }
116 -
117 - // Add Content-Length header if data exists
118 - if (!headerNames['content-length']) {
119 - headers['Content-Length'] = data.length;
120 - }
121 - }
122 -
123 - // HTTP basic authentication
124 - var auth = undefined;
125 - if (config.auth) {
126 - var username = config.auth.username || '';
127 - var password = config.auth.password || '';
128 - auth = username + ':' + password;
129 - }
130 -
131 - // Parse url
132 - var fullPath = buildFullPath(config.baseURL, config.url);
133 - var parsed = url.parse(fullPath);
134 - var protocol = parsed.protocol || supportedProtocols[0];
135 -
136 - if (supportedProtocols.indexOf(protocol) === -1) {
137 - return reject(new AxiosError(
138 - 'Unsupported protocol ' + protocol,
139 - AxiosError.ERR_BAD_REQUEST,
140 - config
141 - ));
142 - }
143 -
144 - if (!auth && parsed.auth) {
145 - var urlAuth = parsed.auth.split(':');
146 - var urlUsername = urlAuth[0] || '';
147 - var urlPassword = urlAuth[1] || '';
148 - auth = urlUsername + ':' + urlPassword;
149 - }
150 -
151 - if (auth && headerNames.authorization) {
152 - delete headers[headerNames.authorization];
153 - }
154 -
155 - var isHttpsRequest = isHttps.test(protocol);
156 - var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
157 -
158 - try {
159 - buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, '');
160 - } catch (err) {
161 - var customErr = new Error(err.message);
162 - customErr.config = config;
163 - customErr.url = config.url;
164 - customErr.exists = true;
165 - reject(customErr);
166 - }
167 -
168 - var options = {
169 - path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
170 - method: config.method.toUpperCase(),
171 - headers: headers,
172 - agent: agent,
173 - agents: { http: config.httpAgent, https: config.httpsAgent },
174 - auth: auth
175 - };
176 -
177 - if (config.socketPath) {
178 - options.socketPath = config.socketPath;
179 - } else {
180 - options.hostname = parsed.hostname;
181 - options.port = parsed.port;
182 - }
183 -
184 - var proxy = config.proxy;
185 - if (!proxy && proxy !== false) {
186 - var proxyEnv = protocol.slice(0, -1) + '_proxy';
187 - var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
188 - if (proxyUrl) {
189 - var parsedProxyUrl = url.parse(proxyUrl);
190 - var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;
191 - var shouldProxy = true;
192 -
193 - if (noProxyEnv) {
194 - var noProxy = noProxyEnv.split(',').map(function trim(s) {
195 - return s.trim();
196 - });
197 -
198 - shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {
199 - if (!proxyElement) {
200 - return false;
201 - }
202 - if (proxyElement === '*') {
203 - return true;
204 - }
205 - if (proxyElement[0] === '.' &&
206 - parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {
207 - return true;
208 - }
209 -
210 - return parsed.hostname === proxyElement;
211 - });
212 - }
213 -
214 - if (shouldProxy) {
215 - proxy = {
216 - host: parsedProxyUrl.hostname,
217 - port: parsedProxyUrl.port,
218 - protocol: parsedProxyUrl.protocol
219 - };
220 -
221 - if (parsedProxyUrl.auth) {
222 - var proxyUrlAuth = parsedProxyUrl.auth.split(':');
223 - proxy.auth = {
224 - username: proxyUrlAuth[0],
225 - password: proxyUrlAuth[1]
226 - };
227 - }
228 - }
229 - }
230 - }
231 -
232 - if (proxy) {
233 - options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
234 - setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
235 - }
236 -
237 - var transport;
238 - var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
239 - if (config.transport) {
240 - transport = config.transport;
241 - } else if (config.maxRedirects === 0) {
242 - transport = isHttpsProxy ? https : http;
243 - } else {
244 - if (config.maxRedirects) {
245 - options.maxRedirects = config.maxRedirects;
246 - }
247 - if (config.beforeRedirect) {
248 - options.beforeRedirect = config.beforeRedirect;
249 - }
250 - transport = isHttpsProxy ? httpsFollow : httpFollow;
251 - }
252 -
253 - if (config.maxBodyLength > -1) {
254 - options.maxBodyLength = config.maxBodyLength;
255 - }
256 -
257 - if (config.insecureHTTPParser) {
258 - options.insecureHTTPParser = config.insecureHTTPParser;
259 - }
260 -
261 - // Create the request
262 - var req = transport.request(options, function handleResponse(res) {
263 - if (req.aborted) return;
264 -
265 - // uncompress the response body transparently if required
266 - var stream = res;
267 -
268 - // return the last request in case of redirects
269 - var lastRequest = res.req || req;
270 -
271 -
272 - // if no content, is HEAD request or decompress disabled we should not decompress
273 - if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {
274 - switch (res.headers['content-encoding']) {
275 - /*eslint default-case:0*/
276 - case 'gzip':
277 - case 'compress':
278 - case 'deflate':
279 - // add the unzipper to the body stream processing pipeline
280 - stream = stream.pipe(zlib.createUnzip());
281 -
282 - // remove the content-encoding in order to not confuse downstream operations
283 - delete res.headers['content-encoding'];
284 - break;
285 - }
286 - }
287 -
288 - var response = {
289 - status: res.statusCode,
290 - statusText: res.statusMessage,
291 - headers: res.headers,
292 - config: config,
293 - request: lastRequest
294 - };
295 -
296 - if (config.responseType === 'stream') {
297 - response.data = stream;
298 - settle(resolve, reject, response);
299 - } else {
300 - var responseBuffer = [];
301 - var totalResponseBytes = 0;
302 - stream.on('data', function handleStreamData(chunk) {
303 - responseBuffer.push(chunk);
304 - totalResponseBytes += chunk.length;
305 -
306 - // make sure the content length is not over the maxContentLength if specified
307 - if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
308 - // stream.destoy() emit aborted event before calling reject() on Node.js v16
309 - rejected = true;
310 - stream.destroy();
311 - reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
312 - AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
313 - }
314 - });
315 -
316 - stream.on('aborted', function handlerStreamAborted() {
317 - if (rejected) {
318 - return;
319 - }
320 - stream.destroy();
321 - reject(new AxiosError(
322 - 'maxContentLength size of ' + config.maxContentLength + ' exceeded',
323 - AxiosError.ERR_BAD_RESPONSE,
324 - config,
325 - lastRequest
326 - ));
327 - });
328 -
329 - stream.on('error', function handleStreamError(err) {
330 - if (req.aborted) return;
331 - reject(AxiosError.from(err, null, config, lastRequest));
332 - });
333 -
334 - stream.on('end', function handleStreamEnd() {
335 - try {
336 - var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
337 - if (config.responseType !== 'arraybuffer') {
338 - responseData = responseData.toString(config.responseEncoding);
339 - if (!config.responseEncoding || config.responseEncoding === 'utf8') {
340 - responseData = utils.stripBOM(responseData);
341 - }
342 - }
343 - response.data = responseData;
344 - } catch (err) {
345 - reject(AxiosError.from(err, null, config, response.request, response));
346 - }
347 - settle(resolve, reject, response);
348 - });
349 - }
350 - });
351 -
352 - // Handle errors
353 - req.on('error', function handleRequestError(err) {
354 - // @todo remove
355 - // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
356 - reject(AxiosError.from(err, null, config, req));
357 - });
358 -
359 - // set tcp keep alive to prevent drop connection by peer
360 - req.on('socket', function handleRequestSocket(socket) {
361 - // default interval of sending ack packet is 1 minute
362 - socket.setKeepAlive(true, 1000 * 60);
363 - });
364 -
365 - // Handle request timeout
366 - if (config.timeout) {
367 - // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
368 - var timeout = parseInt(config.timeout, 10);
369 -
370 - if (isNaN(timeout)) {
371 - reject(new AxiosError(
372 - 'error trying to parse `config.timeout` to int',
373 - AxiosError.ERR_BAD_OPTION_VALUE,
374 - config,
375 - req
376 - ));
377 -
378 - return;
379 - }
380 -
381 - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
382 - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
383 - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
384 - // And then these socket which be hang up will devoring CPU little by little.
385 - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
386 - req.setTimeout(timeout, function handleRequestTimeout() {
387 - req.abort();
388 - var transitional = config.transitional || transitionalDefaults;
389 - reject(new AxiosError(
390 - 'timeout of ' + timeout + 'ms exceeded',
391 - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
392 - config,
393 - req
394 - ));
395 - });
396 - }
397 -
398 - if (config.cancelToken || config.signal) {
399 - // Handle cancellation
400 - // eslint-disable-next-line func-names
401 - onCanceled = function(cancel) {
402 - if (req.aborted) return;
403 -
404 - req.abort();
405 - reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);
406 - };
407 -
408 - config.cancelToken && config.cancelToken.subscribe(onCanceled);
409 - if (config.signal) {
410 - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
411 - }
412 - }
413 -
414 -
415 - // Send the request
416 - if (utils.isStream(data)) {
417 - data.on('error', function handleStreamError(err) {
418 - reject(AxiosError.from(err, config, null, req));
419 - }).pipe(req);
420 - } else {
421 - req.end(data);
422 - }
423 - });
424 -};
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -var settle = require('./../core/settle');
5 -var cookies = require('./../helpers/cookies');
6 -var buildURL = require('./../helpers/buildURL');
7 -var buildFullPath = require('../core/buildFullPath');
8 -var parseHeaders = require('./../helpers/parseHeaders');
9 -var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
10 -var transitionalDefaults = require('../defaults/transitional');
11 -var AxiosError = require('../core/AxiosError');
12 -var CanceledError = require('../cancel/CanceledError');
13 -var parseProtocol = require('../helpers/parseProtocol');
14 -
15 -module.exports = function xhrAdapter(config) {
16 - return new Promise(function dispatchXhrRequest(resolve, reject) {
17 - var requestData = config.data;
18 - var requestHeaders = config.headers;
19 - var responseType = config.responseType;
20 - var onCanceled;
21 - function done() {
22 - if (config.cancelToken) {
23 - config.cancelToken.unsubscribe(onCanceled);
24 - }
25 -
26 - if (config.signal) {
27 - config.signal.removeEventListener('abort', onCanceled);
28 - }
29 - }
30 -
31 - if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
32 - delete requestHeaders['Content-Type']; // Let the browser set it
33 - }
34 -
35 - var request = new XMLHttpRequest();
36 -
37 - // HTTP basic authentication
38 - if (config.auth) {
39 - var username = config.auth.username || '';
40 - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
41 - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
42 - }
43 -
44 - var fullPath = buildFullPath(config.baseURL, config.url);
45 -
46 - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
47 -
48 - // Set the request timeout in MS
49 - request.timeout = config.timeout;
50 -
51 - function onloadend() {
52 - if (!request) {
53 - return;
54 - }
55 - // Prepare the response
56 - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
57 - var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
58 - request.responseText : request.response;
59 - var response = {
60 - data: responseData,
61 - status: request.status,
62 - statusText: request.statusText,
63 - headers: responseHeaders,
64 - config: config,
65 - request: request
66 - };
67 -
68 - settle(function _resolve(value) {
69 - resolve(value);
70 - done();
71 - }, function _reject(err) {
72 - reject(err);
73 - done();
74 - }, response);
75 -
76 - // Clean up request
77 - request = null;
78 - }
79 -
80 - if ('onloadend' in request) {
81 - // Use onloadend if available
82 - request.onloadend = onloadend;
83 - } else {
84 - // Listen for ready state to emulate onloadend
85 - request.onreadystatechange = function handleLoad() {
86 - if (!request || request.readyState !== 4) {
87 - return;
88 - }
89 -
90 - // The request errored out and we didn't get a response, this will be
91 - // handled by onerror instead
92 - // With one exception: request that using file: protocol, most browsers
93 - // will return status as 0 even though it's a successful request
94 - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
95 - return;
96 - }
97 - // readystate handler is calling before onerror or ontimeout handlers,
98 - // so we should call onloadend on the next 'tick'
99 - setTimeout(onloadend);
100 - };
101 - }
102 -
103 - // Handle browser request cancellation (as opposed to a manual cancellation)
104 - request.onabort = function handleAbort() {
105 - if (!request) {
106 - return;
107 - }
108 -
109 - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
110 -
111 - // Clean up request
112 - request = null;
113 - };
114 -
115 - // Handle low level network errors
116 - request.onerror = function handleError() {
117 - // Real errors are hidden from us by the browser
118 - // onerror should only fire if it's a network error
119 - reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request));
120 -
121 - // Clean up request
122 - request = null;
123 - };
124 -
125 - // Handle timeout
126 - request.ontimeout = function handleTimeout() {
127 - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
128 - var transitional = config.transitional || transitionalDefaults;
129 - if (config.timeoutErrorMessage) {
130 - timeoutErrorMessage = config.timeoutErrorMessage;
131 - }
132 - reject(new AxiosError(
133 - timeoutErrorMessage,
134 - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
135 - config,
136 - request));
137 -
138 - // Clean up request
139 - request = null;
140 - };
141 -
142 - // Add xsrf header
143 - // This is only done if running in a standard browser environment.
144 - // Specifically not if we're in a web worker, or react-native.
145 - if (utils.isStandardBrowserEnv()) {
146 - // Add xsrf header
147 - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
148 - cookies.read(config.xsrfCookieName) :
149 - undefined;
150 -
151 - if (xsrfValue) {
152 - requestHeaders[config.xsrfHeaderName] = xsrfValue;
153 - }
154 - }
155 -
156 - // Add headers to the request
157 - if ('setRequestHeader' in request) {
158 - utils.forEach(requestHeaders, function setRequestHeader(val, key) {
159 - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
160 - // Remove Content-Type if data is undefined
161 - delete requestHeaders[key];
162 - } else {
163 - // Otherwise add header to the request
164 - request.setRequestHeader(key, val);
165 - }
166 - });
167 - }
168 -
169 - // Add withCredentials to request if needed
170 - if (!utils.isUndefined(config.withCredentials)) {
171 - request.withCredentials = !!config.withCredentials;
172 - }
173 -
174 - // Add responseType to request if needed
175 - if (responseType && responseType !== 'json') {
176 - request.responseType = config.responseType;
177 - }
178 -
179 - // Handle progress if needed
180 - if (typeof config.onDownloadProgress === 'function') {
181 - request.addEventListener('progress', config.onDownloadProgress);
182 - }
183 -
184 - // Not all browsers support upload events
185 - if (typeof config.onUploadProgress === 'function' && request.upload) {
186 - request.upload.addEventListener('progress', config.onUploadProgress);
187 - }
188 -
189 - if (config.cancelToken || config.signal) {
190 - // Handle cancellation
191 - // eslint-disable-next-line func-names
192 - onCanceled = function(cancel) {
193 - if (!request) {
194 - return;
195 - }
196 - reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);
197 - request.abort();
198 - request = null;
199 - };
200 -
201 - config.cancelToken && config.cancelToken.subscribe(onCanceled);
202 - if (config.signal) {
203 - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
204 - }
205 - }
206 -
207 - if (!requestData) {
208 - requestData = null;
209 - }
210 -
211 - var protocol = parseProtocol(fullPath);
212 -
213 - if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {
214 - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
215 - return;
216 - }
217 -
218 -
219 - // Send the request
220 - request.send(requestData);
221 - });
222 -};
1 -'use strict';
2 -
3 -var utils = require('./utils');
4 -var bind = require('./helpers/bind');
5 -var Axios = require('./core/Axios');
6 -var mergeConfig = require('./core/mergeConfig');
7 -var defaults = require('./defaults');
8 -
9 -/**
10 - * Create an instance of Axios
11 - *
12 - * @param {Object} defaultConfig The default config for the instance
13 - * @return {Axios} A new instance of Axios
14 - */
15 -function createInstance(defaultConfig) {
16 - var context = new Axios(defaultConfig);
17 - var instance = bind(Axios.prototype.request, context);
18 -
19 - // Copy axios.prototype to instance
20 - utils.extend(instance, Axios.prototype, context);
21 -
22 - // Copy context to instance
23 - utils.extend(instance, context);
24 -
25 - // Factory for creating new instances
26 - instance.create = function create(instanceConfig) {
27 - return createInstance(mergeConfig(defaultConfig, instanceConfig));
28 - };
29 -
30 - return instance;
31 -}
32 -
33 -// Create the default instance to be exported
34 -var axios = createInstance(defaults);
35 -
36 -// Expose Axios class to allow class inheritance
37 -axios.Axios = Axios;
38 -
39 -// Expose Cancel & CancelToken
40 -axios.CanceledError = require('./cancel/CanceledError');
41 -axios.CancelToken = require('./cancel/CancelToken');
42 -axios.isCancel = require('./cancel/isCancel');
43 -axios.VERSION = require('./env/data').version;
44 -axios.toFormData = require('./helpers/toFormData');
45 -
46 -// Expose AxiosError class
47 -axios.AxiosError = require('../lib/core/AxiosError');
48 -
49 -// alias for CanceledError for backward compatibility
50 -axios.Cancel = axios.CanceledError;
51 -
52 -// Expose all/spread
53 -axios.all = function all(promises) {
54 - return Promise.all(promises);
55 -};
56 -axios.spread = require('./helpers/spread');
57 -
58 -// Expose isAxiosError
59 -axios.isAxiosError = require('./helpers/isAxiosError');
60 -
61 -module.exports = axios;
62 -
63 -// Allow use of default import syntax in TypeScript
64 -module.exports.default = axios;
1 -'use strict';
2 -
3 -var CanceledError = require('./CanceledError');
4 -
5 -/**
6 - * A `CancelToken` is an object that can be used to request cancellation of an operation.
7 - *
8 - * @class
9 - * @param {Function} executor The executor function.
10 - */
11 -function CancelToken(executor) {
12 - if (typeof executor !== 'function') {
13 - throw new TypeError('executor must be a function.');
14 - }
15 -
16 - var resolvePromise;
17 -
18 - this.promise = new Promise(function promiseExecutor(resolve) {
19 - resolvePromise = resolve;
20 - });
21 -
22 - var token = this;
23 -
24 - // eslint-disable-next-line func-names
25 - this.promise.then(function(cancel) {
26 - if (!token._listeners) return;
27 -
28 - var i;
29 - var l = token._listeners.length;
30 -
31 - for (i = 0; i < l; i++) {
32 - token._listeners[i](cancel);
33 - }
34 - token._listeners = null;
35 - });
36 -
37 - // eslint-disable-next-line func-names
38 - this.promise.then = function(onfulfilled) {
39 - var _resolve;
40 - // eslint-disable-next-line func-names
41 - var promise = new Promise(function(resolve) {
42 - token.subscribe(resolve);
43 - _resolve = resolve;
44 - }).then(onfulfilled);
45 -
46 - promise.cancel = function reject() {
47 - token.unsubscribe(_resolve);
48 - };
49 -
50 - return promise;
51 - };
52 -
53 - executor(function cancel(message) {
54 - if (token.reason) {
55 - // Cancellation has already been requested
56 - return;
57 - }
58 -
59 - token.reason = new CanceledError(message);
60 - resolvePromise(token.reason);
61 - });
62 -}
63 -
64 -/**
65 - * Throws a `CanceledError` if cancellation has been requested.
66 - */
67 -CancelToken.prototype.throwIfRequested = function throwIfRequested() {
68 - if (this.reason) {
69 - throw this.reason;
70 - }
71 -};
72 -
73 -/**
74 - * Subscribe to the cancel signal
75 - */
76 -
77 -CancelToken.prototype.subscribe = function subscribe(listener) {
78 - if (this.reason) {
79 - listener(this.reason);
80 - return;
81 - }
82 -
83 - if (this._listeners) {
84 - this._listeners.push(listener);
85 - } else {
86 - this._listeners = [listener];
87 - }
88 -};
89 -
90 -/**
91 - * Unsubscribe from the cancel signal
92 - */
93 -
94 -CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
95 - if (!this._listeners) {
96 - return;
97 - }
98 - var index = this._listeners.indexOf(listener);
99 - if (index !== -1) {
100 - this._listeners.splice(index, 1);
101 - }
102 -};
103 -
104 -/**
105 - * Returns an object that contains a new `CancelToken` and a function that, when called,
106 - * cancels the `CancelToken`.
107 - */
108 -CancelToken.source = function source() {
109 - var cancel;
110 - var token = new CancelToken(function executor(c) {
111 - cancel = c;
112 - });
113 - return {
114 - token: token,
115 - cancel: cancel
116 - };
117 -};
118 -
119 -module.exports = CancelToken;
1 -'use strict';
2 -
3 -var AxiosError = require('../core/AxiosError');
4 -var utils = require('../utils');
5 -
6 -/**
7 - * A `CanceledError` is an object that is thrown when an operation is canceled.
8 - *
9 - * @class
10 - * @param {string=} message The message.
11 - */
12 -function CanceledError(message) {
13 - // eslint-disable-next-line no-eq-null,eqeqeq
14 - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED);
15 - this.name = 'CanceledError';
16 -}
17 -
18 -utils.inherits(CanceledError, AxiosError, {
19 - __CANCEL__: true
20 -});
21 -
22 -module.exports = CanceledError;
1 -'use strict';
2 -
3 -module.exports = function isCancel(value) {
4 - return !!(value && value.__CANCEL__);
5 -};
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -var buildURL = require('../helpers/buildURL');
5 -var InterceptorManager = require('./InterceptorManager');
6 -var dispatchRequest = require('./dispatchRequest');
7 -var mergeConfig = require('./mergeConfig');
8 -var buildFullPath = require('./buildFullPath');
9 -var validator = require('../helpers/validator');
10 -
11 -var validators = validator.validators;
12 -/**
13 - * Create a new instance of Axios
14 - *
15 - * @param {Object} instanceConfig The default config for the instance
16 - */
17 -function Axios(instanceConfig) {
18 - this.defaults = instanceConfig;
19 - this.interceptors = {
20 - request: new InterceptorManager(),
21 - response: new InterceptorManager()
22 - };
23 -}
24 -
25 -/**
26 - * Dispatch a request
27 - *
28 - * @param {Object} config The config specific for this request (merged with this.defaults)
29 - */
30 -Axios.prototype.request = function request(configOrUrl, config) {
31 - /*eslint no-param-reassign:0*/
32 - // Allow for axios('example/url'[, config]) a la fetch API
33 - if (typeof configOrUrl === 'string') {
34 - config = config || {};
35 - config.url = configOrUrl;
36 - } else {
37 - config = configOrUrl || {};
38 - }
39 -
40 - config = mergeConfig(this.defaults, config);
41 -
42 - // Set config.method
43 - if (config.method) {
44 - config.method = config.method.toLowerCase();
45 - } else if (this.defaults.method) {
46 - config.method = this.defaults.method.toLowerCase();
47 - } else {
48 - config.method = 'get';
49 - }
50 -
51 - var transitional = config.transitional;
52 -
53 - if (transitional !== undefined) {
54 - validator.assertOptions(transitional, {
55 - silentJSONParsing: validators.transitional(validators.boolean),
56 - forcedJSONParsing: validators.transitional(validators.boolean),
57 - clarifyTimeoutError: validators.transitional(validators.boolean)
58 - }, false);
59 - }
60 -
61 - // filter out skipped interceptors
62 - var requestInterceptorChain = [];
63 - var synchronousRequestInterceptors = true;
64 - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
65 - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
66 - return;
67 - }
68 -
69 - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
70 -
71 - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
72 - });
73 -
74 - var responseInterceptorChain = [];
75 - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
76 - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
77 - });
78 -
79 - var promise;
80 -
81 - if (!synchronousRequestInterceptors) {
82 - var chain = [dispatchRequest, undefined];
83 -
84 - Array.prototype.unshift.apply(chain, requestInterceptorChain);
85 - chain = chain.concat(responseInterceptorChain);
86 -
87 - promise = Promise.resolve(config);
88 - while (chain.length) {
89 - promise = promise.then(chain.shift(), chain.shift());
90 - }
91 -
92 - return promise;
93 - }
94 -
95 -
96 - var newConfig = config;
97 - while (requestInterceptorChain.length) {
98 - var onFulfilled = requestInterceptorChain.shift();
99 - var onRejected = requestInterceptorChain.shift();
100 - try {
101 - newConfig = onFulfilled(newConfig);
102 - } catch (error) {
103 - onRejected(error);
104 - break;
105 - }
106 - }
107 -
108 - try {
109 - promise = dispatchRequest(newConfig);
110 - } catch (error) {
111 - return Promise.reject(error);
112 - }
113 -
114 - while (responseInterceptorChain.length) {
115 - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
116 - }
117 -
118 - return promise;
119 -};
120 -
121 -Axios.prototype.getUri = function getUri(config) {
122 - config = mergeConfig(this.defaults, config);
123 - var fullPath = buildFullPath(config.baseURL, config.url);
124 - return buildURL(fullPath, config.params, config.paramsSerializer);
125 -};
126 -
127 -// Provide aliases for supported request methods
128 -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
129 - /*eslint func-names:0*/
130 - Axios.prototype[method] = function(url, config) {
131 - return this.request(mergeConfig(config || {}, {
132 - method: method,
133 - url: url,
134 - data: (config || {}).data
135 - }));
136 - };
137 -});
138 -
139 -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
140 - /*eslint func-names:0*/
141 -
142 - function generateHTTPMethod(isForm) {
143 - return function httpMethod(url, data, config) {
144 - return this.request(mergeConfig(config || {}, {
145 - method: method,
146 - headers: isForm ? {
147 - 'Content-Type': 'multipart/form-data'
148 - } : {},
149 - url: url,
150 - data: data
151 - }));
152 - };
153 - }
154 -
155 - Axios.prototype[method] = generateHTTPMethod();
156 -
157 - Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
158 -});
159 -
160 -module.exports = Axios;
1 -'use strict';
2 -
3 -var utils = require('../utils');
4 -
5 -/**
6 - * Create an Error with the specified message, config, error code, request and response.
7 - *
8 - * @param {string} message The error message.
9 - * @param {string} [code] The error code (for example, 'ECONNABORTED').
10 - * @param {Object} [config] The config.
11 - * @param {Object} [request] The request.
12 - * @param {Object} [response] The response.
13 - * @returns {Error} The created error.
14 - */
15 -function AxiosError(message, code, config, request, response) {
16 - Error.call(this);
17 - this.message = message;
18 - this.name = 'AxiosError';
19 - code && (this.code = code);
20 - config && (this.config = config);
21 - request && (this.request = request);
22 - response && (this.response = response);
23 -}
24 -
25 -utils.inherits(AxiosError, Error, {
26 - toJSON: function toJSON() {
27 - return {
28 - // Standard
29 - message: this.message,
30 - name: this.name,
31 - // Microsoft
32 - description: this.description,
33 - number: this.number,
34 - // Mozilla
35 - fileName: this.fileName,
36 - lineNumber: this.lineNumber,
37 - columnNumber: this.columnNumber,
38 - stack: this.stack,
39 - // Axios
40 - config: this.config,
41 - code: this.code,
42 - status: this.response && this.response.status ? this.response.status : null
43 - };
44 - }
45 -});
46 -
47 -var prototype = AxiosError.prototype;
48 -var descriptors = {};
49 -
50 -[
51 - 'ERR_BAD_OPTION_VALUE',
52 - 'ERR_BAD_OPTION',
53 - 'ECONNABORTED',
54 - 'ETIMEDOUT',
55 - 'ERR_NETWORK',
56 - 'ERR_FR_TOO_MANY_REDIRECTS',
57 - 'ERR_DEPRECATED',
58 - 'ERR_BAD_RESPONSE',
59 - 'ERR_BAD_REQUEST',
60 - 'ERR_CANCELED'
61 -// eslint-disable-next-line func-names
62 -].forEach(function(code) {
63 - descriptors[code] = {value: code};
64 -});
65 -
66 -Object.defineProperties(AxiosError, descriptors);
67 -Object.defineProperty(prototype, 'isAxiosError', {value: true});
68 -
69 -// eslint-disable-next-line func-names
70 -AxiosError.from = function(error, code, config, request, response, customProps) {
71 - var axiosError = Object.create(prototype);
72 -
73 - utils.toFlatObject(error, axiosError, function filter(obj) {
74 - return obj !== Error.prototype;
75 - });
76 -
77 - AxiosError.call(axiosError, error.message, code, config, request, response);
78 -
79 - axiosError.name = error.name;
80 -
81 - customProps && Object.assign(axiosError, customProps);
82 -
83 - return axiosError;
84 -};
85 -
86 -module.exports = AxiosError;
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -
5 -function InterceptorManager() {
6 - this.handlers = [];
7 -}
8 -
9 -/**
10 - * Add a new interceptor to the stack
11 - *
12 - * @param {Function} fulfilled The function to handle `then` for a `Promise`
13 - * @param {Function} rejected The function to handle `reject` for a `Promise`
14 - *
15 - * @return {Number} An ID used to remove interceptor later
16 - */
17 -InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
18 - this.handlers.push({
19 - fulfilled: fulfilled,
20 - rejected: rejected,
21 - synchronous: options ? options.synchronous : false,
22 - runWhen: options ? options.runWhen : null
23 - });
24 - return this.handlers.length - 1;
25 -};
26 -
27 -/**
28 - * Remove an interceptor from the stack
29 - *
30 - * @param {Number} id The ID that was returned by `use`
31 - */
32 -InterceptorManager.prototype.eject = function eject(id) {
33 - if (this.handlers[id]) {
34 - this.handlers[id] = null;
35 - }
36 -};
37 -
38 -/**
39 - * Iterate over all the registered interceptors
40 - *
41 - * This method is particularly useful for skipping over any
42 - * interceptors that may have become `null` calling `eject`.
43 - *
44 - * @param {Function} fn The function to call for each interceptor
45 - */
46 -InterceptorManager.prototype.forEach = function forEach(fn) {
47 - utils.forEach(this.handlers, function forEachHandler(h) {
48 - if (h !== null) {
49 - fn(h);
50 - }
51 - });
52 -};
53 -
54 -module.exports = InterceptorManager;
1 -# axios // core
2 -
3 -The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are:
4 -
5 -- Dispatching requests
6 - - Requests sent via `adapters/` (see lib/adapters/README.md)
7 -- Managing interceptors
8 -- Handling config
1 -'use strict';
2 -
3 -var isAbsoluteURL = require('../helpers/isAbsoluteURL');
4 -var combineURLs = require('../helpers/combineURLs');
5 -
6 -/**
7 - * Creates a new URL by combining the baseURL with the requestedURL,
8 - * only when the requestedURL is not already an absolute URL.
9 - * If the requestURL is absolute, this function returns the requestedURL untouched.
10 - *
11 - * @param {string} baseURL The base URL
12 - * @param {string} requestedURL Absolute or relative URL to combine
13 - * @returns {string} The combined full path
14 - */
15 -module.exports = function buildFullPath(baseURL, requestedURL) {
16 - if (baseURL && !isAbsoluteURL(requestedURL)) {
17 - return combineURLs(baseURL, requestedURL);
18 - }
19 - return requestedURL;
20 -};
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -var transformData = require('./transformData');
5 -var isCancel = require('../cancel/isCancel');
6 -var defaults = require('../defaults');
7 -var CanceledError = require('../cancel/CanceledError');
8 -
9 -/**
10 - * Throws a `CanceledError` if cancellation has been requested.
11 - */
12 -function throwIfCancellationRequested(config) {
13 - if (config.cancelToken) {
14 - config.cancelToken.throwIfRequested();
15 - }
16 -
17 - if (config.signal && config.signal.aborted) {
18 - throw new CanceledError();
19 - }
20 -}
21 -
22 -/**
23 - * Dispatch a request to the server using the configured adapter.
24 - *
25 - * @param {object} config The config that is to be used for the request
26 - * @returns {Promise} The Promise to be fulfilled
27 - */
28 -module.exports = function dispatchRequest(config) {
29 - throwIfCancellationRequested(config);
30 -
31 - // Ensure headers exist
32 - config.headers = config.headers || {};
33 -
34 - // Transform request data
35 - config.data = transformData.call(
36 - config,
37 - config.data,
38 - config.headers,
39 - config.transformRequest
40 - );
41 -
42 - // Flatten headers
43 - config.headers = utils.merge(
44 - config.headers.common || {},
45 - config.headers[config.method] || {},
46 - config.headers
47 - );
48 -
49 - utils.forEach(
50 - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
51 - function cleanHeaderConfig(method) {
52 - delete config.headers[method];
53 - }
54 - );
55 -
56 - var adapter = config.adapter || defaults.adapter;
57 -
58 - return adapter(config).then(function onAdapterResolution(response) {
59 - throwIfCancellationRequested(config);
60 -
61 - // Transform response data
62 - response.data = transformData.call(
63 - config,
64 - response.data,
65 - response.headers,
66 - config.transformResponse
67 - );
68 -
69 - return response;
70 - }, function onAdapterRejection(reason) {
71 - if (!isCancel(reason)) {
72 - throwIfCancellationRequested(config);
73 -
74 - // Transform response data
75 - if (reason && reason.response) {
76 - reason.response.data = transformData.call(
77 - config,
78 - reason.response.data,
79 - reason.response.headers,
80 - config.transformResponse
81 - );
82 - }
83 - }
84 -
85 - return Promise.reject(reason);
86 - });
87 -};
1 -'use strict';
2 -
3 -var utils = require('../utils');
4 -
5 -/**
6 - * Config-specific merge-function which creates a new config-object
7 - * by merging two configuration objects together.
8 - *
9 - * @param {Object} config1
10 - * @param {Object} config2
11 - * @returns {Object} New object resulting from merging config2 to config1
12 - */
13 -module.exports = function mergeConfig(config1, config2) {
14 - // eslint-disable-next-line no-param-reassign
15 - config2 = config2 || {};
16 - var config = {};
17 -
18 - function getMergedValue(target, source) {
19 - if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
20 - return utils.merge(target, source);
21 - } else if (utils.isPlainObject(source)) {
22 - return utils.merge({}, source);
23 - } else if (utils.isArray(source)) {
24 - return source.slice();
25 - }
26 - return source;
27 - }
28 -
29 - // eslint-disable-next-line consistent-return
30 - function mergeDeepProperties(prop) {
31 - if (!utils.isUndefined(config2[prop])) {
32 - return getMergedValue(config1[prop], config2[prop]);
33 - } else if (!utils.isUndefined(config1[prop])) {
34 - return getMergedValue(undefined, config1[prop]);
35 - }
36 - }
37 -
38 - // eslint-disable-next-line consistent-return
39 - function valueFromConfig2(prop) {
40 - if (!utils.isUndefined(config2[prop])) {
41 - return getMergedValue(undefined, config2[prop]);
42 - }
43 - }
44 -
45 - // eslint-disable-next-line consistent-return
46 - function defaultToConfig2(prop) {
47 - if (!utils.isUndefined(config2[prop])) {
48 - return getMergedValue(undefined, config2[prop]);
49 - } else if (!utils.isUndefined(config1[prop])) {
50 - return getMergedValue(undefined, config1[prop]);
51 - }
52 - }
53 -
54 - // eslint-disable-next-line consistent-return
55 - function mergeDirectKeys(prop) {
56 - if (prop in config2) {
57 - return getMergedValue(config1[prop], config2[prop]);
58 - } else if (prop in config1) {
59 - return getMergedValue(undefined, config1[prop]);
60 - }
61 - }
62 -
63 - var mergeMap = {
64 - 'url': valueFromConfig2,
65 - 'method': valueFromConfig2,
66 - 'data': valueFromConfig2,
67 - 'baseURL': defaultToConfig2,
68 - 'transformRequest': defaultToConfig2,
69 - 'transformResponse': defaultToConfig2,
70 - 'paramsSerializer': defaultToConfig2,
71 - 'timeout': defaultToConfig2,
72 - 'timeoutMessage': defaultToConfig2,
73 - 'withCredentials': defaultToConfig2,
74 - 'adapter': defaultToConfig2,
75 - 'responseType': defaultToConfig2,
76 - 'xsrfCookieName': defaultToConfig2,
77 - 'xsrfHeaderName': defaultToConfig2,
78 - 'onUploadProgress': defaultToConfig2,
79 - 'onDownloadProgress': defaultToConfig2,
80 - 'decompress': defaultToConfig2,
81 - 'maxContentLength': defaultToConfig2,
82 - 'maxBodyLength': defaultToConfig2,
83 - 'beforeRedirect': defaultToConfig2,
84 - 'transport': defaultToConfig2,
85 - 'httpAgent': defaultToConfig2,
86 - 'httpsAgent': defaultToConfig2,
87 - 'cancelToken': defaultToConfig2,
88 - 'socketPath': defaultToConfig2,
89 - 'responseEncoding': defaultToConfig2,
90 - 'validateStatus': mergeDirectKeys
91 - };
92 -
93 - utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
94 - var merge = mergeMap[prop] || mergeDeepProperties;
95 - var configValue = merge(prop);
96 - (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
97 - });
98 -
99 - return config;
100 -};
1 -'use strict';
2 -
3 -var AxiosError = require('./AxiosError');
4 -
5 -/**
6 - * Resolve or reject a Promise based on response status.
7 - *
8 - * @param {Function} resolve A function that resolves the promise.
9 - * @param {Function} reject A function that rejects the promise.
10 - * @param {object} response The response.
11 - */
12 -module.exports = function settle(resolve, reject, response) {
13 - var validateStatus = response.config.validateStatus;
14 - if (!response.status || !validateStatus || validateStatus(response.status)) {
15 - resolve(response);
16 - } else {
17 - reject(new AxiosError(
18 - 'Request failed with status code ' + response.status,
19 - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
20 - response.config,
21 - response.request,
22 - response
23 - ));
24 - }
25 -};
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -var defaults = require('../defaults');
5 -
6 -/**
7 - * Transform the data for a request or a response
8 - *
9 - * @param {Object|String} data The data to be transformed
10 - * @param {Array} headers The headers for the request or response
11 - * @param {Array|Function} fns A single function or Array of functions
12 - * @returns {*} The resulting transformed data
13 - */
14 -module.exports = function transformData(data, headers, fns) {
15 - var context = this || defaults;
16 - /*eslint no-param-reassign:0*/
17 - utils.forEach(fns, function transform(fn) {
18 - data = fn.call(context, data, headers);
19 - });
20 -
21 - return data;
22 -};
1 -// eslint-disable-next-line strict
2 -module.exports = require('form-data');
1 -'use strict';
2 -
3 -var utils = require('../utils');
4 -var normalizeHeaderName = require('../helpers/normalizeHeaderName');
5 -var AxiosError = require('../core/AxiosError');
6 -var transitionalDefaults = require('./transitional');
7 -var toFormData = require('../helpers/toFormData');
8 -
9 -var DEFAULT_CONTENT_TYPE = {
10 - 'Content-Type': 'application/x-www-form-urlencoded'
11 -};
12 -
13 -function setContentTypeIfUnset(headers, value) {
14 - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
15 - headers['Content-Type'] = value;
16 - }
17 -}
18 -
19 -function getDefaultAdapter() {
20 - var adapter;
21 - if (typeof XMLHttpRequest !== 'undefined') {
22 - // For browsers use XHR adapter
23 - adapter = require('../adapters/xhr');
24 - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
25 - // For node use HTTP adapter
26 - adapter = require('../adapters/http');
27 - }
28 - return adapter;
29 -}
30 -
31 -function stringifySafely(rawValue, parser, encoder) {
32 - if (utils.isString(rawValue)) {
33 - try {
34 - (parser || JSON.parse)(rawValue);
35 - return utils.trim(rawValue);
36 - } catch (e) {
37 - if (e.name !== 'SyntaxError') {
38 - throw e;
39 - }
40 - }
41 - }
42 -
43 - return (encoder || JSON.stringify)(rawValue);
44 -}
45 -
46 -var defaults = {
47 -
48 - transitional: transitionalDefaults,
49 -
50 - adapter: getDefaultAdapter(),
51 -
52 - transformRequest: [function transformRequest(data, headers) {
53 - normalizeHeaderName(headers, 'Accept');
54 - normalizeHeaderName(headers, 'Content-Type');
55 -
56 - if (utils.isFormData(data) ||
57 - utils.isArrayBuffer(data) ||
58 - utils.isBuffer(data) ||
59 - utils.isStream(data) ||
60 - utils.isFile(data) ||
61 - utils.isBlob(data)
62 - ) {
63 - return data;
64 - }
65 - if (utils.isArrayBufferView(data)) {
66 - return data.buffer;
67 - }
68 - if (utils.isURLSearchParams(data)) {
69 - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
70 - return data.toString();
71 - }
72 -
73 - var isObjectPayload = utils.isObject(data);
74 - var contentType = headers && headers['Content-Type'];
75 -
76 - var isFileList;
77 -
78 - if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {
79 - var _FormData = this.env && this.env.FormData;
80 - return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData());
81 - } else if (isObjectPayload || contentType === 'application/json') {
82 - setContentTypeIfUnset(headers, 'application/json');
83 - return stringifySafely(data);
84 - }
85 -
86 - return data;
87 - }],
88 -
89 - transformResponse: [function transformResponse(data) {
90 - var transitional = this.transitional || defaults.transitional;
91 - var silentJSONParsing = transitional && transitional.silentJSONParsing;
92 - var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
93 - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
94 -
95 - if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
96 - try {
97 - return JSON.parse(data);
98 - } catch (e) {
99 - if (strictJSONParsing) {
100 - if (e.name === 'SyntaxError') {
101 - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
102 - }
103 - throw e;
104 - }
105 - }
106 - }
107 -
108 - return data;
109 - }],
110 -
111 - /**
112 - * A timeout in milliseconds to abort a request. If set to 0 (default) a
113 - * timeout is not created.
114 - */
115 - timeout: 0,
116 -
117 - xsrfCookieName: 'XSRF-TOKEN',
118 - xsrfHeaderName: 'X-XSRF-TOKEN',
119 -
120 - maxContentLength: -1,
121 - maxBodyLength: -1,
122 -
123 - env: {
124 - FormData: require('./env/FormData')
125 - },
126 -
127 - validateStatus: function validateStatus(status) {
128 - return status >= 200 && status < 300;
129 - },
130 -
131 - headers: {
132 - common: {
133 - 'Accept': 'application/json, text/plain, */*'
134 - }
135 - }
136 -};
137 -
138 -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
139 - defaults.headers[method] = {};
140 -});
141 -
142 -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
143 - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
144 -});
145 -
146 -module.exports = defaults;
1 -'use strict';
2 -
3 -module.exports = {
4 - silentJSONParsing: true,
5 - forcedJSONParsing: true,
6 - clarifyTimeoutError: false
7 -};
1 -# axios // env
2 -
3 -The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually.
1 -module.exports = {
2 - "version": "0.27.2"
3 -};
...\ No newline at end of file ...\ No newline at end of file
1 -# axios // helpers
2 -
3 -The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like:
4 -
5 -- Browser polyfills
6 -- Managing cookies
7 -- Parsing HTTP headers
1 -'use strict';
2 -
3 -module.exports = function bind(fn, thisArg) {
4 - return function wrap() {
5 - var args = new Array(arguments.length);
6 - for (var i = 0; i < args.length; i++) {
7 - args[i] = arguments[i];
8 - }
9 - return fn.apply(thisArg, args);
10 - };
11 -};
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -
5 -function encode(val) {
6 - return encodeURIComponent(val).
7 - replace(/%3A/gi, ':').
8 - replace(/%24/g, '$').
9 - replace(/%2C/gi, ',').
10 - replace(/%20/g, '+').
11 - replace(/%5B/gi, '[').
12 - replace(/%5D/gi, ']');
13 -}
14 -
15 -/**
16 - * Build a URL by appending params to the end
17 - *
18 - * @param {string} url The base of the url (e.g., http://www.google.com)
19 - * @param {object} [params] The params to be appended
20 - * @returns {string} The formatted url
21 - */
22 -module.exports = function buildURL(url, params, paramsSerializer) {
23 - /*eslint no-param-reassign:0*/
24 - if (!params) {
25 - return url;
26 - }
27 -
28 - var serializedParams;
29 - if (paramsSerializer) {
30 - serializedParams = paramsSerializer(params);
31 - } else if (utils.isURLSearchParams(params)) {
32 - serializedParams = params.toString();
33 - } else {
34 - var parts = [];
35 -
36 - utils.forEach(params, function serialize(val, key) {
37 - if (val === null || typeof val === 'undefined') {
38 - return;
39 - }
40 -
41 - if (utils.isArray(val)) {
42 - key = key + '[]';
43 - } else {
44 - val = [val];
45 - }
46 -
47 - utils.forEach(val, function parseValue(v) {
48 - if (utils.isDate(v)) {
49 - v = v.toISOString();
50 - } else if (utils.isObject(v)) {
51 - v = JSON.stringify(v);
52 - }
53 - parts.push(encode(key) + '=' + encode(v));
54 - });
55 - });
56 -
57 - serializedParams = parts.join('&');
58 - }
59 -
60 - if (serializedParams) {
61 - var hashmarkIndex = url.indexOf('#');
62 - if (hashmarkIndex !== -1) {
63 - url = url.slice(0, hashmarkIndex);
64 - }
65 -
66 - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
67 - }
68 -
69 - return url;
70 -};
1 -'use strict';
2 -
3 -/**
4 - * Creates a new URL by combining the specified URLs
5 - *
6 - * @param {string} baseURL The base URL
7 - * @param {string} relativeURL The relative URL
8 - * @returns {string} The combined URL
9 - */
10 -module.exports = function combineURLs(baseURL, relativeURL) {
11 - return relativeURL
12 - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
13 - : baseURL;
14 -};
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -
5 -module.exports = (
6 - utils.isStandardBrowserEnv() ?
7 -
8 - // Standard browser envs support document.cookie
9 - (function standardBrowserEnv() {
10 - return {
11 - write: function write(name, value, expires, path, domain, secure) {
12 - var cookie = [];
13 - cookie.push(name + '=' + encodeURIComponent(value));
14 -
15 - if (utils.isNumber(expires)) {
16 - cookie.push('expires=' + new Date(expires).toGMTString());
17 - }
18 -
19 - if (utils.isString(path)) {
20 - cookie.push('path=' + path);
21 - }
22 -
23 - if (utils.isString(domain)) {
24 - cookie.push('domain=' + domain);
25 - }
26 -
27 - if (secure === true) {
28 - cookie.push('secure');
29 - }
30 -
31 - document.cookie = cookie.join('; ');
32 - },
33 -
34 - read: function read(name) {
35 - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
36 - return (match ? decodeURIComponent(match[3]) : null);
37 - },
38 -
39 - remove: function remove(name) {
40 - this.write(name, '', Date.now() - 86400000);
41 - }
42 - };
43 - })() :
44 -
45 - // Non standard browser env (web workers, react-native) lack needed support.
46 - (function nonStandardBrowserEnv() {
47 - return {
48 - write: function write() {},
49 - read: function read() { return null; },
50 - remove: function remove() {}
51 - };
52 - })()
53 -);
1 -'use strict';
2 -
3 -/*eslint no-console:0*/
4 -
5 -/**
6 - * Supply a warning to the developer that a method they are using
7 - * has been deprecated.
8 - *
9 - * @param {string} method The name of the deprecated method
10 - * @param {string} [instead] The alternate method to use if applicable
11 - * @param {string} [docs] The documentation URL to get further details
12 - */
13 -module.exports = function deprecatedMethod(method, instead, docs) {
14 - try {
15 - console.warn(
16 - 'DEPRECATED method `' + method + '`.' +
17 - (instead ? ' Use `' + instead + '` instead.' : '') +
18 - ' This method will be removed in a future release.');
19 -
20 - if (docs) {
21 - console.warn('For more information about usage see ' + docs);
22 - }
23 - } catch (e) { /* Ignore */ }
24 -};
1 -'use strict';
2 -
3 -/**
4 - * Determines whether the specified URL is absolute
5 - *
6 - * @param {string} url The URL to test
7 - * @returns {boolean} True if the specified URL is absolute, otherwise false
8 - */
9 -module.exports = function isAbsoluteURL(url) {
10 - // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
11 - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
12 - // by any combination of letters, digits, plus, period, or hyphen.
13 - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
14 -};
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -
5 -/**
6 - * Determines whether the payload is an error thrown by Axios
7 - *
8 - * @param {*} payload The value to test
9 - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
10 - */
11 -module.exports = function isAxiosError(payload) {
12 - return utils.isObject(payload) && (payload.isAxiosError === true);
13 -};
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -
5 -module.exports = (
6 - utils.isStandardBrowserEnv() ?
7 -
8 - // Standard browser envs have full support of the APIs needed to test
9 - // whether the request URL is of the same origin as current location.
10 - (function standardBrowserEnv() {
11 - var msie = /(msie|trident)/i.test(navigator.userAgent);
12 - var urlParsingNode = document.createElement('a');
13 - var originURL;
14 -
15 - /**
16 - * Parse a URL to discover it's components
17 - *
18 - * @param {String} url The URL to be parsed
19 - * @returns {Object}
20 - */
21 - function resolveURL(url) {
22 - var href = url;
23 -
24 - if (msie) {
25 - // IE needs attribute set twice to normalize properties
26 - urlParsingNode.setAttribute('href', href);
27 - href = urlParsingNode.href;
28 - }
29 -
30 - urlParsingNode.setAttribute('href', href);
31 -
32 - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
33 - return {
34 - href: urlParsingNode.href,
35 - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
36 - host: urlParsingNode.host,
37 - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
38 - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
39 - hostname: urlParsingNode.hostname,
40 - port: urlParsingNode.port,
41 - pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
42 - urlParsingNode.pathname :
43 - '/' + urlParsingNode.pathname
44 - };
45 - }
46 -
47 - originURL = resolveURL(window.location.href);
48 -
49 - /**
50 - * Determine if a URL shares the same origin as the current location
51 - *
52 - * @param {String} requestURL The URL to test
53 - * @returns {boolean} True if URL shares the same origin, otherwise false
54 - */
55 - return function isURLSameOrigin(requestURL) {
56 - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
57 - return (parsed.protocol === originURL.protocol &&
58 - parsed.host === originURL.host);
59 - };
60 - })() :
61 -
62 - // Non standard browser envs (web workers, react-native) lack needed support.
63 - (function nonStandardBrowserEnv() {
64 - return function isURLSameOrigin() {
65 - return true;
66 - };
67 - })()
68 -);
1 -'use strict';
2 -
3 -var utils = require('../utils');
4 -
5 -module.exports = function normalizeHeaderName(headers, normalizedName) {
6 - utils.forEach(headers, function processHeader(value, name) {
7 - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
8 - headers[normalizedName] = value;
9 - delete headers[name];
10 - }
11 - });
12 -};
1 -// eslint-disable-next-line strict
2 -module.exports = null;
1 -'use strict';
2 -
3 -var utils = require('./../utils');
4 -
5 -// Headers whose duplicates are ignored by node
6 -// c.f. https://nodejs.org/api/http.html#http_message_headers
7 -var ignoreDuplicateOf = [
8 - 'age', 'authorization', 'content-length', 'content-type', 'etag',
9 - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
10 - 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
11 - 'referer', 'retry-after', 'user-agent'
12 -];
13 -
14 -/**
15 - * Parse headers into an object
16 - *
17 - * ```
18 - * Date: Wed, 27 Aug 2014 08:58:49 GMT
19 - * Content-Type: application/json
20 - * Connection: keep-alive
21 - * Transfer-Encoding: chunked
22 - * ```
23 - *
24 - * @param {String} headers Headers needing to be parsed
25 - * @returns {Object} Headers parsed into an object
26 - */
27 -module.exports = function parseHeaders(headers) {
28 - var parsed = {};
29 - var key;
30 - var val;
31 - var i;
32 -
33 - if (!headers) { return parsed; }
34 -
35 - utils.forEach(headers.split('\n'), function parser(line) {
36 - i = line.indexOf(':');
37 - key = utils.trim(line.substr(0, i)).toLowerCase();
38 - val = utils.trim(line.substr(i + 1));
39 -
40 - if (key) {
41 - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
42 - return;
43 - }
44 - if (key === 'set-cookie') {
45 - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
46 - } else {
47 - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
48 - }
49 - }
50 - });
51 -
52 - return parsed;
53 -};
1 -'use strict';
2 -
3 -module.exports = function parseProtocol(url) {
4 - var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
5 - return match && match[1] || '';
6 -};
1 -'use strict';
2 -
3 -/**
4 - * Syntactic sugar for invoking a function and expanding an array for arguments.
5 - *
6 - * Common use case would be to use `Function.prototype.apply`.
7 - *
8 - * ```js
9 - * function f(x, y, z) {}
10 - * var args = [1, 2, 3];
11 - * f.apply(null, args);
12 - * ```
13 - *
14 - * With `spread` this example can be re-written.
15 - *
16 - * ```js
17 - * spread(function(x, y, z) {})([1, 2, 3]);
18 - * ```
19 - *
20 - * @param {Function} callback
21 - * @returns {Function}
22 - */
23 -module.exports = function spread(callback) {
24 - return function wrap(arr) {
25 - return callback.apply(null, arr);
26 - };
27 -};
1 -'use strict';
2 -
3 -var utils = require('../utils');
4 -
5 -/**
6 - * Convert a data object to FormData
7 - * @param {Object} obj
8 - * @param {?Object} [formData]
9 - * @returns {Object}
10 - **/
11 -
12 -function toFormData(obj, formData) {
13 - // eslint-disable-next-line no-param-reassign
14 - formData = formData || new FormData();
15 -
16 - var stack = [];
17 -
18 - function convertValue(value) {
19 - if (value === null) return '';
20 -
21 - if (utils.isDate(value)) {
22 - return value.toISOString();
23 - }
24 -
25 - if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
26 - return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
27 - }
28 -
29 - return value;
30 - }
31 -
32 - function build(data, parentKey) {
33 - if (utils.isPlainObject(data) || utils.isArray(data)) {
34 - if (stack.indexOf(data) !== -1) {
35 - throw Error('Circular reference detected in ' + parentKey);
36 - }
37 -
38 - stack.push(data);
39 -
40 - utils.forEach(data, function each(value, key) {
41 - if (utils.isUndefined(value)) return;
42 - var fullKey = parentKey ? parentKey + '.' + key : key;
43 - var arr;
44 -
45 - if (value && !parentKey && typeof value === 'object') {
46 - if (utils.endsWith(key, '{}')) {
47 - // eslint-disable-next-line no-param-reassign
48 - value = JSON.stringify(value);
49 - } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {
50 - // eslint-disable-next-line func-names
51 - arr.forEach(function(el) {
52 - !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));
53 - });
54 - return;
55 - }
56 - }
57 -
58 - build(value, fullKey);
59 - });
60 -
61 - stack.pop();
62 - } else {
63 - formData.append(parentKey, convertValue(data));
64 - }
65 - }
66 -
67 - build(obj);
68 -
69 - return formData;
70 -}
71 -
72 -module.exports = toFormData;
1 -'use strict';
2 -
3 -var VERSION = require('../env/data').version;
4 -var AxiosError = require('../core/AxiosError');
5 -
6 -var validators = {};
7 -
8 -// eslint-disable-next-line func-names
9 -['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
10 - validators[type] = function validator(thing) {
11 - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
12 - };
13 -});
14 -
15 -var deprecatedWarnings = {};
16 -
17 -/**
18 - * Transitional option validator
19 - * @param {function|boolean?} validator - set to false if the transitional option has been removed
20 - * @param {string?} version - deprecated version / removed since version
21 - * @param {string?} message - some message with additional info
22 - * @returns {function}
23 - */
24 -validators.transitional = function transitional(validator, version, message) {
25 - function formatMessage(opt, desc) {
26 - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
27 - }
28 -
29 - // eslint-disable-next-line func-names
30 - return function(value, opt, opts) {
31 - if (validator === false) {
32 - throw new AxiosError(
33 - formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
34 - AxiosError.ERR_DEPRECATED
35 - );
36 - }
37 -
38 - if (version && !deprecatedWarnings[opt]) {
39 - deprecatedWarnings[opt] = true;
40 - // eslint-disable-next-line no-console
41 - console.warn(
42 - formatMessage(
43 - opt,
44 - ' has been deprecated since v' + version + ' and will be removed in the near future'
45 - )
46 - );
47 - }
48 -
49 - return validator ? validator(value, opt, opts) : true;
50 - };
51 -};
52 -
53 -/**
54 - * Assert object's properties type
55 - * @param {object} options
56 - * @param {object} schema
57 - * @param {boolean?} allowUnknown
58 - */
59 -
60 -function assertOptions(options, schema, allowUnknown) {
61 - if (typeof options !== 'object') {
62 - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
63 - }
64 - var keys = Object.keys(options);
65 - var i = keys.length;
66 - while (i-- > 0) {
67 - var opt = keys[i];
68 - var validator = schema[opt];
69 - if (validator) {
70 - var value = options[opt];
71 - var result = value === undefined || validator(value, opt, options);
72 - if (result !== true) {
73 - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
74 - }
75 - continue;
76 - }
77 - if (allowUnknown !== true) {
78 - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
79 - }
80 - }
81 -}
82 -
83 -module.exports = {
84 - assertOptions: assertOptions,
85 - validators: validators
86 -};
1 -'use strict';
2 -
3 -var bind = require('./helpers/bind');
4 -
5 -// utils is a library of generic helper functions non-specific to axios
6 -
7 -var toString = Object.prototype.toString;
8 -
9 -// eslint-disable-next-line func-names
10 -var kindOf = (function(cache) {
11 - // eslint-disable-next-line func-names
12 - return function(thing) {
13 - var str = toString.call(thing);
14 - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
15 - };
16 -})(Object.create(null));
17 -
18 -function kindOfTest(type) {
19 - type = type.toLowerCase();
20 - return function isKindOf(thing) {
21 - return kindOf(thing) === type;
22 - };
23 -}
24 -
25 -/**
26 - * Determine if a value is an Array
27 - *
28 - * @param {Object} val The value to test
29 - * @returns {boolean} True if value is an Array, otherwise false
30 - */
31 -function isArray(val) {
32 - return Array.isArray(val);
33 -}
34 -
35 -/**
36 - * Determine if a value is undefined
37 - *
38 - * @param {Object} val The value to test
39 - * @returns {boolean} True if the value is undefined, otherwise false
40 - */
41 -function isUndefined(val) {
42 - return typeof val === 'undefined';
43 -}
44 -
45 -/**
46 - * Determine if a value is a Buffer
47 - *
48 - * @param {Object} val The value to test
49 - * @returns {boolean} True if value is a Buffer, otherwise false
50 - */
51 -function isBuffer(val) {
52 - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
53 - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
54 -}
55 -
56 -/**
57 - * Determine if a value is an ArrayBuffer
58 - *
59 - * @function
60 - * @param {Object} val The value to test
61 - * @returns {boolean} True if value is an ArrayBuffer, otherwise false
62 - */
63 -var isArrayBuffer = kindOfTest('ArrayBuffer');
64 -
65 -
66 -/**
67 - * Determine if a value is a view on an ArrayBuffer
68 - *
69 - * @param {Object} val The value to test
70 - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
71 - */
72 -function isArrayBufferView(val) {
73 - var result;
74 - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
75 - result = ArrayBuffer.isView(val);
76 - } else {
77 - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
78 - }
79 - return result;
80 -}
81 -
82 -/**
83 - * Determine if a value is a String
84 - *
85 - * @param {Object} val The value to test
86 - * @returns {boolean} True if value is a String, otherwise false
87 - */
88 -function isString(val) {
89 - return typeof val === 'string';
90 -}
91 -
92 -/**
93 - * Determine if a value is a Number
94 - *
95 - * @param {Object} val The value to test
96 - * @returns {boolean} True if value is a Number, otherwise false
97 - */
98 -function isNumber(val) {
99 - return typeof val === 'number';
100 -}
101 -
102 -/**
103 - * Determine if a value is an Object
104 - *
105 - * @param {Object} val The value to test
106 - * @returns {boolean} True if value is an Object, otherwise false
107 - */
108 -function isObject(val) {
109 - return val !== null && typeof val === 'object';
110 -}
111 -
112 -/**
113 - * Determine if a value is a plain Object
114 - *
115 - * @param {Object} val The value to test
116 - * @return {boolean} True if value is a plain Object, otherwise false
117 - */
118 -function isPlainObject(val) {
119 - if (kindOf(val) !== 'object') {
120 - return false;
121 - }
122 -
123 - var prototype = Object.getPrototypeOf(val);
124 - return prototype === null || prototype === Object.prototype;
125 -}
126 -
127 -/**
128 - * Determine if a value is a Date
129 - *
130 - * @function
131 - * @param {Object} val The value to test
132 - * @returns {boolean} True if value is a Date, otherwise false
133 - */
134 -var isDate = kindOfTest('Date');
135 -
136 -/**
137 - * Determine if a value is a File
138 - *
139 - * @function
140 - * @param {Object} val The value to test
141 - * @returns {boolean} True if value is a File, otherwise false
142 - */
143 -var isFile = kindOfTest('File');
144 -
145 -/**
146 - * Determine if a value is a Blob
147 - *
148 - * @function
149 - * @param {Object} val The value to test
150 - * @returns {boolean} True if value is a Blob, otherwise false
151 - */
152 -var isBlob = kindOfTest('Blob');
153 -
154 -/**
155 - * Determine if a value is a FileList
156 - *
157 - * @function
158 - * @param {Object} val The value to test
159 - * @returns {boolean} True if value is a File, otherwise false
160 - */
161 -var isFileList = kindOfTest('FileList');
162 -
163 -/**
164 - * Determine if a value is a Function
165 - *
166 - * @param {Object} val The value to test
167 - * @returns {boolean} True if value is a Function, otherwise false
168 - */
169 -function isFunction(val) {
170 - return toString.call(val) === '[object Function]';
171 -}
172 -
173 -/**
174 - * Determine if a value is a Stream
175 - *
176 - * @param {Object} val The value to test
177 - * @returns {boolean} True if value is a Stream, otherwise false
178 - */
179 -function isStream(val) {
180 - return isObject(val) && isFunction(val.pipe);
181 -}
182 -
183 -/**
184 - * Determine if a value is a FormData
185 - *
186 - * @param {Object} thing The value to test
187 - * @returns {boolean} True if value is an FormData, otherwise false
188 - */
189 -function isFormData(thing) {
190 - var pattern = '[object FormData]';
191 - return thing && (
192 - (typeof FormData === 'function' && thing instanceof FormData) ||
193 - toString.call(thing) === pattern ||
194 - (isFunction(thing.toString) && thing.toString() === pattern)
195 - );
196 -}
197 -
198 -/**
199 - * Determine if a value is a URLSearchParams object
200 - * @function
201 - * @param {Object} val The value to test
202 - * @returns {boolean} True if value is a URLSearchParams object, otherwise false
203 - */
204 -var isURLSearchParams = kindOfTest('URLSearchParams');
205 -
206 -/**
207 - * Trim excess whitespace off the beginning and end of a string
208 - *
209 - * @param {String} str The String to trim
210 - * @returns {String} The String freed of excess whitespace
211 - */
212 -function trim(str) {
213 - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
214 -}
215 -
216 -/**
217 - * Determine if we're running in a standard browser environment
218 - *
219 - * This allows axios to run in a web worker, and react-native.
220 - * Both environments support XMLHttpRequest, but not fully standard globals.
221 - *
222 - * web workers:
223 - * typeof window -> undefined
224 - * typeof document -> undefined
225 - *
226 - * react-native:
227 - * navigator.product -> 'ReactNative'
228 - * nativescript
229 - * navigator.product -> 'NativeScript' or 'NS'
230 - */
231 -function isStandardBrowserEnv() {
232 - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
233 - navigator.product === 'NativeScript' ||
234 - navigator.product === 'NS')) {
235 - return false;
236 - }
237 - return (
238 - typeof window !== 'undefined' &&
239 - typeof document !== 'undefined'
240 - );
241 -}
242 -
243 -/**
244 - * Iterate over an Array or an Object invoking a function for each item.
245 - *
246 - * If `obj` is an Array callback will be called passing
247 - * the value, index, and complete array for each item.
248 - *
249 - * If 'obj' is an Object callback will be called passing
250 - * the value, key, and complete object for each property.
251 - *
252 - * @param {Object|Array} obj The object to iterate
253 - * @param {Function} fn The callback to invoke for each item
254 - */
255 -function forEach(obj, fn) {
256 - // Don't bother if no value provided
257 - if (obj === null || typeof obj === 'undefined') {
258 - return;
259 - }
260 -
261 - // Force an array if not already something iterable
262 - if (typeof obj !== 'object') {
263 - /*eslint no-param-reassign:0*/
264 - obj = [obj];
265 - }
266 -
267 - if (isArray(obj)) {
268 - // Iterate over array values
269 - for (var i = 0, l = obj.length; i < l; i++) {
270 - fn.call(null, obj[i], i, obj);
271 - }
272 - } else {
273 - // Iterate over object keys
274 - for (var key in obj) {
275 - if (Object.prototype.hasOwnProperty.call(obj, key)) {
276 - fn.call(null, obj[key], key, obj);
277 - }
278 - }
279 - }
280 -}
281 -
282 -/**
283 - * Accepts varargs expecting each argument to be an object, then
284 - * immutably merges the properties of each object and returns result.
285 - *
286 - * When multiple objects contain the same key the later object in
287 - * the arguments list will take precedence.
288 - *
289 - * Example:
290 - *
291 - * ```js
292 - * var result = merge({foo: 123}, {foo: 456});
293 - * console.log(result.foo); // outputs 456
294 - * ```
295 - *
296 - * @param {Object} obj1 Object to merge
297 - * @returns {Object} Result of all merge properties
298 - */
299 -function merge(/* obj1, obj2, obj3, ... */) {
300 - var result = {};
301 - function assignValue(val, key) {
302 - if (isPlainObject(result[key]) && isPlainObject(val)) {
303 - result[key] = merge(result[key], val);
304 - } else if (isPlainObject(val)) {
305 - result[key] = merge({}, val);
306 - } else if (isArray(val)) {
307 - result[key] = val.slice();
308 - } else {
309 - result[key] = val;
310 - }
311 - }
312 -
313 - for (var i = 0, l = arguments.length; i < l; i++) {
314 - forEach(arguments[i], assignValue);
315 - }
316 - return result;
317 -}
318 -
319 -/**
320 - * Extends object a by mutably adding to it the properties of object b.
321 - *
322 - * @param {Object} a The object to be extended
323 - * @param {Object} b The object to copy properties from
324 - * @param {Object} thisArg The object to bind function to
325 - * @return {Object} The resulting value of object a
326 - */
327 -function extend(a, b, thisArg) {
328 - forEach(b, function assignValue(val, key) {
329 - if (thisArg && typeof val === 'function') {
330 - a[key] = bind(val, thisArg);
331 - } else {
332 - a[key] = val;
333 - }
334 - });
335 - return a;
336 -}
337 -
338 -/**
339 - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
340 - *
341 - * @param {string} content with BOM
342 - * @return {string} content value without BOM
343 - */
344 -function stripBOM(content) {
345 - if (content.charCodeAt(0) === 0xFEFF) {
346 - content = content.slice(1);
347 - }
348 - return content;
349 -}
350 -
351 -/**
352 - * Inherit the prototype methods from one constructor into another
353 - * @param {function} constructor
354 - * @param {function} superConstructor
355 - * @param {object} [props]
356 - * @param {object} [descriptors]
357 - */
358 -
359 -function inherits(constructor, superConstructor, props, descriptors) {
360 - constructor.prototype = Object.create(superConstructor.prototype, descriptors);
361 - constructor.prototype.constructor = constructor;
362 - props && Object.assign(constructor.prototype, props);
363 -}
364 -
365 -/**
366 - * Resolve object with deep prototype chain to a flat object
367 - * @param {Object} sourceObj source object
368 - * @param {Object} [destObj]
369 - * @param {Function} [filter]
370 - * @returns {Object}
371 - */
372 -
373 -function toFlatObject(sourceObj, destObj, filter) {
374 - var props;
375 - var i;
376 - var prop;
377 - var merged = {};
378 -
379 - destObj = destObj || {};
380 -
381 - do {
382 - props = Object.getOwnPropertyNames(sourceObj);
383 - i = props.length;
384 - while (i-- > 0) {
385 - prop = props[i];
386 - if (!merged[prop]) {
387 - destObj[prop] = sourceObj[prop];
388 - merged[prop] = true;
389 - }
390 - }
391 - sourceObj = Object.getPrototypeOf(sourceObj);
392 - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
393 -
394 - return destObj;
395 -}
396 -
397 -/*
398 - * determines whether a string ends with the characters of a specified string
399 - * @param {String} str
400 - * @param {String} searchString
401 - * @param {Number} [position= 0]
402 - * @returns {boolean}
403 - */
404 -function endsWith(str, searchString, position) {
405 - str = String(str);
406 - if (position === undefined || position > str.length) {
407 - position = str.length;
408 - }
409 - position -= searchString.length;
410 - var lastIndex = str.indexOf(searchString, position);
411 - return lastIndex !== -1 && lastIndex === position;
412 -}
413 -
414 -
415 -/**
416 - * Returns new array from array like object
417 - * @param {*} [thing]
418 - * @returns {Array}
419 - */
420 -function toArray(thing) {
421 - if (!thing) return null;
422 - var i = thing.length;
423 - if (isUndefined(i)) return null;
424 - var arr = new Array(i);
425 - while (i-- > 0) {
426 - arr[i] = thing[i];
427 - }
428 - return arr;
429 -}
430 -
431 -// eslint-disable-next-line func-names
432 -var isTypedArray = (function(TypedArray) {
433 - // eslint-disable-next-line func-names
434 - return function(thing) {
435 - return TypedArray && thing instanceof TypedArray;
436 - };
437 -})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
438 -
439 -module.exports = {
440 - isArray: isArray,
441 - isArrayBuffer: isArrayBuffer,
442 - isBuffer: isBuffer,
443 - isFormData: isFormData,
444 - isArrayBufferView: isArrayBufferView,
445 - isString: isString,
446 - isNumber: isNumber,
447 - isObject: isObject,
448 - isPlainObject: isPlainObject,
449 - isUndefined: isUndefined,
450 - isDate: isDate,
451 - isFile: isFile,
452 - isBlob: isBlob,
453 - isFunction: isFunction,
454 - isStream: isStream,
455 - isURLSearchParams: isURLSearchParams,
456 - isStandardBrowserEnv: isStandardBrowserEnv,
457 - forEach: forEach,
458 - merge: merge,
459 - extend: extend,
460 - trim: trim,
461 - stripBOM: stripBOM,
462 - inherits: inherits,
463 - toFlatObject: toFlatObject,
464 - kindOf: kindOf,
465 - kindOfTest: kindOfTest,
466 - endsWith: endsWith,
467 - toArray: toArray,
468 - isTypedArray: isTypedArray,
469 - isFileList: isFileList
470 -};
1 -{
2 - "name": "axios",
3 - "version": "0.27.2",
4 - "description": "Promise based HTTP client for the browser and node.js",
5 - "main": "index.js",
6 - "types": "index.d.ts",
7 - "scripts": {
8 - "test": "grunt test && dtslint",
9 - "start": "node ./sandbox/server.js",
10 - "preversion": "grunt version && npm test",
11 - "build": "NODE_ENV=production grunt build",
12 - "examples": "node ./examples/server.js",
13 - "coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
14 - "fix": "eslint --fix lib/**/*.js"
15 - },
16 - "repository": {
17 - "type": "git",
18 - "url": "https://github.com/axios/axios.git"
19 - },
20 - "keywords": [
21 - "xhr",
22 - "http",
23 - "ajax",
24 - "promise",
25 - "node"
26 - ],
27 - "author": "Matt Zabriskie",
28 - "license": "MIT",
29 - "bugs": {
30 - "url": "https://github.com/axios/axios/issues"
31 - },
32 - "homepage": "https://axios-http.com",
33 - "devDependencies": {
34 - "abortcontroller-polyfill": "^1.7.3",
35 - "coveralls": "^3.1.1",
36 - "dtslint": "^4.2.1",
37 - "es6-promise": "^4.2.8",
38 - "formidable": "^2.0.1",
39 - "grunt": "^1.4.1",
40 - "grunt-banner": "^0.6.0",
41 - "grunt-cli": "^1.4.3",
42 - "grunt-contrib-clean": "^2.0.0",
43 - "grunt-contrib-watch": "^1.1.0",
44 - "grunt-eslint": "^24.0.0",
45 - "grunt-karma": "^4.0.2",
46 - "grunt-mocha-test": "^0.13.3",
47 - "grunt-webpack": "^5.0.0",
48 - "istanbul-instrumenter-loader": "^3.0.1",
49 - "jasmine-core": "^2.4.1",
50 - "karma": "^6.3.17",
51 - "karma-chrome-launcher": "^3.1.1",
52 - "karma-firefox-launcher": "^2.1.2",
53 - "karma-jasmine": "^1.1.1",
54 - "karma-jasmine-ajax": "^0.1.13",
55 - "karma-safari-launcher": "^1.0.0",
56 - "karma-sauce-launcher": "^4.3.6",
57 - "karma-sinon": "^1.0.5",
58 - "karma-sourcemap-loader": "^0.3.8",
59 - "karma-webpack": "^4.0.2",
60 - "load-grunt-tasks": "^5.1.0",
61 - "minimist": "^1.2.6",
62 - "mocha": "^8.2.1",
63 - "sinon": "^4.5.0",
64 - "terser-webpack-plugin": "^4.2.3",
65 - "typescript": "^4.6.3",
66 - "url-search-params": "^0.10.0",
67 - "webpack": "^4.44.2",
68 - "webpack-dev-server": "^3.11.0"
69 - },
70 - "browser": {
71 - "./lib/adapters/http.js": "./lib/adapters/xhr.js",
72 - "./lib/defaults/env/FormData.js": "./lib/helpers/null.js"
73 - },
74 - "jsdelivr": "dist/axios.min.js",
75 - "unpkg": "dist/axios.min.js",
76 - "typings": "./index.d.ts",
77 - "dependencies": {
78 - "follow-redirects": "^1.14.9",
79 - "form-data": "^4.0.0"
80 - },
81 - "bundlesize": [
82 - {
83 - "path": "./dist/axios.min.js",
84 - "threshold": "5kB"
85 - }
86 - ]
87 -}
1 -{
2 - "compilerOptions": {
3 - "module": "es2015",
4 - "lib": ["dom", "es2015"],
5 - "types": [],
6 - "moduleResolution": "node",
7 - "strict": true,
8 - "noEmit": true,
9 - "baseUrl": ".",
10 - "paths": {
11 - "axios": ["."]
12 - }
13 - }
14 -}
1 -{
2 - "extends": "dtslint/dtslint.json",
3 - "rules": {
4 - "no-unnecessary-generics": false
5 - }
6 -}
1 +data-uri-to-buffer
2 +==================
3 +### Generate a Buffer instance from a [Data URI][rfc] string
4 +[![Build Status](https://travis-ci.org/TooTallNate/node-data-uri-to-buffer.svg?branch=master)](https://travis-ci.org/TooTallNate/node-data-uri-to-buffer)
5 +
6 +This module accepts a ["data" URI][rfc] String of data, and returns a
7 +node.js `Buffer` instance with the decoded data.
8 +
9 +
10 +Installation
11 +------------
12 +
13 +Install with `npm`:
14 +
15 +``` bash
16 +$ npm install data-uri-to-buffer
17 +```
18 +
19 +
20 +Example
21 +-------
22 +
23 +``` js
24 +var dataUriToBuffer = require('data-uri-to-buffer');
25 +
26 +// plain-text data is supported
27 +var uri = 'data:,Hello%2C%20World!';
28 +var decoded = dataUriToBuffer(uri);
29 +console.log(decoded.toString());
30 +// 'Hello, World!'
31 +
32 +// base64-encoded data is supported
33 +uri = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D';
34 +decoded = dataUriToBuffer(uri);
35 +console.log(decoded.toString());
36 +// 'Hello, World!'
37 +```
38 +
39 +
40 +API
41 +---
42 +
43 +### dataUriToBuffer(String uri) → Buffer
44 +
45 +The `type` property on the Buffer instance gets set to the main type portion of
46 +the "mediatype" portion of the "data" URI, or defaults to `"text/plain"` if not
47 +specified.
48 +
49 +The `typeFull` property on the Buffer instance gets set to the entire
50 +"mediatype" portion of the "data" URI (including all parameters), or defaults
51 +to `"text/plain;charset=US-ASCII"` if not specified.
52 +
53 +The `charset` property on the Buffer instance gets set to the Charset portion of
54 +the "mediatype" portion of the "data" URI, or defaults to `"US-ASCII"` if the
55 +entire type is not specified, or defaults to `""` otherwise.
56 +
57 +*Note*: If the only the main type is specified but not the charset, e.g.
58 +`"data:text/plain,abc"`, the charset is set to the empty string. The spec only
59 +defaults to US-ASCII as charset if the entire type is not specified.
60 +
61 +
62 +License
63 +-------
64 +
65 +(The MIT License)
66 +
67 +Copyright (c) 2014 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
68 +
69 +Permission is hereby granted, free of charge, to any person obtaining
70 +a copy of this software and associated documentation files (the
71 +'Software'), to deal in the Software without restriction, including
72 +without limitation the rights to use, copy, modify, merge, publish,
73 +distribute, sublicense, and/or sell copies of the Software, and to
74 +permit persons to whom the Software is furnished to do so, subject to
75 +the following conditions:
76 +
77 +The above copyright notice and this permission notice shall be
78 +included in all copies or substantial portions of the Software.
79 +
80 +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
81 +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
82 +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
83 +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
84 +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
85 +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
86 +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
87 +
88 +[rfc]: http://tools.ietf.org/html/rfc2397
1 +/// <reference types="node" />
2 +export interface MimeBuffer extends Buffer {
3 + type: string;
4 + typeFull: string;
5 + charset: string;
6 +}
7 +/**
8 + * Returns a `Buffer` instance from the given data URI `uri`.
9 + *
10 + * @param {String} uri Data URI to turn into a Buffer instance
11 + * @returns {Buffer} Buffer instance from Data URI
12 + * @api public
13 + */
14 +export declare function dataUriToBuffer(uri: string): MimeBuffer;
15 +export default dataUriToBuffer;
1 +/**
2 + * Returns a `Buffer` instance from the given data URI `uri`.
3 + *
4 + * @param {String} uri Data URI to turn into a Buffer instance
5 + * @returns {Buffer} Buffer instance from Data URI
6 + * @api public
7 + */
8 +export function dataUriToBuffer(uri) {
9 + if (!/^data:/i.test(uri)) {
10 + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
11 + }
12 + // strip newlines
13 + uri = uri.replace(/\r?\n/g, '');
14 + // split the URI up into the "metadata" and the "data" portions
15 + const firstComma = uri.indexOf(',');
16 + if (firstComma === -1 || firstComma <= 4) {
17 + throw new TypeError('malformed data: URI');
18 + }
19 + // remove the "data:" scheme and parse the metadata
20 + const meta = uri.substring(5, firstComma).split(';');
21 + let charset = '';
22 + let base64 = false;
23 + const type = meta[0] || 'text/plain';
24 + let typeFull = type;
25 + for (let i = 1; i < meta.length; i++) {
26 + if (meta[i] === 'base64') {
27 + base64 = true;
28 + }
29 + else {
30 + typeFull += `;${meta[i]}`;
31 + if (meta[i].indexOf('charset=') === 0) {
32 + charset = meta[i].substring(8);
33 + }
34 + }
35 + }
36 + // defaults to US-ASCII only if type is not provided
37 + if (!meta[0] && !charset.length) {
38 + typeFull += ';charset=US-ASCII';
39 + charset = 'US-ASCII';
40 + }
41 + // get the encoded data portion and decode URI-encoded chars
42 + const encoding = base64 ? 'base64' : 'ascii';
43 + const data = unescape(uri.substring(firstComma + 1));
44 + const buffer = Buffer.from(data, encoding);
45 + // set `.type` and `.typeFull` properties to MIME type
46 + buffer.type = type;
47 + buffer.typeFull = typeFull;
48 + // set the `.charset` property
49 + buffer.charset = charset;
50 + return buffer;
51 +}
52 +export default dataUriToBuffer;
53 +//# sourceMappingURL=index.js.map
...\ No newline at end of file ...\ No newline at end of file
1 +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,GAAW;IAC1C,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QACzB,MAAM,IAAI,SAAS,CAClB,kEAAkE,CAClE,CAAC;KACF;IAED,iBAAiB;IACjB,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAEhC,+DAA+D;IAC/D,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,IAAI,UAAU,KAAK,CAAC,CAAC,IAAI,UAAU,IAAI,CAAC,EAAE;QACzC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;KAC3C;IAED,mDAAmD;IACnD,MAAM,IAAI,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAErD,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC;IACrC,IAAI,QAAQ,GAAG,IAAI,CAAC;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE;YACzB,MAAM,GAAG,IAAI,CAAC;SACd;aAAM;YACN,QAAQ,IAAI,IAAM,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5B,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE;gBACtC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;aAC/B;SACD;KACD;IACD,oDAAoD;IACpD,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;QAChC,QAAQ,IAAI,mBAAmB,CAAC;QAChC,OAAO,GAAG,UAAU,CAAC;KACrB;IAED,4DAA4D;IAC5D,MAAM,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7C,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;IACrD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAe,CAAC;IAEzD,sDAAsD;IACtD,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAE3B,8BAA8B;IAC9B,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;IAEzB,OAAO,MAAM,CAAC;AACf,CAAC;AAED,eAAe,eAAe,CAAC"}
...\ No newline at end of file ...\ No newline at end of file
1 +/// <reference types="node" />
2 +export interface MimeBuffer extends Buffer {
3 + type: string;
4 + typeFull: string;
5 + charset: string;
6 +}
7 +/**
8 + * Returns a `Buffer` instance from the given data URI `uri`.
9 + *
10 + * @param {String} uri Data URI to turn into a Buffer instance
11 + * @returns {Buffer} Buffer instance from Data URI
12 + * @api public
13 + */
14 +export declare function dataUriToBuffer(uri: string): MimeBuffer;
15 +export default dataUriToBuffer;
1 +/**
2 + * Returns a `Buffer` instance from the given data URI `uri`.
3 + *
4 + * @param {String} uri Data URI to turn into a Buffer instance
5 + * @returns {Buffer} Buffer instance from Data URI
6 + * @api public
7 + */
8 +export function dataUriToBuffer(uri) {
9 + if (!/^data:/i.test(uri)) {
10 + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
11 + }
12 + // strip newlines
13 + uri = uri.replace(/\r?\n/g, '');
14 + // split the URI up into the "metadata" and the "data" portions
15 + const firstComma = uri.indexOf(',');
16 + if (firstComma === -1 || firstComma <= 4) {
17 + throw new TypeError('malformed data: URI');
18 + }
19 + // remove the "data:" scheme and parse the metadata
20 + const meta = uri.substring(5, firstComma).split(';');
21 + let charset = '';
22 + let base64 = false;
23 + const type = meta[0] || 'text/plain';
24 + let typeFull = type;
25 + for (let i = 1; i < meta.length; i++) {
26 + if (meta[i] === 'base64') {
27 + base64 = true;
28 + }
29 + else {
30 + typeFull += `;${meta[i]}`;
31 + if (meta[i].indexOf('charset=') === 0) {
32 + charset = meta[i].substring(8);
33 + }
34 + }
35 + }
36 + // defaults to US-ASCII only if type is not provided
37 + if (!meta[0] && !charset.length) {
38 + typeFull += ';charset=US-ASCII';
39 + charset = 'US-ASCII';
40 + }
41 + // get the encoded data portion and decode URI-encoded chars
42 + const encoding = base64 ? 'base64' : 'ascii';
43 + const data = unescape(uri.substring(firstComma + 1));
44 + const buffer = Buffer.from(data, encoding);
45 + // set `.type` and `.typeFull` properties to MIME type
46 + buffer.type = type;
47 + buffer.typeFull = typeFull;
48 + // set the `.charset` property
49 + buffer.charset = charset;
50 + return buffer;
51 +}
52 +export default dataUriToBuffer;
53 +//# sourceMappingURL=index.js.map
...\ No newline at end of file ...\ No newline at end of file
1 +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAMA;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,GAAW;IAC1C,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QACzB,MAAM,IAAI,SAAS,CAClB,kEAAkE,CAClE,CAAC;KACF;IAED,iBAAiB;IACjB,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAEhC,+DAA+D;IAC/D,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,IAAI,UAAU,KAAK,CAAC,CAAC,IAAI,UAAU,IAAI,CAAC,EAAE;QACzC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;KAC3C;IAED,mDAAmD;IACnD,MAAM,IAAI,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAErD,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC;IACrC,IAAI,QAAQ,GAAG,IAAI,CAAC;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE;YACzB,MAAM,GAAG,IAAI,CAAC;SACd;aAAM;YACN,QAAQ,IAAI,IAAM,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5B,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE;gBACtC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;aAC/B;SACD;KACD;IACD,oDAAoD;IACpD,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;QAChC,QAAQ,IAAI,mBAAmB,CAAC;QAChC,OAAO,GAAG,UAAU,CAAC;KACrB;IAED,4DAA4D;IAC5D,MAAM,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7C,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;IACrD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAe,CAAC;IAEzD,sDAAsD;IACtD,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAE3B,8BAA8B;IAC9B,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;IAEzB,OAAO,MAAM,CAAC;AACf,CAAC;AAED,eAAe,eAAe,CAAC"}
...\ No newline at end of file ...\ No newline at end of file
1 +/**
2 + * Module dependencies.
3 + */
4 +export {};
1 +/**
2 + * Module dependencies.
3 + */
4 +import assert from 'assert';
5 +import dataUriToBuffer from '../src';
6 +describe('data-uri-to-buffer', function () {
7 + it('should decode bare-bones Data URIs', function () {
8 + var uri = 'data:,Hello%2C%20World!';
9 + var buf = dataUriToBuffer(uri);
10 + assert.equal('text/plain', buf.type);
11 + assert.equal('text/plain;charset=US-ASCII', buf.typeFull);
12 + assert.equal('US-ASCII', buf.charset);
13 + assert.equal('Hello, World!', buf.toString());
14 + });
15 + it('should decode bare-bones "base64" Data URIs', function () {
16 + var uri = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D';
17 + var buf = dataUriToBuffer(uri);
18 + assert.equal('text/plain', buf.type);
19 + assert.equal('Hello, World!', buf.toString());
20 + });
21 + it('should decode plain-text Data URIs', function () {
22 + var html = '<!DOCTYPE html>' +
23 + '<html lang="en">' +
24 + '<head><title>Embedded Window</title></head>' +
25 + '<body><h1>42</h1></body>' +
26 + '</html>';
27 + // Escape the HTML for URL formatting
28 + var uri = 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
29 + var buf = dataUriToBuffer(uri);
30 + assert.equal('text/html', buf.type);
31 + assert.equal('utf-8', buf.charset);
32 + assert.equal(html, buf.toString());
33 + });
34 + // the next 4 tests are from:
35 + // https://bug161965.bugzilla.mozilla.org/attachment.cgi?id=94670&action=view
36 + it('should decode "ISO-8859-8 in Base64" URIs', function () {
37 + var uri = 'data:text/plain;charset=iso-8859-8-i;base64,+ezl7Q==';
38 + var buf = dataUriToBuffer(uri);
39 + assert.equal('text/plain', buf.type);
40 + assert.equal('iso-8859-8-i', buf.charset);
41 + assert.equal(4, buf.length);
42 + assert.equal(0xf9, buf[0]);
43 + assert.equal(0xec, buf[1]);
44 + assert.equal(0xe5, buf[2]);
45 + assert.equal(0xed, buf[3]);
46 + });
47 + it('should decode "ISO-8859-8 in URL-encoding" URIs', function () {
48 + var uri = 'data:text/plain;charset=iso-8859-8-i,%f9%ec%e5%ed';
49 + var buf = dataUriToBuffer(uri);
50 + assert.equal('text/plain', buf.type);
51 + assert.equal('iso-8859-8-i', buf.charset);
52 + assert.equal(4, buf.length);
53 + assert.equal(0xf9, buf[0]);
54 + assert.equal(0xec, buf[1]);
55 + assert.equal(0xe5, buf[2]);
56 + assert.equal(0xed, buf[3]);
57 + });
58 + it('should decode "UTF-8 in Base64" URIs', function () {
59 + var uri = 'data:text/plain;charset=UTF-8;base64,16nXnNeV150=';
60 + var buf = dataUriToBuffer(uri);
61 + assert.equal('text/plain', buf.type);
62 + assert.equal('UTF-8', buf.charset);
63 + assert.equal(8, buf.length);
64 + assert.equal('שלום', buf.toString('utf8'));
65 + });
66 + it('should decode "UTF-8 in URL-encoding" URIs', function () {
67 + var uri = 'data:text/plain;charset=UTF-8,%d7%a9%d7%9c%d7%95%d7%9d';
68 + var buf = dataUriToBuffer(uri);
69 + assert.equal('text/plain', buf.type);
70 + assert.equal('UTF-8', buf.charset);
71 + assert.equal(8, buf.length);
72 + assert.equal('שלום', buf.toString('utf8'));
73 + });
74 + // this next one is from Wikipedia IIRC
75 + it('should decode "base64" Data URIs with newlines', function () {
76 + var uri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA\n' +
77 + 'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO\n' +
78 + '9TXL0Y4OHwAAAABJRU5ErkJggg==';
79 + var buf = dataUriToBuffer(uri);
80 + assert.equal('image/png', buf.type);
81 + assert.equal('iVBORw0KGgoAAAANSUhEUgAAAAUA' +
82 + 'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +
83 + '9TXL0Y4OHwAAAABJRU5ErkJggg==', buf.toString('base64'));
84 + });
85 + it('should decode a plain-text URI with a space character in it', function () {
86 + var uri = 'data:,foo bar';
87 + var buf = dataUriToBuffer(uri);
88 + assert.equal('text/plain', buf.type);
89 + assert.equal('foo bar', buf.toString());
90 + });
91 + it('should decode data with a "," comma char', function () {
92 + var uri = 'data:,a,b';
93 + var buf = dataUriToBuffer(uri);
94 + assert.equal('text/plain', buf.type);
95 + assert.equal('a,b', buf.toString());
96 + });
97 + it('should decode data with traditionally reserved characters like ";"', function () {
98 + var uri = 'data:,;test';
99 + var buf = dataUriToBuffer(uri);
100 + assert.equal('text/plain', buf.type);
101 + assert.equal(';test', buf.toString());
102 + });
103 + it('should not default to US-ASCII if main type is provided', function () {
104 + var uri = 'data:text/plain,abc';
105 + var buf = dataUriToBuffer(uri);
106 + assert.equal('text/plain', buf.type);
107 + assert.equal('text/plain', buf.typeFull);
108 + assert.equal('', buf.charset);
109 + assert.equal('abc', buf.toString());
110 + });
111 + it('should default to text/plain if main type is not provided', function () {
112 + var uri = 'data:;charset=UTF-8,abc';
113 + var buf = dataUriToBuffer(uri);
114 + assert.equal('text/plain', buf.type);
115 + assert.equal('text/plain;charset=UTF-8', buf.typeFull);
116 + assert.equal('UTF-8', buf.charset);
117 + assert.equal('abc', buf.toString());
118 + });
119 + it('should not allow charset without a leading ;', function () {
120 + var uri = 'data:charset=UTF-8,abc';
121 + var buf = dataUriToBuffer(uri);
122 + assert.equal('charset=UTF-8', buf.type);
123 + assert.equal('charset=UTF-8', buf.typeFull);
124 + assert.equal('', buf.charset);
125 + assert.equal('abc', buf.toString());
126 + });
127 + it('should allow custom media type parameters', function () {
128 + var uri = 'data:application/javascript;version=1.8;charset=UTF-8,abc';
129 + var buf = dataUriToBuffer(uri);
130 + assert.equal('application/javascript', buf.type);
131 + assert.equal('application/javascript;version=1.8;charset=UTF-8', buf.typeFull);
132 + assert.equal('UTF-8', buf.charset);
133 + assert.equal('abc', buf.toString());
134 + });
135 + it('should allow base64 annotation anywhere', function () {
136 + var uri = 'data:text/plain;base64;charset=UTF-8,YWJj';
137 + var buf = dataUriToBuffer(uri);
138 + assert.equal('text/plain', buf.type);
139 + assert.equal('text/plain;charset=UTF-8', buf.typeFull);
140 + assert.equal('UTF-8', buf.charset);
141 + assert.equal('abc', buf.toString());
142 + });
143 +});
144 +//# sourceMappingURL=test.js.map
...\ No newline at end of file ...\ No newline at end of file
1 +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test/test.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,eAAe,MAAM,QAAQ,CAAC;AAErC,QAAQ,CAAC,oBAAoB,EAAE;IAC9B,EAAE,CAAC,oCAAoC,EAAE;QACxC,IAAI,GAAG,GAAG,yBAAyB,CAAC;QAEpC,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,6BAA6B,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC1D,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QACtC,MAAM,CAAC,KAAK,CAAC,eAAe,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC/C,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,6CAA6C,EAAE;QACjD,IAAI,GAAG,GAAG,iDAAiD,CAAC;QAE5D,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,eAAe,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC/C,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,oCAAoC,EAAE;QACxC,IAAI,IAAI,GACP,iBAAiB;YACjB,kBAAkB;YAClB,6CAA6C;YAC7C,0BAA0B;YAC1B,SAAS,CAAC;QAEX,qCAAqC;QACrC,IAAI,GAAG,GAAG,+BAA+B,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;QAErE,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,WAAW,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QACnC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;IAEH,6BAA6B;IAC7B,6EAA6E;IAE7E,EAAE,CAAC,2CAA2C,EAAE;QAC/C,IAAI,GAAG,GAAG,sDAAsD,CAAC;QAEjE,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,cAAc,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QAC1C,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,iDAAiD,EAAE;QACrD,IAAI,GAAG,GAAG,mDAAmD,CAAC;QAE9D,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,cAAc,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QAC1C,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,sCAAsC,EAAE;QAC1C,IAAI,GAAG,GAAG,mDAAmD,CAAC;QAE9D,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QACnC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5C,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,4CAA4C,EAAE;QAChD,IAAI,GAAG,GAAG,wDAAwD,CAAC;QAEnE,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QACnC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5C,CAAC,CAAC,CAAC;IAEH,uCAAuC;IAEvC,EAAE,CAAC,gDAAgD,EAAE;QACpD,IAAI,GAAG,GACN,sDAAsD;YACtD,gEAAgE;YAChE,8BAA8B,CAAC;QAEhC,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,WAAW,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,MAAM,CAAC,KAAK,CACX,8BAA8B;YAC7B,8DAA8D;YAC9D,8BAA8B,EAC/B,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CACtB,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,6DAA6D,EAAE;QACjE,IAAI,GAAG,GAAG,eAAe,CAAC;QAE1B,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,SAAS,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACzC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,0CAA0C,EAAE;QAC9C,IAAI,GAAG,GAAG,WAAW,CAAC;QACtB,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,oEAAoE,EAAE;QACxE,IAAI,GAAG,GAAG,aAAa,CAAC;QACxB,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACvC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,yDAAyD,EAAE;QAC7D,IAAI,GAAG,GAAG,qBAAqB,CAAC;QAChC,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;QACzC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QAC9B,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,2DAA2D,EAAE;QAC/D,IAAI,GAAG,GAAG,yBAAyB,CAAC;QACpC,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;QACvD,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QACnC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,8CAA8C,EAAE;QAClD,IAAI,GAAG,GAAG,wBAAwB,CAAC;QACnC,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,eAAe,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACxC,MAAM,CAAC,KAAK,CAAC,eAAe,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC5C,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QAC9B,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,2CAA2C,EAAE;QAC/C,IAAI,GAAG,GAAG,2DAA2D,CAAC;QACtE,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,wBAAwB,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACjD,MAAM,CAAC,KAAK,CACX,kDAAkD,EAClD,GAAG,CAAC,QAAQ,CACZ,CAAC;QACF,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QACnC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,yCAAyC,EAAE;QAC7C,IAAI,GAAG,GAAG,2CAA2C,CAAC;QACtD,IAAI,GAAG,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;QACvD,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QACnC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;AACJ,CAAC,CAAC,CAAC"}
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "name": "data-uri-to-buffer",
3 + "version": "4.0.0",
4 + "description": "Generate a Buffer instance from a Data URI string",
5 + "type": "module",
6 + "main": "dist/index.js",
7 + "types": "dist/index.d.ts",
8 + "files": [
9 + "dist",
10 + "src"
11 + ],
12 + "scripts": {
13 + "build": "tsc",
14 + "test": "jest",
15 + "prepublishOnly": "npm run build"
16 + },
17 + "repository": {
18 + "type": "git",
19 + "url": "git://github.com/TooTallNate/node-data-uri-to-buffer.git"
20 + },
21 + "engines": {
22 + "node": ">= 12"
23 + },
24 + "keywords": [
25 + "data",
26 + "uri",
27 + "datauri",
28 + "data-uri",
29 + "buffer",
30 + "convert",
31 + "rfc2397",
32 + "2397"
33 + ],
34 + "author": "Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)",
35 + "license": "MIT",
36 + "bugs": {
37 + "url": "https://github.com/TooTallNate/node-data-uri-to-buffer/issues"
38 + },
39 + "homepage": "https://github.com/TooTallNate/node-data-uri-to-buffer",
40 + "devDependencies": {
41 + "@types/es6-promisify": "^5.0.0",
42 + "@types/mocha": "^9.0.0",
43 + "@types/node": "^10.5.3",
44 + "jest": "^27.2.2",
45 + "ts-jest": "^27.0.5",
46 + "typescript": "^4.4.3"
47 + },
48 + "jest": {
49 + "preset": "ts-jest",
50 + "globals": {
51 + "ts-jest": {
52 + "diagnostics": false,
53 + "isolatedModules": true
54 + }
55 + },
56 + "verbose": false,
57 + "testEnvironment": "node",
58 + "testMatch": [
59 + "<rootDir>/test/**/*.test.ts"
60 + ]
61 + }
62 +}
1 +export interface MimeBuffer extends Buffer {
2 + type: string;
3 + typeFull: string;
4 + charset: string;
5 +}
6 +
7 +/**
8 + * Returns a `Buffer` instance from the given data URI `uri`.
9 + *
10 + * @param {String} uri Data URI to turn into a Buffer instance
11 + * @returns {Buffer} Buffer instance from Data URI
12 + * @api public
13 + */
14 +export function dataUriToBuffer(uri: string): MimeBuffer {
15 + if (!/^data:/i.test(uri)) {
16 + throw new TypeError(
17 + '`uri` does not appear to be a Data URI (must begin with "data:")'
18 + );
19 + }
20 +
21 + // strip newlines
22 + uri = uri.replace(/\r?\n/g, '');
23 +
24 + // split the URI up into the "metadata" and the "data" portions
25 + const firstComma = uri.indexOf(',');
26 + if (firstComma === -1 || firstComma <= 4) {
27 + throw new TypeError('malformed data: URI');
28 + }
29 +
30 + // remove the "data:" scheme and parse the metadata
31 + const meta = uri.substring(5, firstComma).split(';');
32 +
33 + let charset = '';
34 + let base64 = false;
35 + const type = meta[0] || 'text/plain';
36 + let typeFull = type;
37 + for (let i = 1; i < meta.length; i++) {
38 + if (meta[i] === 'base64') {
39 + base64 = true;
40 + } else {
41 + typeFull += `;${ meta[i]}`;
42 + if (meta[i].indexOf('charset=') === 0) {
43 + charset = meta[i].substring(8);
44 + }
45 + }
46 + }
47 + // defaults to US-ASCII only if type is not provided
48 + if (!meta[0] && !charset.length) {
49 + typeFull += ';charset=US-ASCII';
50 + charset = 'US-ASCII';
51 + }
52 +
53 + // get the encoded data portion and decode URI-encoded chars
54 + const encoding = base64 ? 'base64' : 'ascii';
55 + const data = unescape(uri.substring(firstComma + 1));
56 + const buffer = Buffer.from(data, encoding) as MimeBuffer;
57 +
58 + // set `.type` and `.typeFull` properties to MIME type
59 + buffer.type = type;
60 + buffer.typeFull = typeFull;
61 +
62 + // set the `.charset` property
63 + buffer.charset = charset;
64 +
65 + return buffer;
66 +}
67 +
68 +export default dataUriToBuffer;
1 -Copyright (c) 2014-present Matt Zabriskie 1 +The MIT License (MIT)
2 +
3 +Copyright (c) 2016 David Frank
2 4
3 Permission is hereby granted, free of charge, to any person obtaining a copy 5 Permission is hereby granted, free of charge, to any person obtaining a copy
4 of this software and associated documentation files (the "Software"), to deal 6 of this software and associated documentation files (the "Software"), to deal
...@@ -7,13 +9,14 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ...@@ -7,13 +9,14 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 copies of the Software, and to permit persons to whom the Software is 9 copies of the Software, and to permit persons to whom the Software is
8 furnished to do so, subject to the following conditions: 10 furnished to do so, subject to the following conditions:
9 11
10 -The above copyright notice and this permission notice shall be included in 12 +The above copyright notice and this permission notice shall be included in all
11 -all copies or substantial portions of the Software. 13 +copies or substantial portions of the Software.
12 14
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 -THE SOFTWARE. 21 +SOFTWARE.
22 +
......
1 +node-fetch
2 +==========
3 +
4 +[![npm version][npm-image]][npm-url]
5 +[![build status][travis-image]][travis-url]
6 +[![coverage status][codecov-image]][codecov-url]
7 +[![install size][install-size-image]][install-size-url]
8 +[![Discord][discord-image]][discord-url]
9 +
10 +A light-weight module that brings `window.fetch` to Node.js
11 +
12 +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567))
13 +
14 +[![Backers][opencollective-image]][opencollective-url]
15 +
16 +<!-- TOC -->
17 +
18 +- [Motivation](#motivation)
19 +- [Features](#features)
20 +- [Difference from client-side fetch](#difference-from-client-side-fetch)
21 +- [Installation](#installation)
22 +- [Loading and configuring the module](#loading-and-configuring-the-module)
23 +- [Common Usage](#common-usage)
24 + - [Plain text or HTML](#plain-text-or-html)
25 + - [JSON](#json)
26 + - [Simple Post](#simple-post)
27 + - [Post with JSON](#post-with-json)
28 + - [Post with form parameters](#post-with-form-parameters)
29 + - [Handling exceptions](#handling-exceptions)
30 + - [Handling client and server errors](#handling-client-and-server-errors)
31 +- [Advanced Usage](#advanced-usage)
32 + - [Streams](#streams)
33 + - [Buffer](#buffer)
34 + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)
35 + - [Extract Set-Cookie Header](#extract-set-cookie-header)
36 + - [Post data using a file stream](#post-data-using-a-file-stream)
37 + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)
38 + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
39 +- [API](#api)
40 + - [fetch(url[, options])](#fetchurl-options)
41 + - [Options](#options)
42 + - [Class: Request](#class-request)
43 + - [Class: Response](#class-response)
44 + - [Class: Headers](#class-headers)
45 + - [Interface: Body](#interface-body)
46 + - [Class: FetchError](#class-fetcherror)
47 +- [License](#license)
48 +- [Acknowledgement](#acknowledgement)
49 +
50 +<!-- /TOC -->
51 +
52 +## Motivation
53 +
54 +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.
55 +
56 +See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).
57 +
58 +## Features
59 +
60 +- Stay consistent with `window.fetch` API.
61 +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.
62 +- Use native promise but allow substituting it with [insert your favorite promise library].
63 +- Use native Node streams for body on both request and response.
64 +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.
65 +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting.
66 +
67 +## Difference from client-side fetch
68 +
69 +- See [Known Differences](LIMITS.md) for details.
70 +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.
71 +- Pull requests are welcomed too!
72 +
73 +## Installation
74 +
75 +Current stable release (`2.x`)
76 +
77 +```sh
78 +$ npm install node-fetch
79 +```
80 +
81 +## Loading and configuring the module
82 +We suggest you load the module via `require` until the stabilization of ES modules in node:
83 +```js
84 +const fetch = require('node-fetch');
85 +```
86 +
87 +If you are using a Promise library other than native, set it through `fetch.Promise`:
88 +```js
89 +const Bluebird = require('bluebird');
90 +
91 +fetch.Promise = Bluebird;
92 +```
93 +
94 +## Common Usage
95 +
96 +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences.
97 +
98 +#### Plain text or HTML
99 +```js
100 +fetch('https://github.com/')
101 + .then(res => res.text())
102 + .then(body => console.log(body));
103 +```
104 +
105 +#### JSON
106 +
107 +```js
108 +
109 +fetch('https://api.github.com/users/github')
110 + .then(res => res.json())
111 + .then(json => console.log(json));
112 +```
113 +
114 +#### Simple Post
115 +```js
116 +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
117 + .then(res => res.json()) // expecting a json response
118 + .then(json => console.log(json));
119 +```
120 +
121 +#### Post with JSON
122 +
123 +```js
124 +const body = { a: 1 };
125 +
126 +fetch('https://httpbin.org/post', {
127 + method: 'post',
128 + body: JSON.stringify(body),
129 + headers: { 'Content-Type': 'application/json' },
130 + })
131 + .then(res => res.json())
132 + .then(json => console.log(json));
133 +```
134 +
135 +#### Post with form parameters
136 +`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.
137 +
138 +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:
139 +
140 +```js
141 +const { URLSearchParams } = require('url');
142 +
143 +const params = new URLSearchParams();
144 +params.append('a', 1);
145 +
146 +fetch('https://httpbin.org/post', { method: 'POST', body: params })
147 + .then(res => res.json())
148 + .then(json => console.log(json));
149 +```
150 +
151 +#### Handling exceptions
152 +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information.
153 +
154 +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details.
155 +
156 +```js
157 +fetch('https://domain.invalid/')
158 + .catch(err => console.error(err));
159 +```
160 +
161 +#### Handling client and server errors
162 +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:
163 +
164 +```js
165 +function checkStatus(res) {
166 + if (res.ok) { // res.status >= 200 && res.status < 300
167 + return res;
168 + } else {
169 + throw MyCustomError(res.statusText);
170 + }
171 +}
172 +
173 +fetch('https://httpbin.org/status/400')
174 + .then(checkStatus)
175 + .then(res => console.log('will not get here...'))
176 +```
177 +
178 +## Advanced Usage
179 +
180 +#### Streams
181 +The "Node.js way" is to use streams when possible:
182 +
183 +```js
184 +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
185 + .then(res => {
186 + const dest = fs.createWriteStream('./octocat.png');
187 + res.body.pipe(dest);
188 + });
189 +```
190 +
191 +#### Buffer
192 +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API)
193 +
194 +```js
195 +const fileType = require('file-type');
196 +
197 +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
198 + .then(res => res.buffer())
199 + .then(buffer => fileType(buffer))
200 + .then(type => { /* ... */ });
201 +```
202 +
203 +#### Accessing Headers and other Meta data
204 +```js
205 +fetch('https://github.com/')
206 + .then(res => {
207 + console.log(res.ok);
208 + console.log(res.status);
209 + console.log(res.statusText);
210 + console.log(res.headers.raw());
211 + console.log(res.headers.get('content-type'));
212 + });
213 +```
214 +
215 +#### Extract Set-Cookie Header
216 +
217 +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.
218 +
219 +```js
220 +fetch(url).then(res => {
221 + // returns an array of values, instead of a string of comma-separated values
222 + console.log(res.headers.raw()['set-cookie']);
223 +});
224 +```
225 +
226 +#### Post data using a file stream
227 +
228 +```js
229 +const { createReadStream } = require('fs');
230 +
231 +const stream = createReadStream('input.txt');
232 +
233 +fetch('https://httpbin.org/post', { method: 'POST', body: stream })
234 + .then(res => res.json())
235 + .then(json => console.log(json));
236 +```
237 +
238 +#### Post with form-data (detect multipart)
239 +
240 +```js
241 +const FormData = require('form-data');
242 +
243 +const form = new FormData();
244 +form.append('a', 1);
245 +
246 +fetch('https://httpbin.org/post', { method: 'POST', body: form })
247 + .then(res => res.json())
248 + .then(json => console.log(json));
249 +
250 +// OR, using custom headers
251 +// NOTE: getHeaders() is non-standard API
252 +
253 +const form = new FormData();
254 +form.append('a', 1);
255 +
256 +const options = {
257 + method: 'POST',
258 + body: form,
259 + headers: form.getHeaders()
260 +}
261 +
262 +fetch('https://httpbin.org/post', options)
263 + .then(res => res.json())
264 + .then(json => console.log(json));
265 +```
266 +
267 +#### Request cancellation with AbortSignal
268 +
269 +> NOTE: You may cancel streamed requests only on Node >= v8.0.0
270 +
271 +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).
272 +
273 +An example of timing out a request after 150ms could be achieved as the following:
274 +
275 +```js
276 +import AbortController from 'abort-controller';
277 +
278 +const controller = new AbortController();
279 +const timeout = setTimeout(
280 + () => { controller.abort(); },
281 + 150,
282 +);
283 +
284 +fetch(url, { signal: controller.signal })
285 + .then(res => res.json())
286 + .then(
287 + data => {
288 + useData(data)
289 + },
290 + err => {
291 + if (err.name === 'AbortError') {
292 + // request was aborted
293 + }
294 + },
295 + )
296 + .finally(() => {
297 + clearTimeout(timeout);
298 + });
299 +```
300 +
301 +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples.
302 +
303 +
304 +## API
305 +
306 +### fetch(url[, options])
307 +
308 +- `url` A string representing the URL for fetching
309 +- `options` [Options](#fetch-options) for the HTTP(S) request
310 +- Returns: <code>Promise&lt;[Response](#class-response)&gt;</code>
311 +
312 +Perform an HTTP(S) fetch.
313 +
314 +`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.
315 +
316 +<a id="fetch-options"></a>
317 +### Options
318 +
319 +The default values are shown after each option key.
320 +
321 +```js
322 +{
323 + // These properties are part of the Fetch Standard
324 + method: 'GET',
325 + headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)
326 + body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream
327 + redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect
328 + signal: null, // pass an instance of AbortSignal to optionally abort requests
329 +
330 + // The following properties are node-fetch extensions
331 + follow: 20, // maximum redirect count. 0 to not follow redirect
332 + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.
333 + compress: true, // support gzip/deflate content encoding. false to disable
334 + size: 0, // maximum response body size in bytes. 0 to disable
335 + agent: null // http(s).Agent instance or function that returns an instance (see below)
336 +}
337 +```
338 +
339 +##### Default Headers
340 +
341 +If no values are set, the following request headers will be sent automatically:
342 +
343 +Header | Value
344 +------------------- | --------------------------------------------------------
345 +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_
346 +`Accept` | `*/*`
347 +`Connection` | `close` _(when no `options.agent` is present)_
348 +`Content-Length` | _(automatically calculated, if possible)_
349 +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_
350 +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)`
351 +
352 +Note: when `body` is a `Stream`, `Content-Length` is not set automatically.
353 +
354 +##### Custom Agent
355 +
356 +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:
357 +
358 +- Support self-signed certificate
359 +- Use only IPv4 or IPv6
360 +- Custom DNS Lookup
361 +
362 +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.
363 +
364 +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.
365 +
366 +```js
367 +const httpAgent = new http.Agent({
368 + keepAlive: true
369 +});
370 +const httpsAgent = new https.Agent({
371 + keepAlive: true
372 +});
373 +
374 +const options = {
375 + agent: function (_parsedURL) {
376 + if (_parsedURL.protocol == 'http:') {
377 + return httpAgent;
378 + } else {
379 + return httpsAgent;
380 + }
381 + }
382 +}
383 +```
384 +
385 +<a id="class-request"></a>
386 +### Class: Request
387 +
388 +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.
389 +
390 +Due to the nature of Node.js, the following properties are not implemented at this moment:
391 +
392 +- `type`
393 +- `destination`
394 +- `referrer`
395 +- `referrerPolicy`
396 +- `mode`
397 +- `credentials`
398 +- `cache`
399 +- `integrity`
400 +- `keepalive`
401 +
402 +The following node-fetch extension properties are provided:
403 +
404 +- `follow`
405 +- `compress`
406 +- `counter`
407 +- `agent`
408 +
409 +See [options](#fetch-options) for exact meaning of these extensions.
410 +
411 +#### new Request(input[, options])
412 +
413 +<small>*(spec-compliant)*</small>
414 +
415 +- `input` A string representing a URL, or another `Request` (which will be cloned)
416 +- `options` [Options][#fetch-options] for the HTTP(S) request
417 +
418 +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).
419 +
420 +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.
421 +
422 +<a id="class-response"></a>
423 +### Class: Response
424 +
425 +An HTTP(S) response. This class implements the [Body](#iface-body) interface.
426 +
427 +The following properties are not implemented in node-fetch at this moment:
428 +
429 +- `Response.error()`
430 +- `Response.redirect()`
431 +- `type`
432 +- `trailer`
433 +
434 +#### new Response([body[, options]])
435 +
436 +<small>*(spec-compliant)*</small>
437 +
438 +- `body` A `String` or [`Readable` stream][node-readable]
439 +- `options` A [`ResponseInit`][response-init] options dictionary
440 +
441 +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).
442 +
443 +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.
444 +
445 +#### response.ok
446 +
447 +<small>*(spec-compliant)*</small>
448 +
449 +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.
450 +
451 +#### response.redirected
452 +
453 +<small>*(spec-compliant)*</small>
454 +
455 +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.
456 +
457 +<a id="class-headers"></a>
458 +### Class: Headers
459 +
460 +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.
461 +
462 +#### new Headers([init])
463 +
464 +<small>*(spec-compliant)*</small>
465 +
466 +- `init` Optional argument to pre-fill the `Headers` object
467 +
468 +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.
469 +
470 +```js
471 +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
472 +
473 +const meta = {
474 + 'Content-Type': 'text/xml',
475 + 'Breaking-Bad': '<3'
476 +};
477 +const headers = new Headers(meta);
478 +
479 +// The above is equivalent to
480 +const meta = [
481 + [ 'Content-Type', 'text/xml' ],
482 + [ 'Breaking-Bad', '<3' ]
483 +];
484 +const headers = new Headers(meta);
485 +
486 +// You can in fact use any iterable objects, like a Map or even another Headers
487 +const meta = new Map();
488 +meta.set('Content-Type', 'text/xml');
489 +meta.set('Breaking-Bad', '<3');
490 +const headers = new Headers(meta);
491 +const copyOfHeaders = new Headers(headers);
492 +```
493 +
494 +<a id="iface-body"></a>
495 +### Interface: Body
496 +
497 +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.
498 +
499 +The following methods are not yet implemented in node-fetch at this moment:
500 +
501 +- `formData()`
502 +
503 +#### body.body
504 +
505 +<small>*(deviation from spec)*</small>
506 +
507 +* Node.js [`Readable` stream][node-readable]
508 +
509 +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].
510 +
511 +#### body.bodyUsed
512 +
513 +<small>*(spec-compliant)*</small>
514 +
515 +* `Boolean`
516 +
517 +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.
518 +
519 +#### body.arrayBuffer()
520 +#### body.blob()
521 +#### body.json()
522 +#### body.text()
523 +
524 +<small>*(spec-compliant)*</small>
525 +
526 +* Returns: <code>Promise</code>
527 +
528 +Consume the body and return a promise that will resolve to one of these formats.
529 +
530 +#### body.buffer()
531 +
532 +<small>*(node-fetch extension)*</small>
533 +
534 +* Returns: <code>Promise&lt;Buffer&gt;</code>
535 +
536 +Consume the body and return a promise that will resolve to a Buffer.
537 +
538 +#### body.textConverted()
539 +
540 +<small>*(node-fetch extension)*</small>
541 +
542 +* Returns: <code>Promise&lt;String&gt;</code>
543 +
544 +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible.
545 +
546 +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.)
547 +
548 +<a id="class-fetcherror"></a>
549 +### Class: FetchError
550 +
551 +<small>*(node-fetch extension)*</small>
552 +
553 +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.
554 +
555 +<a id="class-aborterror"></a>
556 +### Class: AbortError
557 +
558 +<small>*(node-fetch extension)*</small>
559 +
560 +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.
561 +
562 +## Acknowledgement
563 +
564 +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.
565 +
566 +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr).
567 +
568 +## License
569 +
570 +MIT
571 +
572 +[npm-image]: https://flat.badgen.net/npm/v/node-fetch
573 +[npm-url]: https://www.npmjs.com/package/node-fetch
574 +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch
575 +[travis-url]: https://travis-ci.org/bitinn/node-fetch
576 +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master
577 +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch
578 +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch
579 +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch
580 +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square
581 +[discord-url]: https://discord.gg/Zxbndcm
582 +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg
583 +[opencollective-url]: https://opencollective.com/node-fetch
584 +[whatwg-fetch]: https://fetch.spec.whatwg.org/
585 +[response-init]: https://fetch.spec.whatwg.org/#responseinit
586 +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams
587 +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers
588 +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md
589 +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md
590 +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md
1 +{
2 + "name": "node-fetch",
3 + "version": "2.6.7",
4 + "description": "A light-weight module that brings window.fetch to node.js",
5 + "main": "lib/index.js",
6 + "browser": "./browser.js",
7 + "module": "lib/index.mjs",
8 + "files": [
9 + "lib/index.js",
10 + "lib/index.mjs",
11 + "lib/index.es.js",
12 + "browser.js"
13 + ],
14 + "engines": {
15 + "node": "4.x || >=6.0.0"
16 + },
17 + "scripts": {
18 + "build": "cross-env BABEL_ENV=rollup rollup -c",
19 + "prepare": "npm run build",
20 + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js",
21 + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js",
22 + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json"
23 + },
24 + "repository": {
25 + "type": "git",
26 + "url": "https://github.com/bitinn/node-fetch.git"
27 + },
28 + "keywords": [
29 + "fetch",
30 + "http",
31 + "promise"
32 + ],
33 + "author": "David Frank",
34 + "license": "MIT",
35 + "bugs": {
36 + "url": "https://github.com/bitinn/node-fetch/issues"
37 + },
38 + "homepage": "https://github.com/bitinn/node-fetch",
39 + "dependencies": {
40 + "whatwg-url": "^5.0.0"
41 + },
42 + "peerDependencies": {
43 + "encoding": "^0.1.0"
44 + },
45 + "peerDependenciesMeta": {
46 + "encoding": {
47 + "optional": true
48 + }
49 + },
50 + "devDependencies": {
51 + "@ungap/url-search-params": "^0.1.2",
52 + "abort-controller": "^1.1.0",
53 + "abortcontroller-polyfill": "^1.3.0",
54 + "babel-core": "^6.26.3",
55 + "babel-plugin-istanbul": "^4.1.6",
56 + "babel-preset-env": "^1.6.1",
57 + "babel-register": "^6.16.3",
58 + "chai": "^3.5.0",
59 + "chai-as-promised": "^7.1.1",
60 + "chai-iterator": "^1.1.1",
61 + "chai-string": "~1.3.0",
62 + "codecov": "3.3.0",
63 + "cross-env": "^5.2.0",
64 + "form-data": "^2.3.3",
65 + "is-builtin-module": "^1.0.0",
66 + "mocha": "^5.0.0",
67 + "nyc": "11.9.0",
68 + "parted": "^0.1.1",
69 + "promise": "^8.0.3",
70 + "resumer": "0.0.0",
71 + "rollup": "^0.63.4",
72 + "rollup-plugin-babel": "^3.0.7",
73 + "string-to-arraybuffer": "^1.0.2",
74 + "teeny-request": "3.7.0"
75 + }
76 +}
1 -Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors 1 +MIT License
2 2
3 - Permission is hereby granted, free of charge, to any person obtaining a copy 3 +Copyright (c) 2019 David Frank
4 - of this software and associated documentation files (the "Software"), to deal
5 - in the Software without restriction, including without limitation the rights
6 - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 - copies of the Software, and to permit persons to whom the Software is
8 - furnished to do so, subject to the following conditions:
9 4
10 - The above copyright notice and this permission notice shall be included in 5 +Permission is hereby granted, free of charge, to any person obtaining a copy
11 - all copies or substantial portions of the Software. 6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
12 11
13 - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 +The above copyright notice and this permission notice shall be included in all
14 - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 +copies or substantial portions of the Software.
15 - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 +
16 - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 - THE SOFTWARE. 18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
......
1 +# fetch-blob
2 +
3 +[![npm version][npm-image]][npm-url]
4 +[![build status][ci-image]][ci-url]
5 +[![coverage status][codecov-image]][codecov-url]
6 +[![install size][install-size-image]][install-size-url]
7 +
8 +A Blob implementation in Node.js, originally from [node-fetch](https://github.com/node-fetch/node-fetch).
9 +
10 +## Installation
11 +
12 +```sh
13 +npm install fetch-blob
14 +```
15 +
16 +<details>
17 + <summary>Upgrading from 2x to 3x</summary>
18 +
19 + Updating from 2 to 3 should be a breeze since there is not many changes to the blob specification.
20 + The major cause of a major release is coding standards.
21 + - internal WeakMaps was replaced with private fields
22 + - internal Buffer.from was replaced with TextEncoder/Decoder
23 + - internal buffers was replaced with Uint8Arrays
24 + - CommonJS was replaced with ESM
25 + - The node stream returned by calling `blob.stream()` was replaced with whatwg streams
26 + - (Read "Differences from other blobs" for more info.)
27 +
28 +</details>
29 +
30 +<details>
31 + <summary>Differences from other Blobs</summary>
32 +
33 + - Unlike NodeJS `buffer.Blob` (Added in: v15.7.0) and browser native Blob this polyfilled version can't be sent via PostMessage
34 + - This blob version is more arbitrary, it can be constructed with blob parts that isn't a instance of itself
35 + it has to look and behave as a blob to be accepted as a blob part.
36 + - The benefit of this is that you can create other types of blobs that don't contain any internal data that has to be read in other ways, such as the `BlobDataItem` created in `from.js` that wraps a file path into a blob-like item and read lazily (nodejs plans to [implement this][fs-blobs] as well)
37 + - The `blob.stream()` is the most noticeable differences. It returns a WHATWG stream now. to keep it as a node stream you would have to do:
38 +
39 + ```js
40 + import {Readable} from 'stream'
41 + const stream = Readable.from(blob.stream())
42 + ```
43 +</details>
44 +
45 +## Usage
46 +
47 +```js
48 +// Ways to import
49 +// (PS it's dependency free ESM package so regular http-import from CDN works too)
50 +import Blob from 'fetch-blob'
51 +import File from 'fetch-blob/file.js'
52 +
53 +import {Blob} from 'fetch-blob'
54 +import {File} from 'fetch-blob/file.js'
55 +
56 +const {Blob} = await import('fetch-blob')
57 +
58 +
59 +// Ways to read the blob:
60 +const blob = new Blob(['hello, world'])
61 +
62 +await blob.text()
63 +await blob.arrayBuffer()
64 +for await (let chunk of blob.stream()) { ... }
65 +blob.stream().getReader().read()
66 +blob.stream().getReader({mode: 'byob'}).read(view)
67 +```
68 +
69 +### Blob part backed up by filesystem
70 +
71 +`fetch-blob/from.js` comes packed with tools to convert any filepath into either a Blob or a File
72 +It will not read the content into memory. It will only stat the file for last modified date and file size.
73 +
74 +```js
75 +// The default export is sync and use fs.stat to retrieve size & last modified as a blob
76 +import blobFromSync from 'fetch-blob/from.js'
77 +import {File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync} from 'fetch-blob/from.js'
78 +
79 +const fsFile = fileFromSync('./2-GiB-file.bin', 'application/octet-stream')
80 +const fsBlob = await blobFrom('./2-GiB-file.mp4')
81 +
82 +// Not a 4 GiB memory snapshot, just holds references
83 +// points to where data is located on the disk
84 +const blob = new Blob([fsFile, fsBlob, 'memory', new Uint8Array(10)])
85 +console.log(blob.size) // ~4 GiB
86 +```
87 +
88 +`blobFrom|blobFromSync|fileFrom|fileFromSync(path, [mimetype])`
89 +
90 +### Creating Blobs backed up by other async sources
91 +Our Blob & File class are more generic then any other polyfills in the way that it can accept any blob look-a-like item
92 +An example of this is that our blob implementation can be constructed with parts coming from [BlobDataItem](https://github.com/node-fetch/fetch-blob/blob/8ef89adad40d255a3bbd55cf38b88597c1cd5480/from.js#L32) (aka a filepath) or from [buffer.Blob](https://nodejs.org/api/buffer.html#buffer_new_buffer_blob_sources_options), It dose not have to implement all the methods - just enough that it can be read/understood by our Blob implementation. The minium requirements is that it has `Symbol.toStringTag`, `size`, `slice()` and either a `stream()` or a `arrayBuffer()` method. If you then wrap it in our Blob or File `new Blob([blobDataItem])` then you get all of the other methods that should be implemented in a blob or file
93 +
94 +An example of this could be to create a file or blob like item coming from a remote HTTP request. Or from a DataBase
95 +
96 +See the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and [tests](https://github.com/node-fetch/fetch-blob/blob/master/test.js) for more details of how to use the Blob.
97 +
98 +[npm-image]: https://flat.badgen.net/npm/v/fetch-blob
99 +[npm-url]: https://www.npmjs.com/package/fetch-blob
100 +[ci-image]: https://github.com/node-fetch/fetch-blob/workflows/CI/badge.svg
101 +[ci-url]: https://github.com/node-fetch/fetch-blob/actions
102 +[codecov-image]: https://flat.badgen.net/codecov/c/github/node-fetch/fetch-blob/master
103 +[codecov-url]: https://codecov.io/gh/node-fetch/fetch-blob
104 +[install-size-image]: https://flat.badgen.net/packagephobia/install/fetch-blob
105 +[install-size-url]: https://packagephobia.now.sh/result?p=fetch-blob
106 +[fs-blobs]: https://github.com/nodejs/node/issues/37340
1 +/** @type {typeof globalThis.File} */ export const File: typeof globalThis.File;
2 +export default File;
1 +import Blob from './index.js'
2 +
3 +const _File = class File extends Blob {
4 + #lastModified = 0
5 + #name = ''
6 +
7 + /**
8 + * @param {*[]} fileBits
9 + * @param {string} fileName
10 + * @param {{lastModified?: number, type?: string}} options
11 + */// @ts-ignore
12 + constructor (fileBits, fileName, options = {}) {
13 + if (arguments.length < 2) {
14 + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`)
15 + }
16 + super(fileBits, options)
17 +
18 + if (options === null) options = {}
19 +
20 + // Simulate WebIDL type casting for NaN value in lastModified option.
21 + const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified)
22 + if (!Number.isNaN(lastModified)) {
23 + this.#lastModified = lastModified
24 + }
25 +
26 + this.#name = String(fileName)
27 + }
28 +
29 + get name () {
30 + return this.#name
31 + }
32 +
33 + get lastModified () {
34 + return this.#lastModified
35 + }
36 +
37 + get [Symbol.toStringTag] () {
38 + return 'File'
39 + }
40 +
41 + static [Symbol.hasInstance] (object) {
42 + return !!object && object instanceof Blob &&
43 + /^(File)$/.test(object[Symbol.toStringTag])
44 + }
45 +}
46 +
47 +/** @type {typeof globalThis.File} */// @ts-ignore
48 +export const File = _File
49 +export default File
1 +export default blobFromSync;
2 +/**
3 + * @param {string} path filepath on the disk
4 + * @param {string} [type] mimetype to use
5 + */
6 +export function blobFromSync(path: string, type?: string): Blob;
7 +import File from "./file.js";
8 +import Blob from "./index.js";
9 +/**
10 + * @param {string} path filepath on the disk
11 + * @param {string} [type] mimetype to use
12 + * @returns {Promise<Blob>}
13 + */
14 +export function blobFrom(path: string, type?: string): Promise<Blob>;
15 +/**
16 + * @param {string} path filepath on the disk
17 + * @param {string} [type] mimetype to use
18 + * @returns {Promise<File>}
19 + */
20 +export function fileFrom(path: string, type?: string): Promise<File>;
21 +/**
22 + * @param {string} path filepath on the disk
23 + * @param {string} [type] mimetype to use
24 + */
25 +export function fileFromSync(path: string, type?: string): File;
26 +export { File, Blob };
1 +import { statSync, createReadStream, promises as fs } from 'node:fs'
2 +import { basename } from 'node:path'
3 +import DOMException from 'node-domexception'
4 +
5 +import File from './file.js'
6 +import Blob from './index.js'
7 +
8 +const { stat } = fs
9 +
10 +/**
11 + * @param {string} path filepath on the disk
12 + * @param {string} [type] mimetype to use
13 + */
14 +const blobFromSync = (path, type) => fromBlob(statSync(path), path, type)
15 +
16 +/**
17 + * @param {string} path filepath on the disk
18 + * @param {string} [type] mimetype to use
19 + * @returns {Promise<Blob>}
20 + */
21 +const blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type))
22 +
23 +/**
24 + * @param {string} path filepath on the disk
25 + * @param {string} [type] mimetype to use
26 + * @returns {Promise<File>}
27 + */
28 +const fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type))
29 +
30 +/**
31 + * @param {string} path filepath on the disk
32 + * @param {string} [type] mimetype to use
33 + */
34 +const fileFromSync = (path, type) => fromFile(statSync(path), path, type)
35 +
36 +// @ts-ignore
37 +const fromBlob = (stat, path, type = '') => new Blob([new BlobDataItem({
38 + path,
39 + size: stat.size,
40 + lastModified: stat.mtimeMs,
41 + start: 0
42 +})], { type })
43 +
44 +// @ts-ignore
45 +const fromFile = (stat, path, type = '') => new File([new BlobDataItem({
46 + path,
47 + size: stat.size,
48 + lastModified: stat.mtimeMs,
49 + start: 0
50 +})], basename(path), { type, lastModified: stat.mtimeMs })
51 +
52 +/**
53 + * This is a blob backed up by a file on the disk
54 + * with minium requirement. Its wrapped around a Blob as a blobPart
55 + * so you have no direct access to this.
56 + *
57 + * @private
58 + */
59 +class BlobDataItem {
60 + #path
61 + #start
62 +
63 + constructor (options) {
64 + this.#path = options.path
65 + this.#start = options.start
66 + this.size = options.size
67 + this.lastModified = options.lastModified
68 + this.originalSize = options.originalSize === undefined
69 + ? options.size
70 + : options.originalSize
71 + }
72 +
73 + /**
74 + * Slicing arguments is first validated and formatted
75 + * to not be out of range by Blob.prototype.slice
76 + */
77 + slice (start, end) {
78 + return new BlobDataItem({
79 + path: this.#path,
80 + lastModified: this.lastModified,
81 + originalSize: this.originalSize,
82 + size: end - start,
83 + start: this.#start + start
84 + })
85 + }
86 +
87 + async * stream () {
88 + const { mtimeMs, size } = await stat(this.#path)
89 +
90 + if (mtimeMs > this.lastModified || this.originalSize !== size) {
91 + throw new DOMException('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError')
92 + }
93 +
94 + yield * createReadStream(this.#path, {
95 + start: this.#start,
96 + end: this.#start + this.size - 1
97 + })
98 + }
99 +
100 + get [Symbol.toStringTag] () {
101 + return 'Blob'
102 + }
103 +}
104 +
105 +export default blobFromSync
106 +export { File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync }
1 +/** @type {typeof globalThis.Blob} */
2 +export const Blob: typeof globalThis.Blob;
3 +export default Blob;
1 +/*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x)
4 +// Node has recently added whatwg stream into core
5 +
6 +import './streams.cjs'
7 +
8 +// 64 KiB (same size chrome slice theirs blob into Uint8array's)
9 +const POOL_SIZE = 65536
10 +
11 +/** @param {(Blob | Uint8Array)[]} parts */
12 +async function * toIterator (parts, clone = true) {
13 + for (const part of parts) {
14 + if ('stream' in part) {
15 + yield * (/** @type {AsyncIterableIterator<Uint8Array>} */ (part.stream()))
16 + } else if (ArrayBuffer.isView(part)) {
17 + if (clone) {
18 + let position = part.byteOffset
19 + const end = part.byteOffset + part.byteLength
20 + while (position !== end) {
21 + const size = Math.min(end - position, POOL_SIZE)
22 + const chunk = part.buffer.slice(position, position + size)
23 + position += chunk.byteLength
24 + yield new Uint8Array(chunk)
25 + }
26 + } else {
27 + yield part
28 + }
29 + /* c8 ignore next 10 */
30 + } else {
31 + // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob)
32 + let position = 0, b = (/** @type {Blob} */ (part))
33 + while (position !== b.size) {
34 + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE))
35 + const buffer = await chunk.arrayBuffer()
36 + position += buffer.byteLength
37 + yield new Uint8Array(buffer)
38 + }
39 + }
40 + }
41 +}
42 +
43 +const _Blob = class Blob {
44 + /** @type {Array.<(Blob|Uint8Array)>} */
45 + #parts = []
46 + #type = ''
47 + #size = 0
48 + #endings = 'transparent'
49 +
50 + /**
51 + * The Blob() constructor returns a new Blob object. The content
52 + * of the blob consists of the concatenation of the values given
53 + * in the parameter array.
54 + *
55 + * @param {*} blobParts
56 + * @param {{ type?: string, endings?: string }} [options]
57 + */
58 + constructor (blobParts = [], options = {}) {
59 + if (typeof blobParts !== 'object' || blobParts === null) {
60 + throw new TypeError('Failed to construct \'Blob\': The provided value cannot be converted to a sequence.')
61 + }
62 +
63 + if (typeof blobParts[Symbol.iterator] !== 'function') {
64 + throw new TypeError('Failed to construct \'Blob\': The object must have a callable @@iterator property.')
65 + }
66 +
67 + if (typeof options !== 'object' && typeof options !== 'function') {
68 + throw new TypeError('Failed to construct \'Blob\': parameter 2 cannot convert to dictionary.')
69 + }
70 +
71 + if (options === null) options = {}
72 +
73 + const encoder = new TextEncoder()
74 + for (const element of blobParts) {
75 + let part
76 + if (ArrayBuffer.isView(element)) {
77 + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength))
78 + } else if (element instanceof ArrayBuffer) {
79 + part = new Uint8Array(element.slice(0))
80 + } else if (element instanceof Blob) {
81 + part = element
82 + } else {
83 + part = encoder.encode(`${element}`)
84 + }
85 +
86 + const size = ArrayBuffer.isView(part) ? part.byteLength : part.size
87 + // Avoid pushing empty parts into the array to better GC them
88 + if (size) {
89 + this.#size += size
90 + this.#parts.push(part)
91 + }
92 + }
93 +
94 + this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}`
95 + const type = options.type === undefined ? '' : String(options.type)
96 + this.#type = /^[\x20-\x7E]*$/.test(type) ? type : ''
97 + }
98 +
99 + /**
100 + * The Blob interface's size property returns the
101 + * size of the Blob in bytes.
102 + */
103 + get size () {
104 + return this.#size
105 + }
106 +
107 + /**
108 + * The type property of a Blob object returns the MIME type of the file.
109 + */
110 + get type () {
111 + return this.#type
112 + }
113 +
114 + /**
115 + * The text() method in the Blob interface returns a Promise
116 + * that resolves with a string containing the contents of
117 + * the blob, interpreted as UTF-8.
118 + *
119 + * @return {Promise<string>}
120 + */
121 + async text () {
122 + // More optimized than using this.arrayBuffer()
123 + // that requires twice as much ram
124 + const decoder = new TextDecoder()
125 + let str = ''
126 + for await (const part of toIterator(this.#parts, false)) {
127 + str += decoder.decode(part, { stream: true })
128 + }
129 + // Remaining
130 + str += decoder.decode()
131 + return str
132 + }
133 +
134 + /**
135 + * The arrayBuffer() method in the Blob interface returns a
136 + * Promise that resolves with the contents of the blob as
137 + * binary data contained in an ArrayBuffer.
138 + *
139 + * @return {Promise<ArrayBuffer>}
140 + */
141 + async arrayBuffer () {
142 + // Easier way... Just a unnecessary overhead
143 + // const view = new Uint8Array(this.size);
144 + // await this.stream().getReader({mode: 'byob'}).read(view);
145 + // return view.buffer;
146 +
147 + const data = new Uint8Array(this.size)
148 + let offset = 0
149 + for await (const chunk of toIterator(this.#parts, false)) {
150 + data.set(chunk, offset)
151 + offset += chunk.length
152 + }
153 +
154 + return data.buffer
155 + }
156 +
157 + stream () {
158 + const it = toIterator(this.#parts, true)
159 +
160 + return new globalThis.ReadableStream({
161 + // @ts-ignore
162 + type: 'bytes',
163 + async pull (ctrl) {
164 + const chunk = await it.next()
165 + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value)
166 + },
167 +
168 + async cancel () {
169 + await it.return()
170 + }
171 + })
172 + }
173 +
174 + /**
175 + * The Blob interface's slice() method creates and returns a
176 + * new Blob object which contains data from a subset of the
177 + * blob on which it's called.
178 + *
179 + * @param {number} [start]
180 + * @param {number} [end]
181 + * @param {string} [type]
182 + */
183 + slice (start = 0, end = this.size, type = '') {
184 + const { size } = this
185 +
186 + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size)
187 + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size)
188 +
189 + const span = Math.max(relativeEnd - relativeStart, 0)
190 + const parts = this.#parts
191 + const blobParts = []
192 + let added = 0
193 +
194 + for (const part of parts) {
195 + // don't add the overflow to new blobParts
196 + if (added >= span) {
197 + break
198 + }
199 +
200 + const size = ArrayBuffer.isView(part) ? part.byteLength : part.size
201 + if (relativeStart && size <= relativeStart) {
202 + // Skip the beginning and change the relative
203 + // start & end position as we skip the unwanted parts
204 + relativeStart -= size
205 + relativeEnd -= size
206 + } else {
207 + let chunk
208 + if (ArrayBuffer.isView(part)) {
209 + chunk = part.subarray(relativeStart, Math.min(size, relativeEnd))
210 + added += chunk.byteLength
211 + } else {
212 + chunk = part.slice(relativeStart, Math.min(size, relativeEnd))
213 + added += chunk.size
214 + }
215 + relativeEnd -= size
216 + blobParts.push(chunk)
217 + relativeStart = 0 // All next sequential parts should start at 0
218 + }
219 + }
220 +
221 + const blob = new Blob([], { type: String(type).toLowerCase() })
222 + blob.#size = span
223 + blob.#parts = blobParts
224 +
225 + return blob
226 + }
227 +
228 + get [Symbol.toStringTag] () {
229 + return 'Blob'
230 + }
231 +
232 + static [Symbol.hasInstance] (object) {
233 + return (
234 + object &&
235 + typeof object === 'object' &&
236 + typeof object.constructor === 'function' &&
237 + (
238 + typeof object.stream === 'function' ||
239 + typeof object.arrayBuffer === 'function'
240 + ) &&
241 + /^(Blob|File)$/.test(object[Symbol.toStringTag])
242 + )
243 + }
244 +}
245 +
246 +Object.defineProperties(_Blob.prototype, {
247 + size: { enumerable: true },
248 + type: { enumerable: true },
249 + slice: { enumerable: true }
250 +})
251 +
252 +/** @type {typeof globalThis.Blob} */
253 +export const Blob = _Blob
254 +export default Blob
1 +{
2 + "name": "fetch-blob",
3 + "version": "3.1.5",
4 + "description": "Blob & File implementation in Node.js, originally from node-fetch.",
5 + "main": "index.js",
6 + "type": "module",
7 + "files": [
8 + "from.js",
9 + "file.js",
10 + "file.d.ts",
11 + "index.js",
12 + "index.d.ts",
13 + "from.d.ts",
14 + "streams.cjs"
15 + ],
16 + "scripts": {
17 + "test": "node --experimental-loader ./test/http-loader.js ./test/test-wpt-in-node.js",
18 + "report": "c8 --reporter json --reporter text npm run test",
19 + "coverage": "npm run report && codecov -f coverage/coverage-final.json",
20 + "prepublishOnly": "tsc --declaration --emitDeclarationOnly --allowJs index.js from.js"
21 + },
22 + "repository": "https://github.com/node-fetch/fetch-blob.git",
23 + "keywords": [
24 + "blob",
25 + "file",
26 + "node-fetch"
27 + ],
28 + "engines": {
29 + "node": "^12.20 || >= 14.13"
30 + },
31 + "author": "Jimmy Wärting <jimmy@warting.se> (https://jimmy.warting.se)",
32 + "license": "MIT",
33 + "bugs": {
34 + "url": "https://github.com/node-fetch/fetch-blob/issues"
35 + },
36 + "homepage": "https://github.com/node-fetch/fetch-blob#readme",
37 + "devDependencies": {
38 + "@types/node": "^17.0.9",
39 + "c8": "^7.11.0",
40 + "typescript": "^4.5.4"
41 + },
42 + "funding": [
43 + {
44 + "type": "github",
45 + "url": "https://github.com/sponsors/jimmywarting"
46 + },
47 + {
48 + "type": "paypal",
49 + "url": "https://paypal.me/jimmywarting"
50 + }
51 + ],
52 + "dependencies": {
53 + "node-domexception": "^1.0.0",
54 + "web-streams-polyfill": "^3.0.3"
55 + }
56 +}
1 +/* c8 ignore start */
2 +// 64 KiB (same size chrome slice theirs blob into Uint8array's)
3 +const POOL_SIZE = 65536
4 +
5 +if (!globalThis.ReadableStream) {
6 + // `node:stream/web` got introduced in v16.5.0 as experimental
7 + // and it's preferred over the polyfilled version. So we also
8 + // suppress the warning that gets emitted by NodeJS for using it.
9 + try {
10 + const process = require('node:process')
11 + const { emitWarning } = process
12 + try {
13 + process.emitWarning = () => {}
14 + Object.assign(globalThis, require('node:stream/web'))
15 + process.emitWarning = emitWarning
16 + } catch (error) {
17 + process.emitWarning = emitWarning
18 + throw error
19 + }
20 + } catch (error) {
21 + // fallback to polyfill implementation
22 + Object.assign(globalThis, require('web-streams-polyfill/dist/ponyfill.es2018.js'))
23 + }
24 +}
25 +
26 +try {
27 + // Don't use node: prefix for this, require+node: is not supported until node v14.14
28 + // Only `import()` can use prefix in 12.20 and later
29 + const { Blob } = require('buffer')
30 + if (Blob && !Blob.prototype.stream) {
31 + Blob.prototype.stream = function name (params) {
32 + let position = 0
33 + const blob = this
34 +
35 + return new ReadableStream({
36 + type: 'bytes',
37 + async pull (ctrl) {
38 + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE))
39 + const buffer = await chunk.arrayBuffer()
40 + position += buffer.byteLength
41 + ctrl.enqueue(new Uint8Array(buffer))
42 +
43 + if (position === blob.size) {
44 + ctrl.close()
45 + }
46 + }
47 + })
48 + }
49 + }
50 +} catch (error) {}
51 +/* c8 ignore end */
1 -Copyright 2014–present Olivier Lalonde <olalonde@gmail.com>, James Talmage <james@talmage.io>, Ruben Verborgh
2 -
3 -Permission is hereby granted, free of charge, to any person obtaining a copy of
4 -this software and associated documentation files (the "Software"), to deal in
5 -the Software without restriction, including without limitation the rights to
6 -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 -of the Software, and to permit persons to whom the Software is furnished to do
8 -so, subject to the following conditions:
9 -
10 -The above copyright notice and this permission notice shall be included in all
11 -copies or substantial portions of the Software.
12 -
13 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
17 -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
18 -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 -## Follow Redirects
2 -
3 -Drop-in replacement for Node's `http` and `https` modules that automatically follows redirects.
4 -
5 -[![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects)
6 -[![Build Status](https://github.com/follow-redirects/follow-redirects/workflows/CI/badge.svg)](https://github.com/follow-redirects/follow-redirects/actions)
7 -[![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master)
8 -[![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects)
9 -[![Sponsor on GitHub](https://img.shields.io/static/v1?label=Sponsor&message=%F0%9F%92%96&logo=GitHub)](https://github.com/sponsors/RubenVerborgh)
10 -
11 -`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)
12 - 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)
13 - modules, with the exception that they will seamlessly follow redirects.
14 -
15 -```javascript
16 -const { http, https } = require('follow-redirects');
17 -
18 -http.get('http://bit.ly/900913', response => {
19 - response.on('data', chunk => {
20 - console.log(chunk);
21 - });
22 -}).on('error', err => {
23 - console.error(err);
24 -});
25 -```
26 -
27 -You can inspect the final redirected URL through the `responseUrl` property on the `response`.
28 -If no redirection happened, `responseUrl` is the original request URL.
29 -
30 -```javascript
31 -const request = https.request({
32 - host: 'bitly.com',
33 - path: '/UHfDGO',
34 -}, response => {
35 - console.log(response.responseUrl);
36 - // 'http://duckduckgo.com/robots.txt'
37 -});
38 -request.end();
39 -```
40 -
41 -## Options
42 -### Global options
43 -Global options are set directly on the `follow-redirects` module:
44 -
45 -```javascript
46 -const followRedirects = require('follow-redirects');
47 -followRedirects.maxRedirects = 10;
48 -followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB
49 -```
50 -
51 -The following global options are supported:
52 -
53 -- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.
54 -
55 -- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.
56 -
57 -### Per-request options
58 -Per-request options are set by passing an `options` object:
59 -
60 -```javascript
61 -const url = require('url');
62 -const { http, https } = require('follow-redirects');
63 -
64 -const options = url.parse('http://bit.ly/900913');
65 -options.maxRedirects = 10;
66 -options.beforeRedirect = (options, response, request) => {
67 - // Use this to adjust the request options upon redirecting,
68 - // to inspect the latest response headers,
69 - // or to cancel the request by throwing an error
70 -
71 - // response.headers = the redirect response headers
72 - // response.statusCode = the redirect response code (eg. 301, 307, etc.)
73 -
74 - // request.url = the requested URL that resulted in a redirect
75 - // request.headers = the headers in the request that resulted in a redirect
76 - // request.method = the method of the request that resulted in a redirect
77 - if (options.hostname === "example.com") {
78 - options.auth = "user:password";
79 - }
80 -};
81 -http.request(options);
82 -```
83 -
84 -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),
85 -the following per-request options are supported:
86 -- `followRedirects` (default: `true`) – whether redirects should be followed.
87 -
88 -- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.
89 -
90 -- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.
91 -
92 -- `beforeRedirect` (default: `undefined`) – optionally change the request `options` on redirects, or abort the request by throwing an error.
93 -
94 -- `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() }`
95 -
96 -- `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object.
97 -
98 -
99 -### Advanced usage
100 -By default, `follow-redirects` will use the Node.js default implementations
101 -of [`http`](https://nodejs.org/api/http.html)
102 -and [`https`](https://nodejs.org/api/https.html).
103 -To enable features such as caching and/or intermediate request tracking,
104 -you might instead want to wrap `follow-redirects` around custom protocol implementations:
105 -
106 -```javascript
107 -const { http, https } = require('follow-redirects').wrap({
108 - http: require('your-custom-http'),
109 - https: require('your-custom-https'),
110 -});
111 -```
112 -
113 -Such custom protocols only need an implementation of the `request` method.
114 -
115 -## Browser Usage
116 -
117 -Due to the way the browser works,
118 -the `http` and `https` browser equivalents perform redirects by default.
119 -
120 -By requiring `follow-redirects` this way:
121 -```javascript
122 -const http = require('follow-redirects/http');
123 -const https = require('follow-redirects/https');
124 -```
125 -you can easily tell webpack and friends to replace
126 -`follow-redirect` by the built-in versions:
127 -
128 -```json
129 -{
130 - "follow-redirects/http" : "http",
131 - "follow-redirects/https" : "https"
132 -}
133 -```
134 -
135 -## Contributing
136 -
137 -Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues)
138 - detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied
139 - by tests. You can run the test suite locally with a simple `npm test` command.
140 -
141 -## Debug Logging
142 -
143 -`follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging
144 - set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test
145 - suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well.
146 -
147 -## Authors
148 -
149 -- [Ruben Verborgh](https://ruben.verborgh.org/)
150 -- [Olivier Lalonde](mailto:olalonde@gmail.com)
151 -- [James Talmage](mailto:james@talmage.io)
152 -
153 -## License
154 -
155 -[MIT License](https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE)
1 -var debug;
2 -
3 -module.exports = function () {
4 - if (!debug) {
5 - try {
6 - /* eslint global-require: off */
7 - debug = require("debug")("follow-redirects");
8 - }
9 - catch (error) { /* */ }
10 - if (typeof debug !== "function") {
11 - debug = function () { /* */ };
12 - }
13 - }
14 - debug.apply(null, arguments);
15 -};
1 -module.exports = require("./").http;
1 -module.exports = require("./").https;
1 -var url = require("url");
2 -var URL = url.URL;
3 -var http = require("http");
4 -var https = require("https");
5 -var Writable = require("stream").Writable;
6 -var assert = require("assert");
7 -var debug = require("./debug");
8 -
9 -// Create handlers that pass events from native requests
10 -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
11 -var eventHandlers = Object.create(null);
12 -events.forEach(function (event) {
13 - eventHandlers[event] = function (arg1, arg2, arg3) {
14 - this._redirectable.emit(event, arg1, arg2, arg3);
15 - };
16 -});
17 -
18 -// Error types with codes
19 -var RedirectionError = createErrorType(
20 - "ERR_FR_REDIRECTION_FAILURE",
21 - "Redirected request failed"
22 -);
23 -var TooManyRedirectsError = createErrorType(
24 - "ERR_FR_TOO_MANY_REDIRECTS",
25 - "Maximum number of redirects exceeded"
26 -);
27 -var MaxBodyLengthExceededError = createErrorType(
28 - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
29 - "Request body larger than maxBodyLength limit"
30 -);
31 -var WriteAfterEndError = createErrorType(
32 - "ERR_STREAM_WRITE_AFTER_END",
33 - "write after end"
34 -);
35 -
36 -// An HTTP(S) request that can be redirected
37 -function RedirectableRequest(options, responseCallback) {
38 - // Initialize the request
39 - Writable.call(this);
40 - this._sanitizeOptions(options);
41 - this._options = options;
42 - this._ended = false;
43 - this._ending = false;
44 - this._redirectCount = 0;
45 - this._redirects = [];
46 - this._requestBodyLength = 0;
47 - this._requestBodyBuffers = [];
48 -
49 - // Attach a callback if passed
50 - if (responseCallback) {
51 - this.on("response", responseCallback);
52 - }
53 -
54 - // React to responses of native requests
55 - var self = this;
56 - this._onNativeResponse = function (response) {
57 - self._processResponse(response);
58 - };
59 -
60 - // Perform the first request
61 - this._performRequest();
62 -}
63 -RedirectableRequest.prototype = Object.create(Writable.prototype);
64 -
65 -RedirectableRequest.prototype.abort = function () {
66 - abortRequest(this._currentRequest);
67 - this.emit("abort");
68 -};
69 -
70 -// Writes buffered data to the current native request
71 -RedirectableRequest.prototype.write = function (data, encoding, callback) {
72 - // Writing is not allowed if end has been called
73 - if (this._ending) {
74 - throw new WriteAfterEndError();
75 - }
76 -
77 - // Validate input and shift parameters if necessary
78 - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
79 - throw new TypeError("data should be a string, Buffer or Uint8Array");
80 - }
81 - if (typeof encoding === "function") {
82 - callback = encoding;
83 - encoding = null;
84 - }
85 -
86 - // Ignore empty buffers, since writing them doesn't invoke the callback
87 - // https://github.com/nodejs/node/issues/22066
88 - if (data.length === 0) {
89 - if (callback) {
90 - callback();
91 - }
92 - return;
93 - }
94 - // Only write when we don't exceed the maximum body length
95 - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
96 - this._requestBodyLength += data.length;
97 - this._requestBodyBuffers.push({ data: data, encoding: encoding });
98 - this._currentRequest.write(data, encoding, callback);
99 - }
100 - // Error when we exceed the maximum body length
101 - else {
102 - this.emit("error", new MaxBodyLengthExceededError());
103 - this.abort();
104 - }
105 -};
106 -
107 -// Ends the current native request
108 -RedirectableRequest.prototype.end = function (data, encoding, callback) {
109 - // Shift parameters if necessary
110 - if (typeof data === "function") {
111 - callback = data;
112 - data = encoding = null;
113 - }
114 - else if (typeof encoding === "function") {
115 - callback = encoding;
116 - encoding = null;
117 - }
118 -
119 - // Write data if needed and end
120 - if (!data) {
121 - this._ended = this._ending = true;
122 - this._currentRequest.end(null, null, callback);
123 - }
124 - else {
125 - var self = this;
126 - var currentRequest = this._currentRequest;
127 - this.write(data, encoding, function () {
128 - self._ended = true;
129 - currentRequest.end(null, null, callback);
130 - });
131 - this._ending = true;
132 - }
133 -};
134 -
135 -// Sets a header value on the current native request
136 -RedirectableRequest.prototype.setHeader = function (name, value) {
137 - this._options.headers[name] = value;
138 - this._currentRequest.setHeader(name, value);
139 -};
140 -
141 -// Clears a header value on the current native request
142 -RedirectableRequest.prototype.removeHeader = function (name) {
143 - delete this._options.headers[name];
144 - this._currentRequest.removeHeader(name);
145 -};
146 -
147 -// Global timeout for all underlying requests
148 -RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
149 - var self = this;
150 -
151 - // Destroys the socket on timeout
152 - function destroyOnTimeout(socket) {
153 - socket.setTimeout(msecs);
154 - socket.removeListener("timeout", socket.destroy);
155 - socket.addListener("timeout", socket.destroy);
156 - }
157 -
158 - // Sets up a timer to trigger a timeout event
159 - function startTimer(socket) {
160 - if (self._timeout) {
161 - clearTimeout(self._timeout);
162 - }
163 - self._timeout = setTimeout(function () {
164 - self.emit("timeout");
165 - clearTimer();
166 - }, msecs);
167 - destroyOnTimeout(socket);
168 - }
169 -
170 - // Stops a timeout from triggering
171 - function clearTimer() {
172 - // Clear the timeout
173 - if (self._timeout) {
174 - clearTimeout(self._timeout);
175 - self._timeout = null;
176 - }
177 -
178 - // Clean up all attached listeners
179 - self.removeListener("abort", clearTimer);
180 - self.removeListener("error", clearTimer);
181 - self.removeListener("response", clearTimer);
182 - if (callback) {
183 - self.removeListener("timeout", callback);
184 - }
185 - if (!self.socket) {
186 - self._currentRequest.removeListener("socket", startTimer);
187 - }
188 - }
189 -
190 - // Attach callback if passed
191 - if (callback) {
192 - this.on("timeout", callback);
193 - }
194 -
195 - // Start the timer if or when the socket is opened
196 - if (this.socket) {
197 - startTimer(this.socket);
198 - }
199 - else {
200 - this._currentRequest.once("socket", startTimer);
201 - }
202 -
203 - // Clean up on events
204 - this.on("socket", destroyOnTimeout);
205 - this.on("abort", clearTimer);
206 - this.on("error", clearTimer);
207 - this.on("response", clearTimer);
208 -
209 - return this;
210 -};
211 -
212 -// Proxy all other public ClientRequest methods
213 -[
214 - "flushHeaders", "getHeader",
215 - "setNoDelay", "setSocketKeepAlive",
216 -].forEach(function (method) {
217 - RedirectableRequest.prototype[method] = function (a, b) {
218 - return this._currentRequest[method](a, b);
219 - };
220 -});
221 -
222 -// Proxy all public ClientRequest properties
223 -["aborted", "connection", "socket"].forEach(function (property) {
224 - Object.defineProperty(RedirectableRequest.prototype, property, {
225 - get: function () { return this._currentRequest[property]; },
226 - });
227 -});
228 -
229 -RedirectableRequest.prototype._sanitizeOptions = function (options) {
230 - // Ensure headers are always present
231 - if (!options.headers) {
232 - options.headers = {};
233 - }
234 -
235 - // Since http.request treats host as an alias of hostname,
236 - // but the url module interprets host as hostname plus port,
237 - // eliminate the host property to avoid confusion.
238 - if (options.host) {
239 - // Use hostname if set, because it has precedence
240 - if (!options.hostname) {
241 - options.hostname = options.host;
242 - }
243 - delete options.host;
244 - }
245 -
246 - // Complete the URL object when necessary
247 - if (!options.pathname && options.path) {
248 - var searchPos = options.path.indexOf("?");
249 - if (searchPos < 0) {
250 - options.pathname = options.path;
251 - }
252 - else {
253 - options.pathname = options.path.substring(0, searchPos);
254 - options.search = options.path.substring(searchPos);
255 - }
256 - }
257 -};
258 -
259 -
260 -// Executes the next native request (initial or redirect)
261 -RedirectableRequest.prototype._performRequest = function () {
262 - // Load the native protocol
263 - var protocol = this._options.protocol;
264 - var nativeProtocol = this._options.nativeProtocols[protocol];
265 - if (!nativeProtocol) {
266 - this.emit("error", new TypeError("Unsupported protocol " + protocol));
267 - return;
268 - }
269 -
270 - // If specified, use the agent corresponding to the protocol
271 - // (HTTP and HTTPS use different types of agents)
272 - if (this._options.agents) {
273 - var scheme = protocol.slice(0, -1);
274 - this._options.agent = this._options.agents[scheme];
275 - }
276 -
277 - // Create the native request and set up its event handlers
278 - var request = this._currentRequest =
279 - nativeProtocol.request(this._options, this._onNativeResponse);
280 - request._redirectable = this;
281 - for (var event of events) {
282 - request.on(event, eventHandlers[event]);
283 - }
284 -
285 - // RFC7230§5.3.1: When making a request directly to an origin server, […]
286 - // a client MUST send only the absolute path […] as the request-target.
287 - this._currentUrl = /^\//.test(this._options.path) ?
288 - url.format(this._options) :
289 - // When making a request to a proxy, […]
290 - // a client MUST send the target URI in absolute-form […].
291 - this._currentUrl = this._options.path;
292 -
293 - // End a redirected request
294 - // (The first request must be ended explicitly with RedirectableRequest#end)
295 - if (this._isRedirect) {
296 - // Write the request entity and end
297 - var i = 0;
298 - var self = this;
299 - var buffers = this._requestBodyBuffers;
300 - (function writeNext(error) {
301 - // Only write if this request has not been redirected yet
302 - /* istanbul ignore else */
303 - if (request === self._currentRequest) {
304 - // Report any write errors
305 - /* istanbul ignore if */
306 - if (error) {
307 - self.emit("error", error);
308 - }
309 - // Write the next buffer if there are still left
310 - else if (i < buffers.length) {
311 - var buffer = buffers[i++];
312 - /* istanbul ignore else */
313 - if (!request.finished) {
314 - request.write(buffer.data, buffer.encoding, writeNext);
315 - }
316 - }
317 - // End the request if `end` has been called on us
318 - else if (self._ended) {
319 - request.end();
320 - }
321 - }
322 - }());
323 - }
324 -};
325 -
326 -// Processes a response from the current native request
327 -RedirectableRequest.prototype._processResponse = function (response) {
328 - // Store the redirected response
329 - var statusCode = response.statusCode;
330 - if (this._options.trackRedirects) {
331 - this._redirects.push({
332 - url: this._currentUrl,
333 - headers: response.headers,
334 - statusCode: statusCode,
335 - });
336 - }
337 -
338 - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
339 - // that further action needs to be taken by the user agent in order to
340 - // fulfill the request. If a Location header field is provided,
341 - // the user agent MAY automatically redirect its request to the URI
342 - // referenced by the Location field value,
343 - // even if the specific status code is not understood.
344 -
345 - // If the response is not a redirect; return it as-is
346 - var location = response.headers.location;
347 - if (!location || this._options.followRedirects === false ||
348 - statusCode < 300 || statusCode >= 400) {
349 - response.responseUrl = this._currentUrl;
350 - response.redirects = this._redirects;
351 - this.emit("response", response);
352 -
353 - // Clean up
354 - this._requestBodyBuffers = [];
355 - return;
356 - }
357 -
358 - // The response is a redirect, so abort the current request
359 - abortRequest(this._currentRequest);
360 - // Discard the remainder of the response to avoid waiting for data
361 - response.destroy();
362 -
363 - // RFC7231§6.4: A client SHOULD detect and intervene
364 - // in cyclical redirections (i.e., "infinite" redirection loops).
365 - if (++this._redirectCount > this._options.maxRedirects) {
366 - this.emit("error", new TooManyRedirectsError());
367 - return;
368 - }
369 -
370 - // Store the request headers if applicable
371 - var requestHeaders;
372 - var beforeRedirect = this._options.beforeRedirect;
373 - if (beforeRedirect) {
374 - requestHeaders = Object.assign({
375 - // The Host header was set by nativeProtocol.request
376 - Host: response.req.getHeader("host"),
377 - }, this._options.headers);
378 - }
379 -
380 - // RFC7231§6.4: Automatic redirection needs to done with
381 - // care for methods not known to be safe, […]
382 - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
383 - // the request method from POST to GET for the subsequent request.
384 - var method = this._options.method;
385 - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
386 - // RFC7231§6.4.4: The 303 (See Other) status code indicates that
387 - // the server is redirecting the user agent to a different resource […]
388 - // A user agent can perform a retrieval request targeting that URI
389 - // (a GET or HEAD request if using HTTP) […]
390 - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
391 - this._options.method = "GET";
392 - // Drop a possible entity and headers related to it
393 - this._requestBodyBuffers = [];
394 - removeMatchingHeaders(/^content-/i, this._options.headers);
395 - }
396 -
397 - // Drop the Host header, as the redirect might lead to a different host
398 - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
399 -
400 - // If the redirect is relative, carry over the host of the last request
401 - var currentUrlParts = url.parse(this._currentUrl);
402 - var currentHost = currentHostHeader || currentUrlParts.host;
403 - var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
404 - url.format(Object.assign(currentUrlParts, { host: currentHost }));
405 -
406 - // Determine the URL of the redirection
407 - var redirectUrl;
408 - try {
409 - redirectUrl = url.resolve(currentUrl, location);
410 - }
411 - catch (cause) {
412 - this.emit("error", new RedirectionError(cause));
413 - return;
414 - }
415 -
416 - // Create the redirected request
417 - debug("redirecting to", redirectUrl);
418 - this._isRedirect = true;
419 - var redirectUrlParts = url.parse(redirectUrl);
420 - Object.assign(this._options, redirectUrlParts);
421 -
422 - // Drop confidential headers when redirecting to a less secure protocol
423 - // or to a different domain that is not a superdomain
424 - if (redirectUrlParts.protocol !== currentUrlParts.protocol &&
425 - redirectUrlParts.protocol !== "https:" ||
426 - redirectUrlParts.host !== currentHost &&
427 - !isSubdomain(redirectUrlParts.host, currentHost)) {
428 - removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
429 - }
430 -
431 - // Evaluate the beforeRedirect callback
432 - if (typeof beforeRedirect === "function") {
433 - var responseDetails = {
434 - headers: response.headers,
435 - statusCode: statusCode,
436 - };
437 - var requestDetails = {
438 - url: currentUrl,
439 - method: method,
440 - headers: requestHeaders,
441 - };
442 - try {
443 - beforeRedirect(this._options, responseDetails, requestDetails);
444 - }
445 - catch (err) {
446 - this.emit("error", err);
447 - return;
448 - }
449 - this._sanitizeOptions(this._options);
450 - }
451 -
452 - // Perform the redirected request
453 - try {
454 - this._performRequest();
455 - }
456 - catch (cause) {
457 - this.emit("error", new RedirectionError(cause));
458 - }
459 -};
460 -
461 -// Wraps the key/value object of protocols with redirect functionality
462 -function wrap(protocols) {
463 - // Default settings
464 - var exports = {
465 - maxRedirects: 21,
466 - maxBodyLength: 10 * 1024 * 1024,
467 - };
468 -
469 - // Wrap each protocol
470 - var nativeProtocols = {};
471 - Object.keys(protocols).forEach(function (scheme) {
472 - var protocol = scheme + ":";
473 - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
474 - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
475 -
476 - // Executes a request, following redirects
477 - function request(input, options, callback) {
478 - // Parse parameters
479 - if (typeof input === "string") {
480 - var urlStr = input;
481 - try {
482 - input = urlToOptions(new URL(urlStr));
483 - }
484 - catch (err) {
485 - /* istanbul ignore next */
486 - input = url.parse(urlStr);
487 - }
488 - }
489 - else if (URL && (input instanceof URL)) {
490 - input = urlToOptions(input);
491 - }
492 - else {
493 - callback = options;
494 - options = input;
495 - input = { protocol: protocol };
496 - }
497 - if (typeof options === "function") {
498 - callback = options;
499 - options = null;
500 - }
501 -
502 - // Set defaults
503 - options = Object.assign({
504 - maxRedirects: exports.maxRedirects,
505 - maxBodyLength: exports.maxBodyLength,
506 - }, input, options);
507 - options.nativeProtocols = nativeProtocols;
508 -
509 - assert.equal(options.protocol, protocol, "protocol mismatch");
510 - debug("options", options);
511 - return new RedirectableRequest(options, callback);
512 - }
513 -
514 - // Executes a GET request, following redirects
515 - function get(input, options, callback) {
516 - var wrappedRequest = wrappedProtocol.request(input, options, callback);
517 - wrappedRequest.end();
518 - return wrappedRequest;
519 - }
520 -
521 - // Expose the properties on the wrapped protocol
522 - Object.defineProperties(wrappedProtocol, {
523 - request: { value: request, configurable: true, enumerable: true, writable: true },
524 - get: { value: get, configurable: true, enumerable: true, writable: true },
525 - });
526 - });
527 - return exports;
528 -}
529 -
530 -/* istanbul ignore next */
531 -function noop() { /* empty */ }
532 -
533 -// from https://github.com/nodejs/node/blob/master/lib/internal/url.js
534 -function urlToOptions(urlObject) {
535 - var options = {
536 - protocol: urlObject.protocol,
537 - hostname: urlObject.hostname.startsWith("[") ?
538 - /* istanbul ignore next */
539 - urlObject.hostname.slice(1, -1) :
540 - urlObject.hostname,
541 - hash: urlObject.hash,
542 - search: urlObject.search,
543 - pathname: urlObject.pathname,
544 - path: urlObject.pathname + urlObject.search,
545 - href: urlObject.href,
546 - };
547 - if (urlObject.port !== "") {
548 - options.port = Number(urlObject.port);
549 - }
550 - return options;
551 -}
552 -
553 -function removeMatchingHeaders(regex, headers) {
554 - var lastValue;
555 - for (var header in headers) {
556 - if (regex.test(header)) {
557 - lastValue = headers[header];
558 - delete headers[header];
559 - }
560 - }
561 - return (lastValue === null || typeof lastValue === "undefined") ?
562 - undefined : String(lastValue).trim();
563 -}
564 -
565 -function createErrorType(code, defaultMessage) {
566 - function CustomError(cause) {
567 - Error.captureStackTrace(this, this.constructor);
568 - if (!cause) {
569 - this.message = defaultMessage;
570 - }
571 - else {
572 - this.message = defaultMessage + ": " + cause.message;
573 - this.cause = cause;
574 - }
575 - }
576 - CustomError.prototype = new Error();
577 - CustomError.prototype.constructor = CustomError;
578 - CustomError.prototype.name = "Error [" + code + "]";
579 - CustomError.prototype.code = code;
580 - return CustomError;
581 -}
582 -
583 -function abortRequest(request) {
584 - for (var event of events) {
585 - request.removeListener(event, eventHandlers[event]);
586 - }
587 - request.on("error", noop);
588 - request.abort();
589 -}
590 -
591 -function isSubdomain(subdomain, domain) {
592 - const dot = subdomain.length - domain.length - 1;
593 - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
594 -}
595 -
596 -// Exports
597 -module.exports = wrap({ http: http, https: https });
598 -module.exports.wrap = wrap;
1 -{
2 - "name": "follow-redirects",
3 - "version": "1.15.1",
4 - "description": "HTTP and HTTPS modules that follow redirects.",
5 - "license": "MIT",
6 - "main": "index.js",
7 - "files": [
8 - "*.js"
9 - ],
10 - "engines": {
11 - "node": ">=4.0"
12 - },
13 - "scripts": {
14 - "test": "npm run lint && npm run mocha",
15 - "lint": "eslint *.js test",
16 - "mocha": "nyc mocha"
17 - },
18 - "repository": {
19 - "type": "git",
20 - "url": "git@github.com:follow-redirects/follow-redirects.git"
21 - },
22 - "homepage": "https://github.com/follow-redirects/follow-redirects",
23 - "bugs": {
24 - "url": "https://github.com/follow-redirects/follow-redirects/issues"
25 - },
26 - "keywords": [
27 - "http",
28 - "https",
29 - "url",
30 - "redirect",
31 - "client",
32 - "location",
33 - "utility"
34 - ],
35 - "author": "Ruben Verborgh <ruben@verborgh.org> (https://ruben.verborgh.org/)",
36 - "contributors": [
37 - "Olivier Lalonde <olalonde@gmail.com> (http://www.syskall.com)",
38 - "James Talmage <james@talmage.io>"
39 - ],
40 - "funding": [
41 - {
42 - "type": "individual",
43 - "url": "https://github.com/sponsors/RubenVerborgh"
44 - }
45 - ],
46 - "peerDependenciesMeta": {
47 - "debug": {
48 - "optional": true
49 - }
50 - },
51 - "devDependencies": {
52 - "concat-stream": "^2.0.0",
53 - "eslint": "^5.16.0",
54 - "express": "^4.16.4",
55 - "lolex": "^3.1.0",
56 - "mocha": "^6.0.2",
57 - "nyc": "^14.1.1"
58 - }
59 -}
1 -# Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data)
2 -
3 -A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications.
4 -
5 -The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd].
6 -
7 -[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface
8 -
9 -[![Linux Build](https://img.shields.io/travis/form-data/form-data/v4.0.0.svg?label=linux:6.x-12.x)](https://travis-ci.org/form-data/form-data)
10 -[![MacOS Build](https://img.shields.io/travis/form-data/form-data/v4.0.0.svg?label=macos:6.x-12.x)](https://travis-ci.org/form-data/form-data)
11 -[![Windows Build](https://img.shields.io/travis/form-data/form-data/v4.0.0.svg?label=windows:6.x-12.x)](https://travis-ci.org/form-data/form-data)
12 -
13 -[![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/v4.0.0.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master)
14 -[![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data)
15 -
16 -## Install
17 -
18 -```
19 -npm install --save form-data
20 -```
21 -
22 -## Usage
23 -
24 -In this example we are constructing a form with 3 fields that contain a string,
25 -a buffer and a file stream.
26 -
27 -``` javascript
28 -var FormData = require('form-data');
29 -var fs = require('fs');
30 -
31 -var form = new FormData();
32 -form.append('my_field', 'my value');
33 -form.append('my_buffer', new Buffer(10));
34 -form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
35 -```
36 -
37 -Also you can use http-response stream:
38 -
39 -``` javascript
40 -var FormData = require('form-data');
41 -var http = require('http');
42 -
43 -var form = new FormData();
44 -
45 -http.request('http://nodejs.org/images/logo.png', function(response) {
46 - form.append('my_field', 'my value');
47 - form.append('my_buffer', new Buffer(10));
48 - form.append('my_logo', response);
49 -});
50 -```
51 -
52 -Or @mikeal's [request](https://github.com/request/request) stream:
53 -
54 -``` javascript
55 -var FormData = require('form-data');
56 -var request = require('request');
57 -
58 -var form = new FormData();
59 -
60 -form.append('my_field', 'my value');
61 -form.append('my_buffer', new Buffer(10));
62 -form.append('my_logo', request('http://nodejs.org/images/logo.png'));
63 -```
64 -
65 -In order to submit this form to a web application, call ```submit(url, [callback])``` method:
66 -
67 -``` javascript
68 -form.submit('http://example.org/', function(err, res) {
69 - // res – response object (http.IncomingMessage) //
70 - res.resume();
71 -});
72 -
73 -```
74 -
75 -For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods.
76 -
77 -### Custom options
78 -
79 -You can provide custom options, such as `maxDataSize`:
80 -
81 -``` javascript
82 -var FormData = require('form-data');
83 -
84 -var form = new FormData({ maxDataSize: 20971520 });
85 -form.append('my_field', 'my value');
86 -form.append('my_buffer', /* something big */);
87 -```
88 -
89 -List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15)
90 -
91 -### Alternative submission methods
92 -
93 -You can use node's http client interface:
94 -
95 -``` javascript
96 -var http = require('http');
97 -
98 -var request = http.request({
99 - method: 'post',
100 - host: 'example.org',
101 - path: '/upload',
102 - headers: form.getHeaders()
103 -});
104 -
105 -form.pipe(request);
106 -
107 -request.on('response', function(res) {
108 - console.log(res.statusCode);
109 -});
110 -```
111 -
112 -Or if you would prefer the `'Content-Length'` header to be set for you:
113 -
114 -``` javascript
115 -form.submit('example.org/upload', function(err, res) {
116 - console.log(res.statusCode);
117 -});
118 -```
119 -
120 -To use custom headers and pre-known length in parts:
121 -
122 -``` javascript
123 -var CRLF = '\r\n';
124 -var form = new FormData();
125 -
126 -var options = {
127 - header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
128 - knownLength: 1
129 -};
130 -
131 -form.append('my_buffer', buffer, options);
132 -
133 -form.submit('http://example.com/', function(err, res) {
134 - if (err) throw err;
135 - console.log('Done');
136 -});
137 -```
138 -
139 -Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually:
140 -
141 -``` javascript
142 -someModule.stream(function(err, stdout, stderr) {
143 - if (err) throw err;
144 -
145 - var form = new FormData();
146 -
147 - form.append('file', stdout, {
148 - filename: 'unicycle.jpg', // ... or:
149 - filepath: 'photos/toys/unicycle.jpg',
150 - contentType: 'image/jpeg',
151 - knownLength: 19806
152 - });
153 -
154 - form.submit('http://example.com/', function(err, res) {
155 - if (err) throw err;
156 - console.log('Done');
157 - });
158 -});
159 -```
160 -
161 -The `filepath` property overrides `filename` and may contain a relative path. This is typically used when uploading [multiple files from a directory](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory).
162 -
163 -For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter:
164 -
165 -``` javascript
166 -form.submit({
167 - host: 'example.com',
168 - path: '/probably.php?extra=params',
169 - auth: 'username:password'
170 -}, function(err, res) {
171 - console.log(res.statusCode);
172 -});
173 -```
174 -
175 -In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`:
176 -
177 -``` javascript
178 -form.submit({
179 - host: 'example.com',
180 - path: '/surelynot.php',
181 - headers: {'x-test-header': 'test-header-value'}
182 -}, function(err, res) {
183 - console.log(res.statusCode);
184 -});
185 -```
186 -
187 -### Methods
188 -
189 -- [_Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )](https://github.com/form-data/form-data#void-append-string-field-mixed-value--mixed-options-).
190 -- [_Headers_ getHeaders( [**Headers** _userHeaders_] )](https://github.com/form-data/form-data#array-getheaders-array-userheaders-)
191 -- [_String_ getBoundary()](https://github.com/form-data/form-data#string-getboundary)
192 -- [_Void_ setBoundary()](https://github.com/form-data/form-data#void-setboundary)
193 -- [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer)
194 -- [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync)
195 -- [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-)
196 -- [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength)
197 -- [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-)
198 -- [_String_ toString()](https://github.com/form-data/form-data#string-tostring)
199 -
200 -#### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )
201 -Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user.
202 -```javascript
203 -var form = new FormData();
204 -form.append( 'my_string', 'my value' );
205 -form.append( 'my_integer', 1 );
206 -form.append( 'my_boolean', true );
207 -form.append( 'my_buffer', new Buffer(10) );
208 -form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) )
209 -```
210 -
211 -You may provide a string for options, or an object.
212 -```javascript
213 -// Set filename by providing a string for options
214 -form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' );
215 -
216 -// provide an object.
217 -form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} );
218 -```
219 -
220 -#### _Headers_ getHeaders( [**Headers** _userHeaders_] )
221 -This method adds the correct `content-type` header to the provided array of `userHeaders`.
222 -
223 -#### _String_ getBoundary()
224 -Return the boundary of the formData. By default, the boundary consists of 26 `-` followed by 24 numbers
225 -for example:
226 -```javascript
227 ---------------------------515890814546601021194782
228 -```
229 -
230 -#### _Void_ setBoundary(String _boundary_)
231 -Set the boundary string, overriding the default behavior described above.
232 -
233 -_Note: The boundary must be unique and may not appear in the data._
234 -
235 -#### _Buffer_ getBuffer()
236 -Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.
237 -```javascript
238 -var form = new FormData();
239 -form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) );
240 -form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') );
241 -
242 -axios.post( 'https://example.com/path/to/api',
243 - form.getBuffer(),
244 - form.getHeaders()
245 - )
246 -```
247 -**Note:** Because the output is of type Buffer, you can only append types that are accepted by Buffer: *string, Buffer, ArrayBuffer, Array, or Array-like Object*. A ReadStream for example will result in an error.
248 -
249 -#### _Integer_ getLengthSync()
250 -Same as `getLength` but synchronous.
251 -
252 -_Note: getLengthSync __doesn't__ calculate streams length._
253 -
254 -#### _Integer_ getLength( **function** _callback_ )
255 -Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated
256 -```javascript
257 -this.getLength(function(err, length) {
258 - if (err) {
259 - this._error(err);
260 - return;
261 - }
262 -
263 - // add content length
264 - request.setHeader('Content-Length', length);
265 -
266 - ...
267 -}.bind(this));
268 -```
269 -
270 -#### _Boolean_ hasKnownLength()
271 -Checks if the length of added values is known.
272 -
273 -#### _Request_ submit( _params_, **function** _callback_ )
274 -Submit the form to a web application.
275 -```javascript
276 -var form = new FormData();
277 -form.append( 'my_string', 'Hello World' );
278 -
279 -form.submit( 'http://example.com/', function(err, res) {
280 - // res – response object (http.IncomingMessage) //
281 - res.resume();
282 -} );
283 -```
284 -
285 -#### _String_ toString()
286 -Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead.
287 -
288 -### Integration with other libraries
289 -
290 -#### Request
291 -
292 -Form submission using [request](https://github.com/request/request):
293 -
294 -```javascript
295 -var formData = {
296 - my_field: 'my_value',
297 - my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
298 -};
299 -
300 -request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
301 - if (err) {
302 - return console.error('upload failed:', err);
303 - }
304 - console.log('Upload successful! Server responded with:', body);
305 -});
306 -```
307 -
308 -For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads).
309 -
310 -#### node-fetch
311 -
312 -You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch):
313 -
314 -```javascript
315 -var form = new FormData();
316 -
317 -form.append('a', 1);
318 -
319 -fetch('http://example.com', { method: 'POST', body: form })
320 - .then(function(res) {
321 - return res.json();
322 - }).then(function(json) {
323 - console.log(json);
324 - });
325 -```
326 -
327 -#### axios
328 -
329 -In Node.js you can post a file using [axios](https://github.com/axios/axios):
330 -```javascript
331 -const form = new FormData();
332 -const stream = fs.createReadStream(PATH_TO_FILE);
333 -
334 -form.append('image', stream);
335 -
336 -// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
337 -const formHeaders = form.getHeaders();
338 -
339 -axios.post('http://example.com', form, {
340 - headers: {
341 - ...formHeaders,
342 - },
343 -})
344 -.then(response => response)
345 -.catch(error => error)
346 -```
347 -
348 -## Notes
349 -
350 -- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround.
351 -- ```getLength(cb)``` will send an error as first parameter of callback if stream length cannot be calculated (e.g. send in custom streams w/o using ```knownLength```).
352 -- ```submit``` will not add `content-length` if form length is unknown or not calculable.
353 -- Starting version `2.x` FormData has dropped support for `node@0.10.x`.
354 -- Starting version `3.x` FormData has dropped support for `node@4.x`.
355 -
356 -## License
357 -
358 -Form-Data is released under the [MIT](License) license.
1 -# Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data)
2 -
3 -A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications.
4 -
5 -The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd].
6 -
7 -[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface
8 -
9 -[![Linux Build](https://img.shields.io/travis/form-data/form-data/v4.0.0.svg?label=linux:6.x-12.x)](https://travis-ci.org/form-data/form-data)
10 -[![MacOS Build](https://img.shields.io/travis/form-data/form-data/v4.0.0.svg?label=macos:6.x-12.x)](https://travis-ci.org/form-data/form-data)
11 -[![Windows Build](https://img.shields.io/travis/form-data/form-data/v4.0.0.svg?label=windows:6.x-12.x)](https://travis-ci.org/form-data/form-data)
12 -
13 -[![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/v4.0.0.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master)
14 -[![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data)
15 -
16 -## Install
17 -
18 -```
19 -npm install --save form-data
20 -```
21 -
22 -## Usage
23 -
24 -In this example we are constructing a form with 3 fields that contain a string,
25 -a buffer and a file stream.
26 -
27 -``` javascript
28 -var FormData = require('form-data');
29 -var fs = require('fs');
30 -
31 -var form = new FormData();
32 -form.append('my_field', 'my value');
33 -form.append('my_buffer', new Buffer(10));
34 -form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
35 -```
36 -
37 -Also you can use http-response stream:
38 -
39 -``` javascript
40 -var FormData = require('form-data');
41 -var http = require('http');
42 -
43 -var form = new FormData();
44 -
45 -http.request('http://nodejs.org/images/logo.png', function(response) {
46 - form.append('my_field', 'my value');
47 - form.append('my_buffer', new Buffer(10));
48 - form.append('my_logo', response);
49 -});
50 -```
51 -
52 -Or @mikeal's [request](https://github.com/request/request) stream:
53 -
54 -``` javascript
55 -var FormData = require('form-data');
56 -var request = require('request');
57 -
58 -var form = new FormData();
59 -
60 -form.append('my_field', 'my value');
61 -form.append('my_buffer', new Buffer(10));
62 -form.append('my_logo', request('http://nodejs.org/images/logo.png'));
63 -```
64 -
65 -In order to submit this form to a web application, call ```submit(url, [callback])``` method:
66 -
67 -``` javascript
68 -form.submit('http://example.org/', function(err, res) {
69 - // res – response object (http.IncomingMessage) //
70 - res.resume();
71 -});
72 -
73 -```
74 -
75 -For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods.
76 -
77 -### Custom options
78 -
79 -You can provide custom options, such as `maxDataSize`:
80 -
81 -``` javascript
82 -var FormData = require('form-data');
83 -
84 -var form = new FormData({ maxDataSize: 20971520 });
85 -form.append('my_field', 'my value');
86 -form.append('my_buffer', /* something big */);
87 -```
88 -
89 -List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15)
90 -
91 -### Alternative submission methods
92 -
93 -You can use node's http client interface:
94 -
95 -``` javascript
96 -var http = require('http');
97 -
98 -var request = http.request({
99 - method: 'post',
100 - host: 'example.org',
101 - path: '/upload',
102 - headers: form.getHeaders()
103 -});
104 -
105 -form.pipe(request);
106 -
107 -request.on('response', function(res) {
108 - console.log(res.statusCode);
109 -});
110 -```
111 -
112 -Or if you would prefer the `'Content-Length'` header to be set for you:
113 -
114 -``` javascript
115 -form.submit('example.org/upload', function(err, res) {
116 - console.log(res.statusCode);
117 -});
118 -```
119 -
120 -To use custom headers and pre-known length in parts:
121 -
122 -``` javascript
123 -var CRLF = '\r\n';
124 -var form = new FormData();
125 -
126 -var options = {
127 - header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
128 - knownLength: 1
129 -};
130 -
131 -form.append('my_buffer', buffer, options);
132 -
133 -form.submit('http://example.com/', function(err, res) {
134 - if (err) throw err;
135 - console.log('Done');
136 -});
137 -```
138 -
139 -Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually:
140 -
141 -``` javascript
142 -someModule.stream(function(err, stdout, stderr) {
143 - if (err) throw err;
144 -
145 - var form = new FormData();
146 -
147 - form.append('file', stdout, {
148 - filename: 'unicycle.jpg', // ... or:
149 - filepath: 'photos/toys/unicycle.jpg',
150 - contentType: 'image/jpeg',
151 - knownLength: 19806
152 - });
153 -
154 - form.submit('http://example.com/', function(err, res) {
155 - if (err) throw err;
156 - console.log('Done');
157 - });
158 -});
159 -```
160 -
161 -The `filepath` property overrides `filename` and may contain a relative path. This is typically used when uploading [multiple files from a directory](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory).
162 -
163 -For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter:
164 -
165 -``` javascript
166 -form.submit({
167 - host: 'example.com',
168 - path: '/probably.php?extra=params',
169 - auth: 'username:password'
170 -}, function(err, res) {
171 - console.log(res.statusCode);
172 -});
173 -```
174 -
175 -In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`:
176 -
177 -``` javascript
178 -form.submit({
179 - host: 'example.com',
180 - path: '/surelynot.php',
181 - headers: {'x-test-header': 'test-header-value'}
182 -}, function(err, res) {
183 - console.log(res.statusCode);
184 -});
185 -```
186 -
187 -### Methods
188 -
189 -- [_Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )](https://github.com/form-data/form-data#void-append-string-field-mixed-value--mixed-options-).
190 -- [_Headers_ getHeaders( [**Headers** _userHeaders_] )](https://github.com/form-data/form-data#array-getheaders-array-userheaders-)
191 -- [_String_ getBoundary()](https://github.com/form-data/form-data#string-getboundary)
192 -- [_Void_ setBoundary()](https://github.com/form-data/form-data#void-setboundary)
193 -- [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer)
194 -- [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync)
195 -- [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-)
196 -- [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength)
197 -- [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-)
198 -- [_String_ toString()](https://github.com/form-data/form-data#string-tostring)
199 -
200 -#### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )
201 -Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user.
202 -```javascript
203 -var form = new FormData();
204 -form.append( 'my_string', 'my value' );
205 -form.append( 'my_integer', 1 );
206 -form.append( 'my_boolean', true );
207 -form.append( 'my_buffer', new Buffer(10) );
208 -form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) )
209 -```
210 -
211 -You may provide a string for options, or an object.
212 -```javascript
213 -// Set filename by providing a string for options
214 -form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' );
215 -
216 -// provide an object.
217 -form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} );
218 -```
219 -
220 -#### _Headers_ getHeaders( [**Headers** _userHeaders_] )
221 -This method adds the correct `content-type` header to the provided array of `userHeaders`.
222 -
223 -#### _String_ getBoundary()
224 -Return the boundary of the formData. By default, the boundary consists of 26 `-` followed by 24 numbers
225 -for example:
226 -```javascript
227 ---------------------------515890814546601021194782
228 -```
229 -
230 -#### _Void_ setBoundary(String _boundary_)
231 -Set the boundary string, overriding the default behavior described above.
232 -
233 -_Note: The boundary must be unique and may not appear in the data._
234 -
235 -#### _Buffer_ getBuffer()
236 -Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.
237 -```javascript
238 -var form = new FormData();
239 -form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) );
240 -form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') );
241 -
242 -axios.post( 'https://example.com/path/to/api',
243 - form.getBuffer(),
244 - form.getHeaders()
245 - )
246 -```
247 -**Note:** Because the output is of type Buffer, you can only append types that are accepted by Buffer: *string, Buffer, ArrayBuffer, Array, or Array-like Object*. A ReadStream for example will result in an error.
248 -
249 -#### _Integer_ getLengthSync()
250 -Same as `getLength` but synchronous.
251 -
252 -_Note: getLengthSync __doesn't__ calculate streams length._
253 -
254 -#### _Integer_ getLength( **function** _callback_ )
255 -Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated
256 -```javascript
257 -this.getLength(function(err, length) {
258 - if (err) {
259 - this._error(err);
260 - return;
261 - }
262 -
263 - // add content length
264 - request.setHeader('Content-Length', length);
265 -
266 - ...
267 -}.bind(this));
268 -```
269 -
270 -#### _Boolean_ hasKnownLength()
271 -Checks if the length of added values is known.
272 -
273 -#### _Request_ submit( _params_, **function** _callback_ )
274 -Submit the form to a web application.
275 -```javascript
276 -var form = new FormData();
277 -form.append( 'my_string', 'Hello World' );
278 -
279 -form.submit( 'http://example.com/', function(err, res) {
280 - // res – response object (http.IncomingMessage) //
281 - res.resume();
282 -} );
283 -```
284 -
285 -#### _String_ toString()
286 -Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead.
287 -
288 -### Integration with other libraries
289 -
290 -#### Request
291 -
292 -Form submission using [request](https://github.com/request/request):
293 -
294 -```javascript
295 -var formData = {
296 - my_field: 'my_value',
297 - my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
298 -};
299 -
300 -request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
301 - if (err) {
302 - return console.error('upload failed:', err);
303 - }
304 - console.log('Upload successful! Server responded with:', body);
305 -});
306 -```
307 -
308 -For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads).
309 -
310 -#### node-fetch
311 -
312 -You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch):
313 -
314 -```javascript
315 -var form = new FormData();
316 -
317 -form.append('a', 1);
318 -
319 -fetch('http://example.com', { method: 'POST', body: form })
320 - .then(function(res) {
321 - return res.json();
322 - }).then(function(json) {
323 - console.log(json);
324 - });
325 -```
326 -
327 -#### axios
328 -
329 -In Node.js you can post a file using [axios](https://github.com/axios/axios):
330 -```javascript
331 -const form = new FormData();
332 -const stream = fs.createReadStream(PATH_TO_FILE);
333 -
334 -form.append('image', stream);
335 -
336 -// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
337 -const formHeaders = form.getHeaders();
338 -
339 -axios.post('http://example.com', form, {
340 - headers: {
341 - ...formHeaders,
342 - },
343 -})
344 -.then(response => response)
345 -.catch(error => error)
346 -```
347 -
348 -## Notes
349 -
350 -- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround.
351 -- ```getLength(cb)``` will send an error as first parameter of callback if stream length cannot be calculated (e.g. send in custom streams w/o using ```knownLength```).
352 -- ```submit``` will not add `content-length` if form length is unknown or not calculable.
353 -- Starting version `2.x` FormData has dropped support for `node@0.10.x`.
354 -- Starting version `3.x` FormData has dropped support for `node@4.x`.
355 -
356 -## License
357 -
358 -Form-Data is released under the [MIT](License) license.
1 -// Definitions by: Carlos Ballesteros Velasco <https://github.com/soywiz>
2 -// Leon Yu <https://github.com/leonyu>
3 -// BendingBender <https://github.com/BendingBender>
4 -// Maple Miao <https://github.com/mapleeit>
5 -
6 -/// <reference types="node" />
7 -import * as stream from 'stream';
8 -import * as http from 'http';
9 -
10 -export = FormData;
11 -
12 -// Extracted because @types/node doesn't export interfaces.
13 -interface ReadableOptions {
14 - highWaterMark?: number;
15 - encoding?: string;
16 - objectMode?: boolean;
17 - read?(this: stream.Readable, size: number): void;
18 - destroy?(this: stream.Readable, error: Error | null, callback: (error: Error | null) => void): void;
19 - autoDestroy?: boolean;
20 -}
21 -
22 -interface Options extends ReadableOptions {
23 - writable?: boolean;
24 - readable?: boolean;
25 - dataSize?: number;
26 - maxDataSize?: number;
27 - pauseStreams?: boolean;
28 -}
29 -
30 -declare class FormData extends stream.Readable {
31 - constructor(options?: Options);
32 - append(key: string, value: any, options?: FormData.AppendOptions | string): void;
33 - getHeaders(userHeaders?: FormData.Headers): FormData.Headers;
34 - submit(
35 - params: string | FormData.SubmitOptions,
36 - callback?: (error: Error | null, response: http.IncomingMessage) => void
37 - ): http.ClientRequest;
38 - getBuffer(): Buffer;
39 - setBoundary(boundary: string): void;
40 - getBoundary(): string;
41 - getLength(callback: (err: Error | null, length: number) => void): void;
42 - getLengthSync(): number;
43 - hasKnownLength(): boolean;
44 -}
45 -
46 -declare namespace FormData {
47 - interface Headers {
48 - [key: string]: any;
49 - }
50 -
51 - interface AppendOptions {
52 - header?: string | Headers;
53 - knownLength?: number;
54 - filename?: string;
55 - filepath?: string;
56 - contentType?: string;
57 - }
58 -
59 - interface SubmitOptions extends http.RequestOptions {
60 - protocol?: 'https:' | 'http:';
61 - }
62 -}
1 -/* eslint-env browser */
2 -module.exports = typeof self == 'object' ? self.FormData : window.FormData;
1 -var CombinedStream = require('combined-stream');
2 -var util = require('util');
3 -var path = require('path');
4 -var http = require('http');
5 -var https = require('https');
6 -var parseUrl = require('url').parse;
7 -var fs = require('fs');
8 -var Stream = require('stream').Stream;
9 -var mime = require('mime-types');
10 -var asynckit = require('asynckit');
11 -var populate = require('./populate.js');
12 -
13 -// Public API
14 -module.exports = FormData;
15 -
16 -// make it a Stream
17 -util.inherits(FormData, CombinedStream);
18 -
19 -/**
20 - * Create readable "multipart/form-data" streams.
21 - * Can be used to submit forms
22 - * and file uploads to other web applications.
23 - *
24 - * @constructor
25 - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream
26 - */
27 -function FormData(options) {
28 - if (!(this instanceof FormData)) {
29 - return new FormData(options);
30 - }
31 -
32 - this._overheadLength = 0;
33 - this._valueLength = 0;
34 - this._valuesToMeasure = [];
35 -
36 - CombinedStream.call(this);
37 -
38 - options = options || {};
39 - for (var option in options) {
40 - this[option] = options[option];
41 - }
42 -}
43 -
44 -FormData.LINE_BREAK = '\r\n';
45 -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
46 -
47 -FormData.prototype.append = function(field, value, options) {
48 -
49 - options = options || {};
50 -
51 - // allow filename as single option
52 - if (typeof options == 'string') {
53 - options = {filename: options};
54 - }
55 -
56 - var append = CombinedStream.prototype.append.bind(this);
57 -
58 - // all that streamy business can't handle numbers
59 - if (typeof value == 'number') {
60 - value = '' + value;
61 - }
62 -
63 - // https://github.com/felixge/node-form-data/issues/38
64 - if (util.isArray(value)) {
65 - // Please convert your array into string
66 - // the way web server expects it
67 - this._error(new Error('Arrays are not supported.'));
68 - return;
69 - }
70 -
71 - var header = this._multiPartHeader(field, value, options);
72 - var footer = this._multiPartFooter();
73 -
74 - append(header);
75 - append(value);
76 - append(footer);
77 -
78 - // pass along options.knownLength
79 - this._trackLength(header, value, options);
80 -};
81 -
82 -FormData.prototype._trackLength = function(header, value, options) {
83 - var valueLength = 0;
84 -
85 - // used w/ getLengthSync(), when length is known.
86 - // e.g. for streaming directly from a remote server,
87 - // w/ a known file a size, and not wanting to wait for
88 - // incoming file to finish to get its size.
89 - if (options.knownLength != null) {
90 - valueLength += +options.knownLength;
91 - } else if (Buffer.isBuffer(value)) {
92 - valueLength = value.length;
93 - } else if (typeof value === 'string') {
94 - valueLength = Buffer.byteLength(value);
95 - }
96 -
97 - this._valueLength += valueLength;
98 -
99 - // @check why add CRLF? does this account for custom/multiple CRLFs?
100 - this._overheadLength +=
101 - Buffer.byteLength(header) +
102 - FormData.LINE_BREAK.length;
103 -
104 - // empty or either doesn't have path or not an http response or not a stream
105 - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) {
106 - return;
107 - }
108 -
109 - // no need to bother with the length
110 - if (!options.knownLength) {
111 - this._valuesToMeasure.push(value);
112 - }
113 -};
114 -
115 -FormData.prototype._lengthRetriever = function(value, callback) {
116 -
117 - if (value.hasOwnProperty('fd')) {
118 -
119 - // take read range into a account
120 - // `end` = Infinity –> read file till the end
121 - //
122 - // TODO: Looks like there is bug in Node fs.createReadStream
123 - // it doesn't respect `end` options without `start` options
124 - // Fix it when node fixes it.
125 - // https://github.com/joyent/node/issues/7819
126 - if (value.end != undefined && value.end != Infinity && value.start != undefined) {
127 -
128 - // when end specified
129 - // no need to calculate range
130 - // inclusive, starts with 0
131 - callback(null, value.end + 1 - (value.start ? value.start : 0));
132 -
133 - // not that fast snoopy
134 - } else {
135 - // still need to fetch file size from fs
136 - fs.stat(value.path, function(err, stat) {
137 -
138 - var fileSize;
139 -
140 - if (err) {
141 - callback(err);
142 - return;
143 - }
144 -
145 - // update final size based on the range options
146 - fileSize = stat.size - (value.start ? value.start : 0);
147 - callback(null, fileSize);
148 - });
149 - }
150 -
151 - // or http response
152 - } else if (value.hasOwnProperty('httpVersion')) {
153 - callback(null, +value.headers['content-length']);
154 -
155 - // or request stream http://github.com/mikeal/request
156 - } else if (value.hasOwnProperty('httpModule')) {
157 - // wait till response come back
158 - value.on('response', function(response) {
159 - value.pause();
160 - callback(null, +response.headers['content-length']);
161 - });
162 - value.resume();
163 -
164 - // something else
165 - } else {
166 - callback('Unknown stream');
167 - }
168 -};
169 -
170 -FormData.prototype._multiPartHeader = function(field, value, options) {
171 - // custom header specified (as string)?
172 - // it becomes responsible for boundary
173 - // (e.g. to handle extra CRLFs on .NET servers)
174 - if (typeof options.header == 'string') {
175 - return options.header;
176 - }
177 -
178 - var contentDisposition = this._getContentDisposition(value, options);
179 - var contentType = this._getContentType(value, options);
180 -
181 - var contents = '';
182 - var headers = {
183 - // add custom disposition as third element or keep it two elements if not
184 - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
185 - // if no content type. allow it to be empty array
186 - 'Content-Type': [].concat(contentType || [])
187 - };
188 -
189 - // allow custom headers.
190 - if (typeof options.header == 'object') {
191 - populate(headers, options.header);
192 - }
193 -
194 - var header;
195 - for (var prop in headers) {
196 - if (!headers.hasOwnProperty(prop)) continue;
197 - header = headers[prop];
198 -
199 - // skip nullish headers.
200 - if (header == null) {
201 - continue;
202 - }
203 -
204 - // convert all headers to arrays.
205 - if (!Array.isArray(header)) {
206 - header = [header];
207 - }
208 -
209 - // add non-empty headers.
210 - if (header.length) {
211 - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
212 - }
213 - }
214 -
215 - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
216 -};
217 -
218 -FormData.prototype._getContentDisposition = function(value, options) {
219 -
220 - var filename
221 - , contentDisposition
222 - ;
223 -
224 - if (typeof options.filepath === 'string') {
225 - // custom filepath for relative paths
226 - filename = path.normalize(options.filepath).replace(/\\/g, '/');
227 - } else if (options.filename || value.name || value.path) {
228 - // custom filename take precedence
229 - // formidable and the browser add a name property
230 - // fs- and request- streams have path property
231 - filename = path.basename(options.filename || value.name || value.path);
232 - } else if (value.readable && value.hasOwnProperty('httpVersion')) {
233 - // or try http response
234 - filename = path.basename(value.client._httpMessage.path || '');
235 - }
236 -
237 - if (filename) {
238 - contentDisposition = 'filename="' + filename + '"';
239 - }
240 -
241 - return contentDisposition;
242 -};
243 -
244 -FormData.prototype._getContentType = function(value, options) {
245 -
246 - // use custom content-type above all
247 - var contentType = options.contentType;
248 -
249 - // or try `name` from formidable, browser
250 - if (!contentType && value.name) {
251 - contentType = mime.lookup(value.name);
252 - }
253 -
254 - // or try `path` from fs-, request- streams
255 - if (!contentType && value.path) {
256 - contentType = mime.lookup(value.path);
257 - }
258 -
259 - // or if it's http-reponse
260 - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
261 - contentType = value.headers['content-type'];
262 - }
263 -
264 - // or guess it from the filepath or filename
265 - if (!contentType && (options.filepath || options.filename)) {
266 - contentType = mime.lookup(options.filepath || options.filename);
267 - }
268 -
269 - // fallback to the default content type if `value` is not simple value
270 - if (!contentType && typeof value == 'object') {
271 - contentType = FormData.DEFAULT_CONTENT_TYPE;
272 - }
273 -
274 - return contentType;
275 -};
276 -
277 -FormData.prototype._multiPartFooter = function() {
278 - return function(next) {
279 - var footer = FormData.LINE_BREAK;
280 -
281 - var lastPart = (this._streams.length === 0);
282 - if (lastPart) {
283 - footer += this._lastBoundary();
284 - }
285 -
286 - next(footer);
287 - }.bind(this);
288 -};
289 -
290 -FormData.prototype._lastBoundary = function() {
291 - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
292 -};
293 -
294 -FormData.prototype.getHeaders = function(userHeaders) {
295 - var header;
296 - var formHeaders = {
297 - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
298 - };
299 -
300 - for (header in userHeaders) {
301 - if (userHeaders.hasOwnProperty(header)) {
302 - formHeaders[header.toLowerCase()] = userHeaders[header];
303 - }
304 - }
305 -
306 - return formHeaders;
307 -};
308 -
309 -FormData.prototype.setBoundary = function(boundary) {
310 - this._boundary = boundary;
311 -};
312 -
313 -FormData.prototype.getBoundary = function() {
314 - if (!this._boundary) {
315 - this._generateBoundary();
316 - }
317 -
318 - return this._boundary;
319 -};
320 -
321 -FormData.prototype.getBuffer = function() {
322 - var dataBuffer = new Buffer.alloc( 0 );
323 - var boundary = this.getBoundary();
324 -
325 - // Create the form content. Add Line breaks to the end of data.
326 - for (var i = 0, len = this._streams.length; i < len; i++) {
327 - if (typeof this._streams[i] !== 'function') {
328 -
329 - // Add content to the buffer.
330 - if(Buffer.isBuffer(this._streams[i])) {
331 - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]);
332 - }else {
333 - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]);
334 - }
335 -
336 - // Add break after content.
337 - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) {
338 - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] );
339 - }
340 - }
341 - }
342 -
343 - // Add the footer and return the Buffer object.
344 - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] );
345 -};
346 -
347 -FormData.prototype._generateBoundary = function() {
348 - // This generates a 50 character boundary similar to those used by Firefox.
349 - // They are optimized for boyer-moore parsing.
350 - var boundary = '--------------------------';
351 - for (var i = 0; i < 24; i++) {
352 - boundary += Math.floor(Math.random() * 10).toString(16);
353 - }
354 -
355 - this._boundary = boundary;
356 -};
357 -
358 -// Note: getLengthSync DOESN'T calculate streams length
359 -// As workaround one can calculate file size manually
360 -// and add it as knownLength option
361 -FormData.prototype.getLengthSync = function() {
362 - var knownLength = this._overheadLength + this._valueLength;
363 -
364 - // Don't get confused, there are 3 "internal" streams for each keyval pair
365 - // so it basically checks if there is any value added to the form
366 - if (this._streams.length) {
367 - knownLength += this._lastBoundary().length;
368 - }
369 -
370 - // https://github.com/form-data/form-data/issues/40
371 - if (!this.hasKnownLength()) {
372 - // Some async length retrievers are present
373 - // therefore synchronous length calculation is false.
374 - // Please use getLength(callback) to get proper length
375 - this._error(new Error('Cannot calculate proper length in synchronous way.'));
376 - }
377 -
378 - return knownLength;
379 -};
380 -
381 -// Public API to check if length of added values is known
382 -// https://github.com/form-data/form-data/issues/196
383 -// https://github.com/form-data/form-data/issues/262
384 -FormData.prototype.hasKnownLength = function() {
385 - var hasKnownLength = true;
386 -
387 - if (this._valuesToMeasure.length) {
388 - hasKnownLength = false;
389 - }
390 -
391 - return hasKnownLength;
392 -};
393 -
394 -FormData.prototype.getLength = function(cb) {
395 - var knownLength = this._overheadLength + this._valueLength;
396 -
397 - if (this._streams.length) {
398 - knownLength += this._lastBoundary().length;
399 - }
400 -
401 - if (!this._valuesToMeasure.length) {
402 - process.nextTick(cb.bind(this, null, knownLength));
403 - return;
404 - }
405 -
406 - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
407 - if (err) {
408 - cb(err);
409 - return;
410 - }
411 -
412 - values.forEach(function(length) {
413 - knownLength += length;
414 - });
415 -
416 - cb(null, knownLength);
417 - });
418 -};
419 -
420 -FormData.prototype.submit = function(params, cb) {
421 - var request
422 - , options
423 - , defaults = {method: 'post'}
424 - ;
425 -
426 - // parse provided url if it's string
427 - // or treat it as options object
428 - if (typeof params == 'string') {
429 -
430 - params = parseUrl(params);
431 - options = populate({
432 - port: params.port,
433 - path: params.pathname,
434 - host: params.hostname,
435 - protocol: params.protocol
436 - }, defaults);
437 -
438 - // use custom params
439 - } else {
440 -
441 - options = populate(params, defaults);
442 - // if no port provided use default one
443 - if (!options.port) {
444 - options.port = options.protocol == 'https:' ? 443 : 80;
445 - }
446 - }
447 -
448 - // put that good code in getHeaders to some use
449 - options.headers = this.getHeaders(params.headers);
450 -
451 - // https if specified, fallback to http in any other case
452 - if (options.protocol == 'https:') {
453 - request = https.request(options);
454 - } else {
455 - request = http.request(options);
456 - }
457 -
458 - // get content length and fire away
459 - this.getLength(function(err, length) {
460 - if (err && err !== 'Unknown stream') {
461 - this._error(err);
462 - return;
463 - }
464 -
465 - // add content length
466 - if (length) {
467 - request.setHeader('Content-Length', length);
468 - }
469 -
470 - this.pipe(request);
471 - if (cb) {
472 - var onResponse;
473 -
474 - var callback = function (error, responce) {
475 - request.removeListener('error', callback);
476 - request.removeListener('response', onResponse);
477 -
478 - return cb.call(this, error, responce);
479 - };
480 -
481 - onResponse = callback.bind(this, null);
482 -
483 - request.on('error', callback);
484 - request.on('response', onResponse);
485 - }
486 - }.bind(this));
487 -
488 - return request;
489 -};
490 -
491 -FormData.prototype._error = function(err) {
492 - if (!this.error) {
493 - this.error = err;
494 - this.pause();
495 - this.emit('error', err);
496 - }
497 -};
498 -
499 -FormData.prototype.toString = function () {
500 - return '[object FormData]';
501 -};
1 -// populates missing values
2 -module.exports = function(dst, src) {
3 -
4 - Object.keys(src).forEach(function(prop)
5 - {
6 - dst[prop] = dst[prop] || src[prop];
7 - });
8 -
9 - return dst;
10 -};
1 -{
2 - "author": "Felix Geisendörfer <felix@debuggable.com> (http://debuggable.com/)",
3 - "name": "form-data",
4 - "description": "A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.",
5 - "version": "4.0.0",
6 - "repository": {
7 - "type": "git",
8 - "url": "git://github.com/form-data/form-data.git"
9 - },
10 - "main": "./lib/form_data",
11 - "browser": "./lib/browser",
12 - "typings": "./index.d.ts",
13 - "scripts": {
14 - "pretest": "rimraf coverage test/tmp",
15 - "test": "istanbul cover test/run.js",
16 - "posttest": "istanbul report lcov text",
17 - "lint": "eslint lib/*.js test/*.js test/integration/*.js",
18 - "report": "istanbul report lcov text",
19 - "ci-lint": "is-node-modern 8 && npm run lint || is-node-not-modern 8",
20 - "ci-test": "npm run test && npm run browser && npm run report",
21 - "predebug": "rimraf coverage test/tmp",
22 - "debug": "verbose=1 ./test/run.js",
23 - "browser": "browserify -t browserify-istanbul test/run-browser.js | obake --coverage",
24 - "check": "istanbul check-coverage coverage/coverage*.json",
25 - "files": "pkgfiles --sort=name",
26 - "get-version": "node -e \"console.log(require('./package.json').version)\"",
27 - "update-readme": "sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md",
28 - "restore-readme": "mv README.md.bak README.md",
29 - "prepublish": "in-publish && npm run update-readme || not-in-publish",
30 - "postpublish": "npm run restore-readme"
31 - },
32 - "pre-commit": [
33 - "lint",
34 - "ci-test",
35 - "check"
36 - ],
37 - "engines": {
38 - "node": ">= 6"
39 - },
40 - "dependencies": {
41 - "asynckit": "^0.4.0",
42 - "combined-stream": "^1.0.8",
43 - "mime-types": "^2.1.12"
44 - },
45 - "devDependencies": {
46 - "@types/node": "^12.0.10",
47 - "browserify": "^13.1.1",
48 - "browserify-istanbul": "^2.0.0",
49 - "coveralls": "^3.0.4",
50 - "cross-spawn": "^6.0.5",
51 - "eslint": "^6.0.1",
52 - "fake": "^0.2.2",
53 - "far": "^0.0.7",
54 - "formidable": "^1.0.17",
55 - "in-publish": "^2.0.0",
56 - "is-node-modern": "^1.0.0",
57 - "istanbul": "^0.4.5",
58 - "obake": "^0.1.2",
59 - "puppeteer": "^1.19.0",
60 - "pkgfiles": "^2.3.0",
61 - "pre-commit": "^1.1.3",
62 - "request": "^2.88.0",
63 - "rimraf": "^2.7.1",
64 - "tape": "^4.6.2",
65 - "typescript": "^3.5.2"
66 - },
67 - "license": "MIT"
68 -}
1 +/* formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +/* global FormData self Blob File */
4 +/* eslint-disable no-inner-declarations */
5 +
6 +if (typeof Blob !== 'undefined' && (typeof FormData === 'undefined' || !FormData.prototype.keys)) {
7 + const global = typeof globalThis === 'object'
8 + ? globalThis
9 + : typeof window === 'object'
10 + ? window
11 + : typeof self === 'object' ? self : this
12 +
13 + // keep a reference to native implementation
14 + const _FormData = global.FormData
15 +
16 + // To be monkey patched
17 + const _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send
18 + const _fetch = global.Request && global.fetch
19 + const _sendBeacon = global.navigator && global.navigator.sendBeacon
20 + // Might be a worker thread...
21 + const _match = global.Element && global.Element.prototype
22 +
23 + // Unable to patch Request/Response constructor correctly #109
24 + // only way is to use ES6 class extend
25 + // https://github.com/babel/babel/issues/1966
26 +
27 + const stringTag = global.Symbol && Symbol.toStringTag
28 +
29 + // Add missing stringTags to blob and files
30 + if (stringTag) {
31 + if (!Blob.prototype[stringTag]) {
32 + Blob.prototype[stringTag] = 'Blob'
33 + }
34 +
35 + if ('File' in global && !File.prototype[stringTag]) {
36 + File.prototype[stringTag] = 'File'
37 + }
38 + }
39 +
40 + // Fix so you can construct your own File
41 + try {
42 + new File([], '') // eslint-disable-line
43 + } catch (a) {
44 + global.File = function File (b, d, c) {
45 + const blob = new Blob(b, c || {})
46 + const t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date()
47 +
48 + Object.defineProperties(blob, {
49 + name: {
50 + value: d
51 + },
52 + lastModified: {
53 + value: +t
54 + },
55 + toString: {
56 + value () {
57 + return '[object File]'
58 + }
59 + }
60 + })
61 +
62 + if (stringTag) {
63 + Object.defineProperty(blob, stringTag, {
64 + value: 'File'
65 + })
66 + }
67 +
68 + return blob
69 + }
70 + }
71 +
72 + function ensureArgs (args, expected) {
73 + if (args.length < expected) {
74 + throw new TypeError(`${expected} argument required, but only ${args.length} present.`)
75 + }
76 + }
77 +
78 + /**
79 + * @param {string} name
80 + * @param {string | undefined} filename
81 + * @returns {[string, File|string]}
82 + */
83 + function normalizeArgs (name, value, filename) {
84 + if (value instanceof Blob) {
85 + filename = filename !== undefined
86 + ? String(filename + '')
87 + : typeof value.name === 'string'
88 + ? value.name
89 + : 'blob'
90 +
91 + if (value.name !== filename || Object.prototype.toString.call(value) === '[object Blob]') {
92 + value = new File([value], filename)
93 + }
94 + return [String(name), value]
95 + }
96 + return [String(name), String(value)]
97 + }
98 +
99 + // normalize line feeds for textarea
100 + // https://html.spec.whatwg.org/multipage/form-elements.html#textarea-line-break-normalisation-transformation
101 + function normalizeLinefeeds (value) {
102 + return value.replace(/\r?\n|\r/g, '\r\n')
103 + }
104 +
105 + /**
106 + * @template T
107 + * @param {ArrayLike<T>} arr
108 + * @param {{ (elm: T): void; }} cb
109 + */
110 + function each (arr, cb) {
111 + for (let i = 0; i < arr.length; i++) {
112 + cb(arr[i])
113 + }
114 + }
115 +
116 + const escape = str => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
117 +
118 + /**
119 + * @implements {Iterable}
120 + */
121 + class FormDataPolyfill {
122 + /**
123 + * FormData class
124 + *
125 + * @param {HTMLFormElement=} form
126 + */
127 + constructor (form) {
128 + /** @type {[string, string|File][]} */
129 + this._data = []
130 +
131 + const self = this
132 + form && each(form.elements, (/** @type {HTMLInputElement} */ elm) => {
133 + if (
134 + !elm.name ||
135 + elm.disabled ||
136 + elm.type === 'submit' ||
137 + elm.type === 'button' ||
138 + elm.matches('form fieldset[disabled] *')
139 + ) return
140 +
141 + if (elm.type === 'file') {
142 + const files = elm.files && elm.files.length
143 + ? elm.files
144 + : [new File([], '', { type: 'application/octet-stream' })] // #78
145 +
146 + each(files, file => {
147 + self.append(elm.name, file)
148 + })
149 + } else if (elm.type === 'select-multiple' || elm.type === 'select-one') {
150 + each(elm.options, opt => {
151 + !opt.disabled && opt.selected && self.append(elm.name, opt.value)
152 + })
153 + } else if (elm.type === 'checkbox' || elm.type === 'radio') {
154 + if (elm.checked) self.append(elm.name, elm.value)
155 + } else {
156 + const value = elm.type === 'textarea' ? normalizeLinefeeds(elm.value) : elm.value
157 + self.append(elm.name, value)
158 + }
159 + })
160 + }
161 +
162 + /**
163 + * Append a field
164 + *
165 + * @param {string} name field name
166 + * @param {string|Blob|File} value string / blob / file
167 + * @param {string=} filename filename to use with blob
168 + * @return {undefined}
169 + */
170 + append (name, value, filename) {
171 + ensureArgs(arguments, 2)
172 + this._data.push(normalizeArgs(name, value, filename))
173 + }
174 +
175 + /**
176 + * Delete all fields values given name
177 + *
178 + * @param {string} name Field name
179 + * @return {undefined}
180 + */
181 + delete (name) {
182 + ensureArgs(arguments, 1)
183 + const result = []
184 + name = String(name)
185 +
186 + each(this._data, entry => {
187 + entry[0] !== name && result.push(entry)
188 + })
189 +
190 + this._data = result
191 + }
192 +
193 + /**
194 + * Iterate over all fields as [name, value]
195 + *
196 + * @return {Iterator}
197 + */
198 + * entries () {
199 + for (var i = 0; i < this._data.length; i++) {
200 + yield this._data[i]
201 + }
202 + }
203 +
204 + /**
205 + * Iterate over all fields
206 + *
207 + * @param {Function} callback Executed for each item with parameters (value, name, thisArg)
208 + * @param {Object=} thisArg `this` context for callback function
209 + */
210 + forEach (callback, thisArg) {
211 + ensureArgs(arguments, 1)
212 + for (const [name, value] of this) {
213 + callback.call(thisArg, value, name, this)
214 + }
215 + }
216 +
217 + /**
218 + * Return first field value given name
219 + * or null if non existent
220 + *
221 + * @param {string} name Field name
222 + * @return {string|File|null} value Fields value
223 + */
224 + get (name) {
225 + ensureArgs(arguments, 1)
226 + const entries = this._data
227 + name = String(name)
228 + for (let i = 0; i < entries.length; i++) {
229 + if (entries[i][0] === name) {
230 + return entries[i][1]
231 + }
232 + }
233 + return null
234 + }
235 +
236 + /**
237 + * Return all fields values given name
238 + *
239 + * @param {string} name Fields name
240 + * @return {Array} [{String|File}]
241 + */
242 + getAll (name) {
243 + ensureArgs(arguments, 1)
244 + const result = []
245 + name = String(name)
246 + each(this._data, data => {
247 + data[0] === name && result.push(data[1])
248 + })
249 +
250 + return result
251 + }
252 +
253 + /**
254 + * Check for field name existence
255 + *
256 + * @param {string} name Field name
257 + * @return {boolean}
258 + */
259 + has (name) {
260 + ensureArgs(arguments, 1)
261 + name = String(name)
262 + for (let i = 0; i < this._data.length; i++) {
263 + if (this._data[i][0] === name) {
264 + return true
265 + }
266 + }
267 + return false
268 + }
269 +
270 + /**
271 + * Iterate over all fields name
272 + *
273 + * @return {Iterator}
274 + */
275 + * keys () {
276 + for (const [name] of this) {
277 + yield name
278 + }
279 + }
280 +
281 + /**
282 + * Overwrite all values given name
283 + *
284 + * @param {string} name Filed name
285 + * @param {string} value Field value
286 + * @param {string=} filename Filename (optional)
287 + */
288 + set (name, value, filename) {
289 + ensureArgs(arguments, 2)
290 + name = String(name)
291 + /** @type {[string, string|File][]} */
292 + const result = []
293 + const args = normalizeArgs(name, value, filename)
294 + let replace = true
295 +
296 + // - replace the first occurrence with same name
297 + // - discards the remaining with same name
298 + // - while keeping the same order items where added
299 + each(this._data, data => {
300 + data[0] === name
301 + ? replace && (replace = !result.push(args))
302 + : result.push(data)
303 + })
304 +
305 + replace && result.push(args)
306 +
307 + this._data = result
308 + }
309 +
310 + /**
311 + * Iterate over all fields
312 + *
313 + * @return {Iterator}
314 + */
315 + * values () {
316 + for (const [, value] of this) {
317 + yield value
318 + }
319 + }
320 +
321 + /**
322 + * Return a native (perhaps degraded) FormData with only a `append` method
323 + * Can throw if it's not supported
324 + *
325 + * @return {FormData}
326 + */
327 + ['_asNative'] () {
328 + const fd = new _FormData()
329 +
330 + for (const [name, value] of this) {
331 + fd.append(name, value)
332 + }
333 +
334 + return fd
335 + }
336 +
337 + /**
338 + * [_blob description]
339 + *
340 + * @return {Blob} [description]
341 + */
342 + ['_blob'] () {
343 + const boundary = '----formdata-polyfill-' + Math.random(),
344 + chunks = [],
345 + p = `--${boundary}\r\nContent-Disposition: form-data; name="`
346 + this.forEach((value, name) => typeof value == 'string'
347 + ? chunks.push(p + escape(normalizeLinefeeds(name)) + `"\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
348 + : chunks.push(p + escape(normalizeLinefeeds(name)) + `"; filename="${escape(value.name)}"\r\nContent-Type: ${value.type||"application/octet-stream"}\r\n\r\n`, value, `\r\n`))
349 + chunks.push(`--${boundary}--`)
350 + return new Blob(chunks, {
351 + type: "multipart/form-data; boundary=" + boundary
352 + })
353 + }
354 +
355 + /**
356 + * The class itself is iterable
357 + * alias for formdata.entries()
358 + *
359 + * @return {Iterator}
360 + */
361 + [Symbol.iterator] () {
362 + return this.entries()
363 + }
364 +
365 + /**
366 + * Create the default string description.
367 + *
368 + * @return {string} [object FormData]
369 + */
370 + toString () {
371 + return '[object FormData]'
372 + }
373 + }
374 +
375 + if (_match && !_match.matches) {
376 + _match.matches =
377 + _match.matchesSelector ||
378 + _match.mozMatchesSelector ||
379 + _match.msMatchesSelector ||
380 + _match.oMatchesSelector ||
381 + _match.webkitMatchesSelector ||
382 + function (s) {
383 + var matches = (this.document || this.ownerDocument).querySelectorAll(s)
384 + var i = matches.length
385 + while (--i >= 0 && matches.item(i) !== this) {}
386 + return i > -1
387 + }
388 + }
389 +
390 + if (stringTag) {
391 + /**
392 + * Create the default string description.
393 + * It is accessed internally by the Object.prototype.toString().
394 + */
395 + FormDataPolyfill.prototype[stringTag] = 'FormData'
396 + }
397 +
398 + // Patch xhr's send method to call _blob transparently
399 + if (_send) {
400 + const setRequestHeader = global.XMLHttpRequest.prototype.setRequestHeader
401 +
402 + global.XMLHttpRequest.prototype.setRequestHeader = function (name, value) {
403 + setRequestHeader.call(this, name, value)
404 + if (name.toLowerCase() === 'content-type') this._hasContentType = true
405 + }
406 +
407 + global.XMLHttpRequest.prototype.send = function (data) {
408 + // need to patch send b/c old IE don't send blob's type (#44)
409 + if (data instanceof FormDataPolyfill) {
410 + const blob = data['_blob']()
411 + if (!this._hasContentType) this.setRequestHeader('Content-Type', blob.type)
412 + _send.call(this, blob)
413 + } else {
414 + _send.call(this, data)
415 + }
416 + }
417 + }
418 +
419 + // Patch fetch's function to call _blob transparently
420 + if (_fetch) {
421 + global.fetch = function (input, init) {
422 + if (init && init.body && init.body instanceof FormDataPolyfill) {
423 + init.body = init.body['_blob']()
424 + }
425 +
426 + return _fetch.call(this, input, init)
427 + }
428 + }
429 +
430 + // Patch navigator.sendBeacon to use native FormData
431 + if (_sendBeacon) {
432 + global.navigator.sendBeacon = function (url, data) {
433 + if (data instanceof FormDataPolyfill) {
434 + data = data['_asNative']()
435 + }
436 + return _sendBeacon.call(this, url, data)
437 + }
438 + }
439 +
440 + global['FormData'] = FormDataPolyfill
441 +}
1 +MIT License
2 +
3 +Copyright (c) 2016 Jimmy Karl Roland Wärting
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
1 +### A `FormData` polyfill for the browser ...and a module for NodeJS (`New!`)
2 +
3 +```bash
4 +npm install formdata-polyfill
5 +```
6 +
7 +The browser polyfill will likely have done its part already, and i hope you stop supporting old browsers c",)<br>
8 +But NodeJS still laks a proper FormData<br>The good old form-data package is a very old and isn't spec compatible and dose some abnormal stuff to construct and read FormData instances that other http libraries are not happy about when it comes to follow the spec.
9 +
10 +### The NodeJS / ESM version
11 +- The modular (~2.3 KiB minified uncompressed) version of this package is independent of any browser stuff and don't patch anything
12 +- It's as pure/spec compatible as it possible gets the test are run by WPT.
13 +- It's compatible with [node-fetch](https://github.com/node-fetch/node-fetch).
14 +- It have higher platform dependencies as it uses classes, symbols, ESM & private fields
15 +- Only dependency it has is [fetch-blob](https://github.com/node-fetch/fetch-blob)
16 +
17 +```js
18 +// Node example
19 +import fetch from 'node-fetch'
20 +import File from 'fetch-blob/file.js'
21 +import { fileFromSync } from 'fetch-blob/from.js'
22 +import { FormData } from 'formdata-polyfill/esm.min.js'
23 +
24 +const file = fileFromSync('./README.md')
25 +const fd = new FormData()
26 +
27 +fd.append('file-upload', new File(['abc'], 'hello-world.txt'))
28 +fd.append('file-upload', file)
29 +
30 +// it's also possible to append file/blob look-a-like items
31 +// if you have streams coming from other destinations
32 +fd.append('file-upload', {
33 + size: 123,
34 + type: '',
35 + name: 'cat-video.mp4',
36 + stream() { return stream },
37 + [Symbol.toStringTag]: 'File'
38 +})
39 +
40 +fetch('https://httpbin.org/post', { method: 'POST', body: fd })
41 +```
42 +
43 +----
44 +
45 +It also comes with way to convert FormData into Blobs - it's not something that every developer should have to deal with.
46 +It's mainly for [node-fetch](https://github.com/node-fetch/node-fetch) and other http library to ease the process of serializing a FormData into a blob and just wish to deal with Blobs instead (Both Deno and Undici adapted a version of this [formDataToBlob](https://github.com/jimmywarting/FormData/blob/5ddea9e0de2fc5e246ab1b2f9d404dee0c319c02/formdata-to-blob.js) to the core and passes all WPT tests run by the browser itself)
47 +```js
48 +import { Readable } from 'node:stream'
49 +import { FormData, formDataToBlob } from 'formdata-polyfill/esm.min.js'
50 +
51 +const blob = formDataToBlob(new FormData())
52 +fetch('https://httpbin.org/post', { method: 'POST', body: blob })
53 +
54 +// node built in http and other similar http library have to do:
55 +const stream = Readable.from(blob.stream())
56 +const req = http.request('http://httpbin.org/post', {
57 + method: 'post',
58 + headers: {
59 + 'Content-Length': blob.size,
60 + 'Content-Type': blob.type
61 + }
62 +})
63 +stream.pipe(req)
64 +```
65 +
66 +PS: blob & file that are appended to the FormData will not be read until any of the serialized blob read-methods gets called
67 +...so uploading very large files is no biggie
68 +
69 +### Browser polyfill
70 +
71 +usage:
72 +
73 +```js
74 +import 'formdata-polyfill' // that's it
75 +```
76 +
77 +The browser polyfill conditionally replaces the native implementation rather than fixing the missing functions,
78 +since otherwise there is no way to get or delete existing values in the FormData object.
79 +Therefore this also patches `XMLHttpRequest.prototype.send` and `fetch` to send the `FormData` as a blob,
80 +and `navigator.sendBeacon` to send native `FormData`.
81 +
82 +I was unable to patch the Response/Request constructor
83 +so if you are constructing them with FormData then you need to call `fd._blob()` manually.
84 +
85 +```js
86 +new Request(url, {
87 + method: 'post',
88 + body: fd._blob ? fd._blob() : fd
89 +})
90 +```
91 +
92 +Dependencies
93 +---
94 +
95 +If you need to support IE <= 9 then I recommend you to include eligrey's [blob.js]
96 +(which i hope you don't - since IE is now dead)
97 +
98 +<details>
99 + <summary>Updating from 2.x to 3.x</summary>
100 +
101 +Previously you had to import the polyfill and use that,
102 +since it didn't replace the global (existing) FormData implementation.
103 +But now it transparently calls `_blob()` for you when you are sending something with fetch or XHR,
104 +by way of monkey-patching the `XMLHttpRequest.prototype.send` and `fetch` functions.
105 +
106 +So you maybe had something like this:
107 +
108 +```javascript
109 +var FormData = require('formdata-polyfill')
110 +var fd = new FormData(form)
111 +xhr.send(fd._blob())
112 +```
113 +
114 +There is no longer anything exported from the module
115 +(though you of course still need to import it to install the polyfill),
116 +so you can now use the FormData object as normal:
117 +
118 +```javascript
119 +require('formdata-polyfill')
120 +var fd = new FormData(form)
121 +xhr.send(fd)
122 +```
123 +
124 +</details>
125 +
126 +
127 +
128 +Native Browser compatibility (as of 2021-05-08)
129 +---
130 +Based on this you can decide for yourself if you need this polyfill.
131 +
132 +[![screenshot](https://user-images.githubusercontent.com/1148376/117550329-0993aa80-b040-11eb-976c-14e31f1a3ba4.png)](https://developer.mozilla.org/en-US/docs/Web/API/FormData#Browser_compatibility)
133 +
134 +
135 +
136 +This normalizes support for the FormData API:
137 +
138 + - `append` with filename
139 + - `delete()`, `get()`, `getAll()`, `has()`, `set()`
140 + - `entries()`, `keys()`, `values()`, and support for `for...of`
141 + - Available in web workers (just include the polyfill)
142 +
143 + [npm-image]: https://img.shields.io/npm/v/formdata-polyfill.svg
144 + [npm-url]: https://www.npmjs.com/package/formdata-polyfill
145 + [blob.js]: https://github.com/eligrey/Blob.js
1 +export declare const FormData: {
2 + new (): FormData;
3 + prototype: FormData;
4 +};
5 +export declare function formDataToBlob(formData: FormData): Blob;
1 +/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +import C from 'fetch-blob'
4 +import F from 'fetch-blob/file.js'
5 +
6 +var {toStringTag:t,iterator:i,hasInstance:h}=Symbol,
7 +r=Math.random,
8 +m='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','),
9 +f=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new F([b],c,b):b]:[a,b+'']),
10 +e=(c,f)=>(f?c:c.replace(/\r?\n|\r/g,'\r\n')).replace(/\n/g,'%0A').replace(/\r/g,'%0D').replace(/"/g,'%22'),
11 +x=(n, a, e)=>{if(a.length<e){throw new TypeError(`Failed to execute '${n}' on 'FormData': ${e} arguments required, but only ${a.length} present.`)}}
12 +
13 +export const File = F
14 +
15 +/** @type {typeof globalThis.FormData} */
16 +export const FormData = class FormData {
17 +#d=[];
18 +constructor(...a){if(a.length)throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`)}
19 +get [t]() {return 'FormData'}
20 +[i](){return this.entries()}
21 +static [h](o) {return o&&typeof o==='object'&&o[t]==='FormData'&&!m.some(m=>typeof o[m]!='function')}
22 +append(...a){x('append',arguments,2);this.#d.push(f(...a))}
23 +delete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)}
24 +get(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;c<l;c++)if(b[c][0]===a)return b[c][1];return null}
25 +getAll(a,b){x('getAll',arguments,1);b=[];a+='';this.#d.forEach(c=>c[0]===a&&b.push(c[1]));return b}
26 +has(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)}
27 +forEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)}
28 +set(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b}
29 +*entries(){yield*this.#d}
30 +*keys(){for(var[a]of this)yield a}
31 +*values(){for(var[,a]of this)yield a}}
32 +
33 +/** @param {FormData} F */
34 +export function formDataToBlob (F,B=C){
35 +var b=`${r()}${r()}`.replace(/\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\r\nContent-Disposition: form-data; name="`
36 +F.forEach((v,n)=>typeof v=='string'
37 +?c.push(p+e(n)+`"\r\n\r\n${v.replace(/\r(?!\n)|(?<!\r)\n/g, '\r\n')}\r\n`)
38 +:c.push(p+e(n)+`"; filename="${e(v.name, 1)}"\r\nContent-Type: ${v.type||"application/octet-stream"}\r\n\r\n`, v, '\r\n'))
39 +c.push(`--${b}--`)
40 +return new B(c,{type:"multipart/form-data; boundary="+b})}
1 +/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +const escape = (str, filename) =>
4 + (filename ? str : str.replace(/\r?\n|\r/g, '\r\n'))
5 + .replace(/\n/g, '%0A')
6 + .replace(/\r/g, '%0D')
7 + .replace(/"/g, '%22')
8 +
9 +/**
10 + * pure function to convert any formData instance to a Blob
11 + * instances synchronous without reading all of the files
12 + *
13 + * @param {FormData|*} formData an instance of a formData Class
14 + * @param {Blob|*} [BlobClass=Blob] the Blob class to use when constructing it
15 + */
16 +export function formDataToBlob (formData, BlobClass = Blob) {
17 + const boundary = ('----formdata-polyfill-' + Math.random())
18 + const chunks = []
19 + const prefix = `--${boundary}\r\nContent-Disposition: form-data; name="`
20 +
21 + for (let [name, value] of formData) {
22 + if (typeof value === 'string') {
23 + chunks.push(prefix + escape(name) + `"\r\n\r\n${value.replace(/\r(?!\n)|(?<!\r)\n/g, '\r\n')}\r\n`)
24 + } else {
25 + chunks.push(
26 + prefix + escape(name) + `"; filename="${escape(value.name, 1)}"\r\n` +
27 + `Content-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`,
28 + value,
29 + '\r\n'
30 + )
31 + }
32 + }
33 +
34 + chunks.push(`--${boundary}--`)
35 +
36 + return new BlobClass(chunks, {
37 + type: 'multipart/form-data; boundary=' + boundary
38 + })
39 +}
1 +/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */
2 +;(function(){var h;function l(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}}var m="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};
3 +function n(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");}var q=n(this);function r(a,b){if(b)a:{var c=q;a=a.split(".");for(var d=0;d<a.length-1;d++){var e=a[d];if(!(e in c))break a;c=c[e]}a=a[a.length-1];d=c[a];b=b(d);b!=d&&null!=b&&m(c,a,{configurable:!0,writable:!0,value:b})}}
4 +r("Symbol",function(a){function b(f){if(this instanceof b)throw new TypeError("Symbol is not a constructor");return new c(d+(f||"")+"_"+e++,f)}function c(f,g){this.A=f;m(this,"description",{configurable:!0,writable:!0,value:g})}if(a)return a;c.prototype.toString=function(){return this.A};var d="jscomp_symbol_"+(1E9*Math.random()>>>0)+"_",e=0;return b});
5 +r("Symbol.iterator",function(a){if(a)return a;a=Symbol("Symbol.iterator");for(var b="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),c=0;c<b.length;c++){var d=q[b[c]];"function"===typeof d&&"function"!=typeof d.prototype[a]&&m(d.prototype,a,{configurable:!0,writable:!0,value:function(){return u(l(this))}})}return a});function u(a){a={next:a};a[Symbol.iterator]=function(){return this};return a}
6 +function v(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):{next:l(a)}}var w;if("function"==typeof Object.setPrototypeOf)w=Object.setPrototypeOf;else{var y;a:{var z={a:!0},A={};try{A.__proto__=z;y=A.a;break a}catch(a){}y=!1}w=y?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null}var B=w;function C(){this.m=!1;this.j=null;this.v=void 0;this.h=1;this.u=this.C=0;this.l=null}
7 +function D(a){if(a.m)throw new TypeError("Generator is already running");a.m=!0}C.prototype.o=function(a){this.v=a};C.prototype.s=function(a){this.l={D:a,F:!0};this.h=this.C||this.u};C.prototype.return=function(a){this.l={return:a};this.h=this.u};function E(a,b){a.h=3;return{value:b}}function F(a){this.g=new C;this.G=a}F.prototype.o=function(a){D(this.g);if(this.g.j)return G(this,this.g.j.next,a,this.g.o);this.g.o(a);return H(this)};
8 +function I(a,b){D(a.g);var c=a.g.j;if(c)return G(a,"return"in c?c["return"]:function(d){return{value:d,done:!0}},b,a.g.return);a.g.return(b);return H(a)}F.prototype.s=function(a){D(this.g);if(this.g.j)return G(this,this.g.j["throw"],a,this.g.o);this.g.s(a);return H(this)};
9 +function G(a,b,c,d){try{var e=b.call(a.g.j,c);if(!(e instanceof Object))throw new TypeError("Iterator result "+e+" is not an object");if(!e.done)return a.g.m=!1,e;var f=e.value}catch(g){return a.g.j=null,a.g.s(g),H(a)}a.g.j=null;d.call(a.g,f);return H(a)}function H(a){for(;a.g.h;)try{var b=a.G(a.g);if(b)return a.g.m=!1,{value:b.value,done:!1}}catch(c){a.g.v=void 0,a.g.s(c)}a.g.m=!1;if(a.g.l){b=a.g.l;a.g.l=null;if(b.F)throw b.D;return{value:b.return,done:!0}}return{value:void 0,done:!0}}
10 +function J(a){this.next=function(b){return a.o(b)};this.throw=function(b){return a.s(b)};this.return=function(b){return I(a,b)};this[Symbol.iterator]=function(){return this}}function K(a,b){b=new J(new F(b));B&&a.prototype&&B(b,a.prototype);return b}function L(a,b){a instanceof String&&(a+="");var c=0,d=!1,e={next:function(){if(!d&&c<a.length){var f=c++;return{value:b(f,a[f]),done:!1}}d=!0;return{done:!0,value:void 0}}};e[Symbol.iterator]=function(){return e};return e}
11 +r("Array.prototype.entries",function(a){return a?a:function(){return L(this,function(b,c){return[b,c]})}});
12 +if("undefined"!==typeof Blob&&("undefined"===typeof FormData||!FormData.prototype.keys)){var M=function(a,b){for(var c=0;c<a.length;c++)b(a[c])},N=function(a){return a.replace(/\r?\n|\r/g,"\r\n")},O=function(a,b,c){if(b instanceof Blob){c=void 0!==c?String(c+""):"string"===typeof b.name?b.name:"blob";if(b.name!==c||"[object Blob]"===Object.prototype.toString.call(b))b=new File([b],c);return[String(a),b]}return[String(a),String(b)]},P=function(a,b){if(a.length<b)throw new TypeError(b+" argument required, but only "+
13 +a.length+" present.");},Q="object"===typeof globalThis?globalThis:"object"===typeof window?window:"object"===typeof self?self:this,R=Q.FormData,S=Q.XMLHttpRequest&&Q.XMLHttpRequest.prototype.send,T=Q.Request&&Q.fetch,U=Q.navigator&&Q.navigator.sendBeacon,V=Q.Element&&Q.Element.prototype,W=Q.Symbol&&Symbol.toStringTag;W&&(Blob.prototype[W]||(Blob.prototype[W]="Blob"),"File"in Q&&!File.prototype[W]&&(File.prototype[W]="File"));try{new File([],"")}catch(a){Q.File=function(b,c,d){b=new Blob(b,d||{});
14 +Object.defineProperties(b,{name:{value:c},lastModified:{value:+(d&&void 0!==d.lastModified?new Date(d.lastModified):new Date)},toString:{value:function(){return"[object File]"}}});W&&Object.defineProperty(b,W,{value:"File"});return b}}var escape=function(a){return a.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},X=function(a){this.i=[];var b=this;a&&M(a.elements,function(c){if(c.name&&!c.disabled&&"submit"!==c.type&&"button"!==c.type&&!c.matches("form fieldset[disabled] *"))if("file"===
15 +c.type){var d=c.files&&c.files.length?c.files:[new File([],"",{type:"application/octet-stream"})];M(d,function(e){b.append(c.name,e)})}else"select-multiple"===c.type||"select-one"===c.type?M(c.options,function(e){!e.disabled&&e.selected&&b.append(c.name,e.value)}):"checkbox"===c.type||"radio"===c.type?c.checked&&b.append(c.name,c.value):(d="textarea"===c.type?N(c.value):c.value,b.append(c.name,d))})};h=X.prototype;h.append=function(a,b,c){P(arguments,2);this.i.push(O(a,b,c))};h.delete=function(a){P(arguments,
16 +1);var b=[];a=String(a);M(this.i,function(c){c[0]!==a&&b.push(c)});this.i=b};h.entries=function b(){var c,d=this;return K(b,function(e){1==e.h&&(c=0);if(3!=e.h)return c<d.i.length?e=E(e,d.i[c]):(e.h=0,e=void 0),e;c++;e.h=2})};h.forEach=function(b,c){P(arguments,1);for(var d=v(this),e=d.next();!e.done;e=d.next()){var f=v(e.value);e=f.next().value;f=f.next().value;b.call(c,f,e,this)}};h.get=function(b){P(arguments,1);var c=this.i;b=String(b);for(var d=0;d<c.length;d++)if(c[d][0]===b)return c[d][1];
17 +return null};h.getAll=function(b){P(arguments,1);var c=[];b=String(b);M(this.i,function(d){d[0]===b&&c.push(d[1])});return c};h.has=function(b){P(arguments,1);b=String(b);for(var c=0;c<this.i.length;c++)if(this.i[c][0]===b)return!0;return!1};h.keys=function c(){var d=this,e,f,g,k,p;return K(c,function(t){1==t.h&&(e=v(d),f=e.next());if(3!=t.h){if(f.done){t.h=0;return}g=f.value;k=v(g);p=k.next().value;return E(t,p)}f=e.next();t.h=2})};h.set=function(c,d,e){P(arguments,2);c=String(c);var f=[],g=O(c,
18 +d,e),k=!0;M(this.i,function(p){p[0]===c?k&&(k=!f.push(g)):f.push(p)});k&&f.push(g);this.i=f};h.values=function d(){var e=this,f,g,k,p,t;return K(d,function(x){1==x.h&&(f=v(e),g=f.next());if(3!=x.h){if(g.done){x.h=0;return}k=g.value;p=v(k);p.next();t=p.next().value;return E(x,t)}g=f.next();x.h=2})};X.prototype._asNative=function(){for(var d=new R,e=v(this),f=e.next();!f.done;f=e.next()){var g=v(f.value);f=g.next().value;g=g.next().value;d.append(f,g)}return d};X.prototype._blob=function(){var d="----formdata-polyfill-"+
19 +Math.random(),e=[],f="--"+d+'\r\nContent-Disposition: form-data; name="';this.forEach(function(g,k){return"string"==typeof g?e.push(f+escape(N(k))+('"\r\n\r\n'+N(g)+"\r\n")):e.push(f+escape(N(k))+('"; filename="'+escape(g.name)+'"\r\nContent-Type: '+(g.type||"application/octet-stream")+"\r\n\r\n"),g,"\r\n")});e.push("--"+d+"--");return new Blob(e,{type:"multipart/form-data; boundary="+d})};X.prototype[Symbol.iterator]=function(){return this.entries()};X.prototype.toString=function(){return"[object FormData]"};
20 +V&&!V.matches&&(V.matches=V.matchesSelector||V.mozMatchesSelector||V.msMatchesSelector||V.oMatchesSelector||V.webkitMatchesSelector||function(d){d=(this.document||this.ownerDocument).querySelectorAll(d);for(var e=d.length;0<=--e&&d.item(e)!==this;);return-1<e});W&&(X.prototype[W]="FormData");if(S){var Y=Q.XMLHttpRequest.prototype.setRequestHeader;Q.XMLHttpRequest.prototype.setRequestHeader=function(d,e){Y.call(this,d,e);"content-type"===d.toLowerCase()&&(this.B=!0)};Q.XMLHttpRequest.prototype.send=
21 +function(d){d instanceof X?(d=d._blob(),this.B||this.setRequestHeader("Content-Type",d.type),S.call(this,d)):S.call(this,d)}}T&&(Q.fetch=function(d,e){e&&e.body&&e.body instanceof X&&(e.body=e.body._blob());return T.call(this,d,e)});U&&(Q.navigator.sendBeacon=function(d,e){e instanceof X&&(e=e._asNative());return U.call(this,d,e)});Q.FormData=X};})();
1 +{
2 + "name": "formdata-polyfill",
3 + "version": "4.0.10",
4 + "description": "HTML5 `FormData` for Browsers and Node.",
5 + "type": "module",
6 + "main": "formdata.min.js",
7 + "scripts": {
8 + "build": "node build.js",
9 + "test": "node test/test-esm.js",
10 + "test-wpt": "node --experimental-loader ./test/http-loader.js ./test/test-wpt-in-node.js",
11 + "test-polyfill": "php -S localhost:4445 & open http://localhost:4445/test/test-polyfill.html"
12 + },
13 + "repository": {
14 + "type": "git",
15 + "url": "git+https://jimmywarting@github.com/jimmywarting/FormData.git"
16 + },
17 + "files": [
18 + "esm.min.js",
19 + "esm.min.d.ts",
20 + "FormData.js",
21 + "formdata-to-blob.js",
22 + "formdata.min.js",
23 + "README.md"
24 + ],
25 + "engines": {
26 + "node": ">=12.20.0"
27 + },
28 + "keywords": [
29 + "formdata",
30 + "fetch",
31 + "node-fetch",
32 + "html5",
33 + "browser",
34 + "polyfill"
35 + ],
36 + "author": "Jimmy Wärting",
37 + "license": "MIT",
38 + "bugs": {
39 + "url": "https://github.com/jimmywarting/FormData/issues"
40 + },
41 + "homepage": "https://github.com/jimmywarting/FormData#readme",
42 + "dependencies": {
43 + "fetch-blob": "^3.1.2"
44 + },
45 + "devDependencies": {
46 + "@types/google-closure-compiler": "^0.0.19",
47 + "@types/node": "^16.7.10",
48 + "google-closure-compiler": "^20210808.0.0"
49 + }
50 +}
1 +# node-domexception
2 +An implementation of the DOMException class from NodeJS
1 +# DOMException
2 +An implementation of the DOMException class from NodeJS
3 +
4 +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself.
5 +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere.
6 +
7 +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor.
8 +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
9 +The instanceof check would not have worked with a custom class such as the DOMexception provided by domenic which also is much larger in size.
10 +
11 +```js
12 +import DOMException from 'node-domexception'
13 +
14 +hello().catch(err => {
15 + if (err instanceof DOMException) {
16 + ...
17 + }
18 +})
19 +
20 +const e1 = new DOMException("Something went wrong", "BadThingsError");
21 +console.assert(e1.name === "BadThingsError");
22 +console.assert(e1.code === 0);
23 +
24 +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError");
25 +console.assert(e2.name === "NoModificationAllowedError");
26 +console.assert(e2.code === 7);
27 +
28 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10);
29 +```
30 +
31 +## APIs
32 +
33 +This package exposes two flavors of the `DOMException` interface depending on the imported module.
34 +
35 +### `domexception` module
36 +
37 +This module default-exports the `DOMException` interface constructor.
38 +
39 +### `domexception/webidl2js-wrapper` module
40 +
41 +This module exports the `DOMException` [interface wrapper API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js).
1 +# DOMException
2 +An implementation of the DOMException class from NodeJS
3 +
4 +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. (including the legacy codes)
5 +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere.
6 +
7 +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor.
8 +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
9 +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size.
10 +
11 +```js
12 +import DOMException from 'node-domexception'
13 +import { MessageChannel } from 'worker_threads'
14 +
15 +async function hello() {
16 + const port = new MessageChannel().port1
17 + const ab = new ArrayBuffer()
18 + port.postMessage(ab, [ab, ab])
19 +}
20 +
21 +hello().catch(err => {
22 + console.assert(err.name === 'DataCloneError')
23 + console.assert(err.code === 25)
24 + console.assert(err instanceof DOMException)
25 +})
26 +
27 +const e1 = new DOMException('Something went wrong', 'BadThingsError')
28 +console.assert(e1.name === 'BadThingsError')
29 +console.assert(e1.code === 0)
30 +
31 +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError')
32 +console.assert(e2.name === 'NoModificationAllowedError')
33 +console.assert(e2.code === 7)
34 +
35 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10)
36 +```
1 +# DOMException
2 +An implementation of the DOMException class from NodeJS
3 +
4 +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including the legacy codes)
5 +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere.
6 +
7 +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor.
8 +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
9 +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size.
10 +
11 +```js
12 +import DOMException from 'node-domexception'
13 +import { MessageChannel } from 'worker_threads'
14 +
15 +async function hello() {
16 + const port = new MessageChannel().port1
17 + const ab = new ArrayBuffer()
18 + port.postMessage(ab, [ab, ab])
19 +}
20 +
21 +hello().catch(err => {
22 + console.assert(err.name === 'DataCloneError')
23 + console.assert(err.code === 25)
24 + console.assert(err instanceof DOMException)
25 +})
26 +
27 +const e1 = new DOMException('Something went wrong', 'BadThingsError')
28 +console.assert(e1.name === 'BadThingsError')
29 +console.assert(e1.code === 0)
30 +
31 +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError')
32 +console.assert(e2.name === 'NoModificationAllowedError')
33 +console.assert(e2.code === 7)
34 +
35 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10)
36 +```
1 +# DOMException
2 +An implementation of the DOMException class from NodeJS
3 +
4 +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes)
5 +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere.
6 +
7 +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor.
8 +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
9 +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up.
10 +
11 +```js
12 +import DOMException from 'node-domexception'
13 +import { MessageChannel } from 'worker_threads'
14 +
15 +async function hello() {
16 + const port = new MessageChannel().port1
17 + const ab = new ArrayBuffer()
18 + port.postMessage(ab, [ab, ab])
19 +}
20 +
21 +hello().catch(err => {
22 + console.assert(err.name === 'DataCloneError')
23 + console.assert(err.code === 25)
24 + console.assert(err instanceof DOMException)
25 +})
26 +
27 +const e1 = new DOMException('Something went wrong', 'BadThingsError')
28 +console.assert(e1.name === 'BadThingsError')
29 +console.assert(e1.code === 0)
30 +
31 +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError')
32 +console.assert(e2.name === 'NoModificationAllowedError')
33 +console.assert(e2.code === 7)
34 +
35 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10)
36 +```
1 +# DOMException
2 +An implementation of the DOMException class from NodeJS
3 +
4 +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes)
5 +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere.
6 +
7 +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor.
8 +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
9 +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up.
10 +
11 +(plz don't depend on this package in any other environment other than node >=10.5)
12 +
13 +```js
14 +import DOMException from 'node-domexception'
15 +import { MessageChannel } from 'worker_threads'
16 +
17 +async function hello() {
18 + const port = new MessageChannel().port1
19 + const ab = new ArrayBuffer()
20 + port.postMessage(ab, [ab, ab])
21 +}
22 +
23 +hello().catch(err => {
24 + console.assert(err.name === 'DataCloneError')
25 + console.assert(err.code === 25)
26 + console.assert(err instanceof DOMException)
27 +})
28 +
29 +const e1 = new DOMException('Something went wrong', 'BadThingsError')
30 +console.assert(e1.name === 'BadThingsError')
31 +console.assert(e1.code === 0)
32 +
33 +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError')
34 +console.assert(e2.name === 'NoModificationAllowedError')
35 +console.assert(e2.code === 7)
36 +
37 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10)
38 +```
1 +# DOMException
2 +An implementation of the DOMException class from NodeJS
3 +
4 +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes)
5 +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere.
6 +
7 +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor.
8 +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
9 +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up.
10 +
11 +(plz don't depend on this package in any other environment other than node >=10.5)
12 +
13 +```js
14 +import DOMException from 'node-domexception'
15 +import { MessageChannel } from 'worker_threads'
16 +
17 +async function hello() {
18 + const port = new MessageChannel().port1
19 + const ab = new ArrayBuffer()
20 + port.postMessage(ab, [ab, ab])
21 +}
22 +
23 +hello().catch(err => {
24 + console.assert(err.name === 'DataCloneError')
25 + console.assert(err.code === 25)
26 + console.assert(err instanceof DOMException)
27 +})
28 +
29 +const e1 = new DOMException('Something went wrong', 'BadThingsError')
30 +console.assert(e1.name === 'BadThingsError')
31 +console.assert(e1.code === 0)
32 +
33 +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError')
34 +console.assert(e2.name === 'NoModificationAllowedError')
35 +console.assert(e2.code === 7)
36 +
37 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10)
38 +```
1 +const { MessageChannel } = require('worker_threads')
2 +
3 +if (!globalThis.DOMException) {
4 + const port = new MessageChannel().port1
5 + const ab = new ArrayBuffer()
6 + try { port.postMessage(ab, [ab, ab]) }
7 + catch (err) { globalThis.DOMException = err.constructor }
8 +}
1 +if (!globalThis.DOMException) {
2 + const { MessageChannel } = require('worker_threads')
3 + const port = new MessageChannel().port1
4 + const ab = new ArrayBuffer()
5 + try { port.postMessage(ab, [ab, ab]) }
6 + catch (err) { globalThis.DOMException = err.constructor }
7 +}
8 +
9 +module.exports
1 +if (!globalThis.DOMException) {
2 + const { MessageChannel } = require('worker_threads')
3 + const port = new MessageChannel().port1
4 + const ab = new ArrayBuffer()
5 + try { port.postMessage(ab, [ab, ab]) }
6 + catch (err) { globalThis.DOMException = err.constructor }
7 +}
8 +
9 +module.exports = globalThis.DOMException
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads')
5 + const port = new MessageChannel().port1
6 + const ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) { globalThis.DOMException = err.constructor }
9 +}
10 +
11 +module.exports = globalThis.DOMException
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads')
5 + const port = new MessageChannel().port1
6 + const ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) { globalThis.DOMException = err.constructor }
9 +}
10 +
11 +module.exports = globalThis.DOMException
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + var { MessageChannel } = require('worker_threads'),
5 + port = new MessageChannel().port1,
6 + ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) {
9 + err.constructor.name === 'DOMException' && (
10 + globalThis.DOMException = err.constructor
11 + )
12 + }
13 +}
14 +
15 +module.exports = globalThis.DOMException
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads'),
5 + port = new MessageChannel().port1,
6 + ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) {
9 + err.constructor.name === 'DOMException' && (
10 + globalThis.DOMException = err.constructor
11 + )
12 + }
13 +}
14 +
15 +module.exports = globalThis.DOMException
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads'),
5 + port = new MessageChannel().port1,
6 + ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) {
9 + err.constructor.name === 'DOMException' && (
10 + globalThis.DOMException = err.constructor
11 + )
12 + }
13 +}
14 +
15 +module.exports = globalThis.DOMException
16 +
17 +const e1 = new DOMException("Something went wrong", "BadThingsError");
18 +console.assert(e1.name === "BadThingsError");
19 +console.assert(e1.code === 0);
20 +
21 +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError");
22 +console.assert(e2.name === "NoModificationAllowedError");
23 +console.assert(e2.code === 7);
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads'),
5 + port = new MessageChannel().port1,
6 + ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) {
9 + err.constructor.name === 'DOMException' && (
10 + globalThis.DOMException = err.constructor
11 + )
12 + }
13 +}
14 +
15 +module.exports = globalThis.DOMException
16 +
17 +const e1 = new DOMException("Something went wrong", "BadThingsError");
18 +console.assert(e1.name === "BadThingsError");
19 +console.assert(e1.code === 0);
20 +
21 +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError");
22 +console.assert(e2.name === "NoModificationAllowedError");
23 +console.assert(e2.code === 2);
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads'),
5 + port = new MessageChannel().port1,
6 + ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) {
9 + err.constructor.name === 'DOMException' && (
10 + globalThis.DOMException = err.constructor
11 + )
12 + }
13 +}
14 +
15 +module.exports = globalThis.DOMException
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads'),
5 + port = new MessageChannel().port1,
6 + ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) {
9 + console.log(err.code)
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
1 +/*! blob-to-buffer. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads'),
5 + port = new MessageChannel().port1,
6 + ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) {
9 + console.log(err.code, err.name, err.message)
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
1 +/*! node-DOMException. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + const { MessageChannel } = require('worker_threads'),
5 + port = new MessageChannel().port1,
6 + ab = new ArrayBuffer()
7 + try { port.postMessage(ab, [ab, ab]) }
8 + catch (err) {
9 + console.log(err.code, err.name, err.message)
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
1 +/*! node-DOMException. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + try {
5 + const { MessageChannel } = require('worker_threads'),
6 + port = new MessageChannel().port1,
7 + ab = new ArrayBuffer()
8 + port.postMessage(ab, [ab, ab])
9 + catch (err) {
10 + console.log(err.code, err.name, err.message)
11 + err.constructor.name === 'DOMException' && (
12 + globalThis.DOMException = err.constructor
13 + )
14 + }
15 +}
16 +
17 +module.exports = globalThis.DOMException
1 +/*! node-DOMException. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + try {
5 + const { MessageChannel } = require('worker_threads'),
6 + port = new MessageChannel().port1,
7 + ab = new ArrayBuffer()
8 + port.postMessage(ab, [ab, ab])
9 + } catch (err) {
10 + console.log(err.code, err.name, err.message)
11 + err.constructor.name === 'DOMException' && (
12 + globalThis.DOMException = err.constructor
13 + )
14 + }
15 +}
16 +
17 +module.exports = globalThis.DOMException
1 +/*! node-DOMException. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + try {
5 + const { MessageChannel } = require('worker_threads'),
6 + port = new MessageChannel().port1,
7 + ab = new ArrayBuffer()
8 + port.postMessage(ab, [ab, ab])
9 + } catch (err) {
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
1 +/*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + try {
5 + const { MessageChannel } = require('worker_threads'),
6 + port = new MessageChannel().port1,
7 + ab = new ArrayBuffer()
8 + port.postMessage(ab, [ab, ab])
9 + } catch (err) {
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
1 +/*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + try {
5 + const { MessageChannel } = require('worker_threads'),
6 + port = new MessageChannel().port1,
7 + ab = new ArrayBuffer()
8 + port.postMessage(ab, [ab, ab])
9 + } catch (err) {
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
17 +
18 +
19 +const { MessageChannel } = require('worker_threads')
20 +
21 +async function hello() {
22 + const port = new MessageChannel().port1
23 + const ab = new ArrayBuffer()
24 + port.postMessage(ab, [ab, ab])
25 +}
26 +
27 +hello().catch(err => {
28 + console.assert(err.name === 'DataCloneError')
29 + console.assert(err.code === 25)
30 + console.assert(err instanceof DOMException)
31 +})
32 +
33 +const e1 = new DOMException('Something went wrong', 'BadThingsError')
34 +console.assert(e1.name === 'BadThingsError')
35 +console.assert(e1.code === 0)
36 +
37 +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError')
38 +console.assert(e2.name === 'NoModificationAllowedError')
39 +console.assert(e2.code === 7)
40 +
41 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10)
1 +/*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + try {
5 + const { MessageChannel } = require('worker_threads'),
6 + port = new MessageChannel().port1,
7 + ab = new ArrayBuffer()
8 + port.postMessage(ab, [ab, ab])
9 + } catch (err) {
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
17 +
18 +
19 +const { MessageChannel } = require('worker_threads')
20 +
21 +async function hello() {
22 + const port = new MessageChannel().port1
23 + const ab = new ArrayBuffer()
24 + port.postMessage(ab, [ab, ab])
25 +}
26 +
27 +hello().catch(err => {
28 + console.assert(err.name === 'DataCloneError')
29 + console.assert(err.code === 21)
30 + console.assert(err instanceof DOMException)
31 +})
32 +
33 +const e1 = new DOMException('Something went wrong', 'BadThingsError')
34 +console.assert(e1.name === 'BadThingsError')
35 +console.assert(e1.code === 0)
36 +
37 +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError')
38 +console.assert(e2.name === 'NoModificationAllowedError')
39 +console.assert(e2.code === 7)
40 +
41 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10)
1 +/*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + try {
5 + const { MessageChannel } = require('worker_threads'),
6 + port = new MessageChannel().port1,
7 + ab = new ArrayBuffer()
8 + port.postMessage(ab, [ab, ab])
9 + } catch (err) {
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
1 +{
2 + "name": "domexception",
3 + "version": "1.0.0",
4 + "description": "An implementation of the DOMException class from NodeJS",
5 + "main": "index.js",
6 + "scripts": {
7 + "test": "echo \"Error: no test specified\" && exit 1"
8 + },
9 + "repository": {
10 + "type": "git",
11 + "url": "git+https://github.com/jimmywarting/node-domexception.git"
12 + },
13 + "author": "",
14 + "license": "ISC",
15 + "bugs": {
16 + "url": "https://github.com/jimmywarting/node-domexception/issues"
17 + },
18 + "homepage": "https://github.com/jimmywarting/node-domexception#readme"
19 +}
1 +{
2 + "name": "node-domexception",
3 + "version": "1.0.0",
4 + "description": "An implementation of the DOMException class from NodeJS",
5 + "main": "index.js",
6 + "repository": {
7 + "type": "git",
8 + "url": "git+https://github.com/jimmywarting/node-domexception.git"
9 + },
10 + "author": "Jimmy Wärting",
11 + "license": "MIT",
12 + "bugs": {
13 + "url": "https://github.com/jimmywarting/node-domexception/issues"
14 + },
15 + "homepage": "https://github.com/jimmywarting/node-domexception#readme"
16 +}
1 +{
2 + "name": "node-domexception",
3 + "version": "1.0.0",
4 + "description": "An implementation of the DOMException class from NodeJS",
5 + "main": "index.js",
6 + "repository": {
7 + "type": "git",
8 + "url": "git+https://github.com/jimmywarting/node-domexception.git"
9 + },
10 + "engines": {
11 + "node": ">=10.5.0"
12 + },
13 + "author": "Jimmy Wärting",
14 + "license": "MIT",
15 + "bugs": {
16 + "url": "https://github.com/jimmywarting/node-domexception/issues"
17 + },
18 + "homepage": "https://github.com/jimmywarting/node-domexception#readme"
19 +}
1 +{
2 + "name": "node-domexception",
3 + "version": "1.0.0",
4 + "description": "An implementation of the DOMException class from NodeJS",
5 + "main": "index.js",
6 + "repository": {
7 + "type": "git",
8 + "url": "git+https://github.com/jimmywarting/node-domexception.git"
9 + },
10 + "engines": {
11 + "node": ">=10.5.0"
12 + },
13 + "author": "Jimmy Wärting",
14 + "license": "MIT",
15 + "bugs": {
16 + "url": "https://github.com/jimmywarting/node-domexception/issues"
17 + },
18 + "homepage": "https://github.com/jimmywarting/node-domexception#readme",
19 + "funding": [
20 + {
21 + "type": "github",
22 + "url": "https://github.com/sponsors/jimmywarting"
23 + }
24 + ]
25 +}
1 +{
2 + "name": "node-domexception",
3 + "version": "1.0.0",
4 + "description": "An implementation of the DOMException class from NodeJS",
5 + "main": "index.js",
6 + "repository": {
7 + "type": "git",
8 + "url": "git+https://github.com/jimmywarting/node-domexception.git"
9 + },
10 + "engines": {
11 + "node": ">=10.5.0"
12 + },
13 + "author": "Jimmy Wärting",
14 + "license": "MIT",
15 + "bugs": {
16 + "url": "https://github.com/jimmywarting/node-domexception/issues"
17 + },
18 + "homepage": "https://github.com/jimmywarting/node-domexception#readme",
19 + "funding": [
20 + {
21 + "type": "github",
22 + "url": "https://github.com/sponsors/jimmywarting"
23 + }
24 + ]
25 +}
1 +{
2 + "name": "node-domexception",
3 + "version": "1.0.0",
4 + "description": "An implementation of the DOMException class from NodeJS",
5 + "main": "index.js",
6 + "repository": {
7 + "type": "git",
8 + "url": "git+https://github.com/jimmywarting/node-domexception.git"
9 + },
10 + "engines": {
11 + "node": ">=10.5.0"
12 + },
13 + "author": "Jimmy Wärting",
14 + "license": "MIT",
15 + "bugs": {
16 + "url": "https://github.com/jimmywarting/node-domexception/issues"
17 + },
18 + "homepage": "https://github.com/jimmywarting/node-domexception#readme",
19 + "funding": [
20 + {
21 + "type": "github",
22 + "url": "https://github.com/sponsors/jimmywarting"
23 + },
24 + {
25 + "type": "github",
26 + "url": "https://paypal.me/jimmywarting"
27 + }
28 + ]
29 +}
1 +{
2 + "name": "node-domexception",
3 + "version": "1.0.0",
4 + "description": "An implementation of the DOMException class from NodeJS",
5 + "main": "index.js",
6 + "repository": {
7 + "type": "git",
8 + "url": "git+https://github.com/jimmywarting/node-domexception.git"
9 + },
10 + "engines": {
11 + "node": ">=10.5.0"
12 + },
13 + "author": "Jimmy Wärting",
14 + "license": "MIT",
15 + "bugs": {
16 + "url": "https://github.com/jimmywarting/node-domexception/issues"
17 + },
18 + "homepage": "https://github.com/jimmywarting/node-domexception#readme",
19 + "funding": [
20 + {
21 + "type": "github",
22 + "url": "https://github.com/sponsors/jimmywarting"
23 + },
24 + {
25 + "type": "github",
26 + "url": "https://paypal.me/jimmywarting"
27 + }
28 + ]
29 +}
1 +require('./index.js')
2 +
3 +console.log(DOMException.INDEX_SIZE_ERR)
1 +const e = require('./index.js')
2 +
3 +console.log(e.INDEX_SIZE_ERR)
1 +MIT License
2 +
3 +Copyright (c) 2021 Jimmy Wärting
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
1 +# DOMException
2 +An implementation of the DOMException class from NodeJS
3 +
4 +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere.
5 +
6 +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the legacy codes)
7 +
8 +<sub>(plz don't depend on this package in any other environment other than node >=10.5)</sub>
9 +
10 +```js
11 +import DOMException from 'node-domexception'
12 +import { MessageChannel } from 'worker_threads'
13 +
14 +async function hello() {
15 + const port = new MessageChannel().port1
16 + const ab = new ArrayBuffer()
17 + port.postMessage(ab, [ab, ab])
18 +}
19 +
20 +hello().catch(err => {
21 + console.assert(err.name === 'DataCloneError')
22 + console.assert(err.code === 25)
23 + console.assert(err instanceof DOMException)
24 +})
25 +
26 +const e1 = new DOMException('Something went wrong', 'BadThingsError')
27 +console.assert(e1.name === 'BadThingsError')
28 +console.assert(e1.code === 0)
29 +
30 +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError')
31 +console.assert(e2.name === 'NoModificationAllowedError')
32 +console.assert(e2.code === 7)
33 +
34 +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10)
35 +```
36 +
37 +# Background
38 +
39 +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws a DOMException and catch the constructor. This is exactly what this package dose for you and exposes it.<br>
40 +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.<br>
41 +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up.
42 +
43 +The DOMException is used in many places such as the Fetch API, File & Blobs, PostMessaging and more. <br>
44 +Why they decided to call it **DOM**, I don't know
45 +
46 +Please consider sponsoring if you find this helpful
1 +/*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
2 +
3 +if (!globalThis.DOMException) {
4 + try {
5 + const { MessageChannel } = require('worker_threads'),
6 + port = new MessageChannel().port1,
7 + ab = new ArrayBuffer()
8 + port.postMessage(ab, [ab, ab])
9 + } catch (err) {
10 + err.constructor.name === 'DOMException' && (
11 + globalThis.DOMException = err.constructor
12 + )
13 + }
14 +}
15 +
16 +module.exports = globalThis.DOMException
1 +{
2 + "name": "node-domexception",
3 + "version": "1.0.0",
4 + "description": "An implementation of the DOMException class from NodeJS",
5 + "main": "index.js",
6 + "repository": {
7 + "type": "git",
8 + "url": "git+https://github.com/jimmywarting/node-domexception.git"
9 + },
10 + "engines": {
11 + "node": ">=10.5.0"
12 + },
13 + "author": "Jimmy Wärting",
14 + "license": "MIT",
15 + "bugs": {
16 + "url": "https://github.com/jimmywarting/node-domexception/issues"
17 + },
18 + "homepage": "https://github.com/jimmywarting/node-domexception#readme",
19 + "funding": [
20 + {
21 + "type": "github",
22 + "url": "https://github.com/sponsors/jimmywarting"
23 + },
24 + {
25 + "type": "github",
26 + "url": "https://paypal.me/jimmywarting"
27 + }
28 + ]
29 +}
1 +/// <reference types="node" />
2 +/// <reference lib="dom" />
3 +
4 +import {RequestOptions} from 'http';
5 +import {FormData} from 'formdata-polyfill/esm.min.js';
6 +import {
7 + Blob,
8 + blobFrom,
9 + blobFromSync,
10 + File,
11 + fileFrom,
12 + fileFromSync
13 +} from 'fetch-blob/from.js';
14 +
15 +type AbortSignal = {
16 + readonly aborted: boolean;
17 +
18 + addEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void;
19 + removeEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void;
20 +};
21 +
22 +export type HeadersInit = Headers | Record<string, string> | Iterable<readonly [string, string]> | Iterable<Iterable<string>>;
23 +
24 +export {
25 + FormData,
26 + Blob,
27 + blobFrom,
28 + blobFromSync,
29 + File,
30 + fileFrom,
31 + fileFromSync
32 +};
33 +
34 +/**
35 + * This Fetch API interface allows you to perform various actions on HTTP request and response headers.
36 + * These actions include retrieving, setting, adding to, and removing.
37 + * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.
38 + * You can add to this using methods like append() (see Examples.)
39 + * In all methods of this interface, header names are matched by case-insensitive byte sequence.
40 + * */
41 +export class Headers {
42 + constructor(init?: HeadersInit);
43 +
44 + append(name: string, value: string): void;
45 + delete(name: string): void;
46 + get(name: string): string | null;
47 + has(name: string): boolean;
48 + set(name: string, value: string): void;
49 + forEach(
50 + callbackfn: (value: string, key: string, parent: Headers) => void,
51 + thisArg?: any
52 + ): void;
53 +
54 + [Symbol.iterator](): IterableIterator<[string, string]>;
55 + /**
56 + * Returns an iterator allowing to go through all key/value pairs contained in this object.
57 + */
58 + entries(): IterableIterator<[string, string]>;
59 + /**
60 + * Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.
61 + */
62 + keys(): IterableIterator<string>;
63 + /**
64 + * Returns an iterator allowing to go through all values of the key/value pairs contained in this object.
65 + */
66 + values(): IterableIterator<string>;
67 +
68 + /** Node-fetch extension */
69 + raw(): Record<string, string[]>;
70 +}
71 +
72 +export interface RequestInit {
73 + /**
74 + * A BodyInit object or null to set request's body.
75 + */
76 + body?: BodyInit | null;
77 + /**
78 + * A Headers object, an object literal, or an array of two-item arrays to set request's headers.
79 + */
80 + headers?: HeadersInit;
81 + /**
82 + * A string to set request's method.
83 + */
84 + method?: string;
85 + /**
86 + * A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect.
87 + */
88 + redirect?: RequestRedirect;
89 + /**
90 + * An AbortSignal to set request's signal.
91 + */
92 + signal?: AbortSignal | null;
93 + /**
94 + * A string whose value is a same-origin URL, "about:client", or the empty string, to set request’s referrer.
95 + */
96 + referrer?: string;
97 + /**
98 + * A referrer policy to set request’s referrerPolicy.
99 + */
100 + referrerPolicy?: ReferrerPolicy;
101 +
102 + // Node-fetch extensions to the whatwg/fetch spec
103 + agent?: RequestOptions['agent'] | ((parsedUrl: URL) => RequestOptions['agent']);
104 + compress?: boolean;
105 + counter?: number;
106 + follow?: number;
107 + hostname?: string;
108 + port?: number;
109 + protocol?: string;
110 + size?: number;
111 + highWaterMark?: number;
112 + insecureHTTPParser?: boolean;
113 +}
114 +
115 +export interface ResponseInit {
116 + headers?: HeadersInit;
117 + status?: number;
118 + statusText?: string;
119 +}
120 +
121 +export type BodyInit =
122 + | Blob
123 + | Buffer
124 + | URLSearchParams
125 + | FormData
126 + | NodeJS.ReadableStream
127 + | string;
128 +declare class BodyMixin {
129 + constructor(body?: BodyInit, options?: {size?: number});
130 +
131 + readonly body: NodeJS.ReadableStream | null;
132 + readonly bodyUsed: boolean;
133 + readonly size: number;
134 +
135 + /** @deprecated Use `body.arrayBuffer()` instead. */
136 + buffer(): Promise<Buffer>;
137 + arrayBuffer(): Promise<ArrayBuffer>;
138 + formData(): Promise<FormData>;
139 + blob(): Promise<Blob>;
140 + json(): Promise<unknown>;
141 + text(): Promise<string>;
142 +}
143 +
144 +// `Body` must not be exported as a class since it's not exported from the JavaScript code.
145 +export interface Body extends Pick<BodyMixin, keyof BodyMixin> {}
146 +
147 +export type RequestRedirect = 'error' | 'follow' | 'manual';
148 +export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';
149 +export type RequestInfo = string | Request;
150 +export class Request extends BodyMixin {
151 + constructor(input: RequestInfo, init?: RequestInit);
152 +
153 + /**
154 + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header.
155 + */
156 + readonly headers: Headers;
157 + /**
158 + * Returns request's HTTP method, which is "GET" by default.
159 + */
160 + readonly method: string;
161 + /**
162 + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.
163 + */
164 + readonly redirect: RequestRedirect;
165 + /**
166 + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.
167 + */
168 + readonly signal: AbortSignal;
169 + /**
170 + * Returns the URL of request as a string.
171 + */
172 + readonly url: string;
173 + /**
174 + * A string whose value is a same-origin URL, "about:client", or the empty string, to set request’s referrer.
175 + */
176 + readonly referrer: string;
177 + /**
178 + * A referrer policy to set request’s referrerPolicy.
179 + */
180 + readonly referrerPolicy: ReferrerPolicy;
181 + clone(): Request;
182 +}
183 +
184 +type ResponseType = 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect';
185 +
186 +export class Response extends BodyMixin {
187 + constructor(body?: BodyInit | null, init?: ResponseInit);
188 +
189 + readonly headers: Headers;
190 + readonly ok: boolean;
191 + readonly redirected: boolean;
192 + readonly status: number;
193 + readonly statusText: string;
194 + readonly type: ResponseType;
195 + readonly url: string;
196 + clone(): Response;
197 +
198 + static error(): Response;
199 + static redirect(url: string, status?: number): Response;
200 +}
201 +
202 +export class FetchError extends Error {
203 + constructor(message: string, type: string, systemError?: Record<string, unknown>);
204 +
205 + name: 'FetchError';
206 + [Symbol.toStringTag]: 'FetchError';
207 + type: string;
208 + code?: string;
209 + errno?: string;
210 +}
211 +
212 +export class AbortError extends Error {
213 + type: string;
214 + name: 'AbortError';
215 + [Symbol.toStringTag]: 'AbortError';
216 +}
217 +
218 +export function isRedirect(code: number): boolean;
219 +export default function fetch(url: RequestInfo, init?: RequestInit): Promise<Response>;
1 The MIT License (MIT) 1 The MIT License (MIT)
2 2
3 -Copyright (c) 2016 David Frank 3 +Copyright (c) 2016 - 2020 Node Fetch Team
4 4
5 Permission is hereby granted, free of charge, to any person obtaining a copy 5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal 6 of this software and associated documentation files (the "Software"), to deal
......
1 -node-fetch 1 +<div align="center">
2 -========== 2 + <img src="docs/media/Banner.svg" alt="Node Fetch"/>
3 - 3 + <br>
4 -[![npm version][npm-image]][npm-url] 4 + <p>A light-weight module that brings <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a> to Node.js.</p>
5 -[![build status][travis-image]][travis-url] 5 + <a href="https://github.com/node-fetch/node-fetch/actions"><img src="https://github.com/node-fetch/node-fetch/workflows/CI/badge.svg?branch=master" alt="Build status"></a>
6 -[![coverage status][codecov-image]][codecov-url] 6 + <a href="https://coveralls.io/github/node-fetch/node-fetch"><img src="https://img.shields.io/coveralls/github/node-fetch/node-fetch" alt="Coverage status"></a>
7 -[![install size][install-size-image]][install-size-url] 7 + <a href="https://packagephobia.now.sh/result?p=node-fetch"><img src="https://badgen.net/packagephobia/install/node-fetch" alt="Current version"></a>
8 -[![Discord][discord-image]][discord-url] 8 + <a href="https://www.npmjs.com/package/node-fetch"><img src="https://img.shields.io/npm/v/node-fetch" alt="Install size"></a>
9 - 9 + <a href="https://github.com/sindresorhus/awesome-nodejs"><img src="https://awesome.re/mentioned-badge.svg" alt="Mentioned in Awesome Node.js"></a>
10 -A light-weight module that brings `window.fetch` to Node.js 10 + <a href="https://discord.gg/Zxbndcm"><img src="https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord" alt="Discord"></a>
11 - 11 + <br>
12 -(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) 12 + <br>
13 - 13 + <b>Consider supporting us on our Open Collective:</b>
14 -[![Backers][opencollective-image]][opencollective-url] 14 + <br>
15 + <br>
16 + <a href="https://opencollective.com/node-fetch"><img src="https://opencollective.com/node-fetch/donate/button.png?color=blue" alt="Open Collective"></a>
17 +</div>
18 +
19 +---
20 +
21 +**You might be looking for the [v2 docs](https://github.com/node-fetch/node-fetch/tree/2.x#readme)**
15 22
16 <!-- TOC --> 23 <!-- TOC -->
17 24
...@@ -20,32 +27,53 @@ A light-weight module that brings `window.fetch` to Node.js ...@@ -20,32 +27,53 @@ A light-weight module that brings `window.fetch` to Node.js
20 - [Difference from client-side fetch](#difference-from-client-side-fetch) 27 - [Difference from client-side fetch](#difference-from-client-side-fetch)
21 - [Installation](#installation) 28 - [Installation](#installation)
22 - [Loading and configuring the module](#loading-and-configuring-the-module) 29 - [Loading and configuring the module](#loading-and-configuring-the-module)
30 +- [Upgrading](#upgrading)
23 - [Common Usage](#common-usage) 31 - [Common Usage](#common-usage)
24 - - [Plain text or HTML](#plain-text-or-html) 32 + - [Plain text or HTML](#plain-text-or-html)
25 - - [JSON](#json) 33 + - [JSON](#json)
26 - - [Simple Post](#simple-post) 34 + - [Simple Post](#simple-post)
27 - - [Post with JSON](#post-with-json) 35 + - [Post with JSON](#post-with-json)
28 - - [Post with form parameters](#post-with-form-parameters) 36 + - [Post with form parameters](#post-with-form-parameters)
29 - - [Handling exceptions](#handling-exceptions) 37 + - [Handling exceptions](#handling-exceptions)
30 - - [Handling client and server errors](#handling-client-and-server-errors) 38 + - [Handling client and server errors](#handling-client-and-server-errors)
39 + - [Handling cookies](#handling-cookies)
31 - [Advanced Usage](#advanced-usage) 40 - [Advanced Usage](#advanced-usage)
32 - - [Streams](#streams) 41 + - [Streams](#streams)
33 - - [Buffer](#buffer) 42 + - [Accessing Headers and other Metadata](#accessing-headers-and-other-metadata)
34 - - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) 43 + - [Extract Set-Cookie Header](#extract-set-cookie-header)
35 - - [Extract Set-Cookie Header](#extract-set-cookie-header) 44 + - [Post data using a file](#post-data-using-a-file)
36 - - [Post data using a file stream](#post-data-using-a-file-stream) 45 + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
37 - - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)
38 - - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
39 - [API](#api) 46 - [API](#api)
40 - - [fetch(url[, options])](#fetchurl-options) 47 + - [fetch(url[, options])](#fetchurl-options)
41 - - [Options](#options) 48 + - [Options](#options)
42 - - [Class: Request](#class-request) 49 + - [Default Headers](#default-headers)
43 - - [Class: Response](#class-response) 50 + - [Custom Agent](#custom-agent)
44 - - [Class: Headers](#class-headers) 51 + - [Custom highWaterMark](#custom-highwatermark)
45 - - [Interface: Body](#interface-body) 52 + - [Insecure HTTP Parser](#insecure-http-parser)
46 - - [Class: FetchError](#class-fetcherror) 53 + - [Class: Request](#class-request)
47 -- [License](#license) 54 + - [new Request(input[, options])](#new-requestinput-options)
55 + - [Class: Response](#class-response)
56 + - [new Response([body[, options]])](#new-responsebody-options)
57 + - [response.ok](#responseok)
58 + - [response.redirected](#responseredirected)
59 + - [response.type](#responsetype)
60 + - [Class: Headers](#class-headers)
61 + - [new Headers([init])](#new-headersinit)
62 + - [Interface: Body](#interface-body)
63 + - [body.body](#bodybody)
64 + - [body.bodyUsed](#bodybodyused)
65 + - [body.arrayBuffer()](#bodyarraybuffer)
66 + - [body.blob()](#bodyblob)
67 + - [body.formData()](#formdata)
68 + - [body.json()](#bodyjson)
69 + - [body.text()](#bodytext)
70 + - [Class: FetchError](#class-fetcherror)
71 + - [Class: AbortError](#class-aborterror)
72 +- [TypeScript](#typescript)
48 - [Acknowledgement](#acknowledgement) 73 - [Acknowledgement](#acknowledgement)
74 +- [Team](#team)
75 + - [Former](#former)
76 +- [License](#license)
49 77
50 <!-- /TOC --> 78 <!-- /TOC -->
51 79
...@@ -53,253 +81,418 @@ A light-weight module that brings `window.fetch` to Node.js ...@@ -53,253 +81,418 @@ A light-weight module that brings `window.fetch` to Node.js
53 81
54 Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. 82 Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.
55 83
56 -See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). 84 +See Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).
57 85
58 ## Features 86 ## Features
59 87
60 - Stay consistent with `window.fetch` API. 88 - Stay consistent with `window.fetch` API.
61 - Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. 89 - Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.
62 -- Use native promise but allow substituting it with [insert your favorite promise library]. 90 +- Use native promise and async functions.
63 -- Use native Node streams for body on both request and response. 91 +- Use native Node streams for body, on both request and response.
64 -- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. 92 +- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.
65 -- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. 93 +- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.
66 94
67 ## Difference from client-side fetch 95 ## Difference from client-side fetch
68 96
69 -- See [Known Differences](LIMITS.md) for details. 97 +- See known differences:
98 + - [As of v3.x](docs/v3-LIMITS.md)
99 + - [As of v2.x](docs/v2-LIMITS.md)
70 - If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. 100 - If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.
71 - Pull requests are welcomed too! 101 - Pull requests are welcomed too!
72 102
73 ## Installation 103 ## Installation
74 104
75 -Current stable release (`2.x`) 105 +Current stable release (`3.x`) requires at least Node.js 12.20.0.
76 106
77 ```sh 107 ```sh
78 -$ npm install node-fetch 108 +npm install node-fetch
79 ``` 109 ```
80 110
81 ## Loading and configuring the module 111 ## Loading and configuring the module
82 -We suggest you load the module via `require` until the stabilization of ES modules in node: 112 +
113 +### ES Modules (ESM)
114 +
83 ```js 115 ```js
84 -const fetch = require('node-fetch'); 116 +import fetch from 'node-fetch';
85 ``` 117 ```
86 118
87 -If you are using a Promise library other than native, set it through `fetch.Promise`: 119 +### CommonJS
120 +
121 +`node-fetch` from v3 is an ESM-only module - you are not able to import it with `require()`.
122 +
123 +If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.
124 +
125 +```sh
126 +npm install node-fetch@2
127 +```
128 +
129 +Alternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously:
130 +
88 ```js 131 ```js
89 -const Bluebird = require('bluebird'); 132 +// mod.cjs
133 +const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
134 +```
135 +
136 +### Providing global access
137 +
138 +To use `fetch()` without importing it, you can patch the `global` object in node:
90 139
91 -fetch.Promise = Bluebird; 140 +```js
141 +// fetch-polyfill.js
142 +import fetch, {
143 + Blob,
144 + blobFrom,
145 + blobFromSync,
146 + File,
147 + fileFrom,
148 + fileFromSync,
149 + FormData,
150 + Headers,
151 + Request,
152 + Response,
153 +} from 'node-fetch'
154 +
155 +if (!globalThis.fetch) {
156 + globalThis.fetch = fetch
157 + globalThis.Headers = Headers
158 + globalThis.Request = Request
159 + globalThis.Response = Response
160 +}
161 +
162 +// index.js
163 +import './fetch-polyfill'
164 +
165 +// ...
92 ``` 166 ```
93 167
168 +## Upgrading
169 +
170 +Using an old version of node-fetch? Check out the following files:
171 +
172 +- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)
173 +- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)
174 +- [Changelog](https://github.com/node-fetch/node-fetch/releases)
175 +
94 ## Common Usage 176 ## Common Usage
95 177
96 -NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. 178 +NOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).
179 +
180 +### Plain text or HTML
97 181
98 -#### Plain text or HTML
99 ```js 182 ```js
100 -fetch('https://github.com/') 183 +import fetch from 'node-fetch';
101 - .then(res => res.text()) 184 +
102 - .then(body => console.log(body)); 185 +const response = await fetch('https://github.com/');
186 +const body = await response.text();
187 +
188 +console.log(body);
103 ``` 189 ```
104 190
105 -#### JSON 191 +### JSON
106 192
107 ```js 193 ```js
194 +import fetch from 'node-fetch';
195 +
196 +const response = await fetch('https://api.github.com/users/github');
197 +const data = await response.json();
108 198
109 -fetch('https://api.github.com/users/github') 199 +console.log(data);
110 - .then(res => res.json())
111 - .then(json => console.log(json));
112 ``` 200 ```
113 201
114 -#### Simple Post 202 +### Simple Post
203 +
115 ```js 204 ```js
116 -fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) 205 +import fetch from 'node-fetch';
117 - .then(res => res.json()) // expecting a json response 206 +
118 - .then(json => console.log(json)); 207 +const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});
208 +const data = await response.json();
209 +
210 +console.log(data);
119 ``` 211 ```
120 212
121 -#### Post with JSON 213 +### Post with JSON
122 214
123 ```js 215 ```js
124 -const body = { a: 1 }; 216 +import fetch from 'node-fetch';
125 - 217 +
126 -fetch('https://httpbin.org/post', { 218 +const body = {a: 1};
127 - method: 'post', 219 +
128 - body: JSON.stringify(body), 220 +const response = await fetch('https://httpbin.org/post', {
129 - headers: { 'Content-Type': 'application/json' }, 221 + method: 'post',
130 - }) 222 + body: JSON.stringify(body),
131 - .then(res => res.json()) 223 + headers: {'Content-Type': 'application/json'}
132 - .then(json => console.log(json)); 224 +});
225 +const data = await response.json();
226 +
227 +console.log(data);
133 ``` 228 ```
134 229
135 -#### Post with form parameters 230 +### Post with form parameters
136 -`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. 231 +
232 +`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.
137 233
138 NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: 234 NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:
139 235
140 ```js 236 ```js
141 -const { URLSearchParams } = require('url'); 237 +import fetch from 'node-fetch';
142 238
143 const params = new URLSearchParams(); 239 const params = new URLSearchParams();
144 params.append('a', 1); 240 params.append('a', 1);
145 241
146 -fetch('https://httpbin.org/post', { method: 'POST', body: params }) 242 +const response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});
147 - .then(res => res.json()) 243 +const data = await response.json();
148 - .then(json => console.log(json)); 244 +
245 +console.log(data);
149 ``` 246 ```
150 247
151 -#### Handling exceptions 248 +### Handling exceptions
152 -NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. 249 +
250 +NOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.
153 251
154 -Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. 252 +Wrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.
155 253
156 ```js 254 ```js
157 -fetch('https://domain.invalid/') 255 +import fetch from 'node-fetch';
158 - .catch(err => console.error(err)); 256 +
257 +try {
258 + await fetch('https://domain.invalid/');
259 +} catch (error) {
260 + console.log(error);
261 +}
159 ``` 262 ```
160 263
161 -#### Handling client and server errors 264 +### Handling client and server errors
265 +
162 It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: 266 It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:
163 267
164 ```js 268 ```js
165 -function checkStatus(res) { 269 +import fetch from 'node-fetch';
166 - if (res.ok) { // res.status >= 200 && res.status < 300 270 +
167 - return res; 271 +class HTTPResponseError extends Error {
168 - } else { 272 + constructor(response, ...args) {
169 - throw MyCustomError(res.statusText); 273 + super(`HTTP Error Response: ${response.status} ${response.statusText}`, ...args);
170 - } 274 + this.response = response;
275 + }
171 } 276 }
172 277
173 -fetch('https://httpbin.org/status/400') 278 +const checkStatus = response => {
174 - .then(checkStatus) 279 + if (response.ok) {
175 - .then(res => console.log('will not get here...')) 280 + // response.status >= 200 && response.status < 300
281 + return response;
282 + } else {
283 + throw new HTTPResponseError(response);
284 + }
285 +}
286 +
287 +const response = await fetch('https://httpbin.org/status/400');
288 +
289 +try {
290 + checkStatus(response);
291 +} catch (error) {
292 + console.error(error);
293 +
294 + const errorBody = await error.response.text();
295 + console.error(`Error body: ${errorBody}`);
296 +}
176 ``` 297 ```
177 298
299 +### Handling cookies
300 +
301 +Cookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.
302 +
178 ## Advanced Usage 303 ## Advanced Usage
179 304
180 -#### Streams 305 +### Streams
181 -The "Node.js way" is to use streams when possible: 306 +
307 +The "Node.js way" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.
182 308
183 ```js 309 ```js
184 -fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') 310 +import {createWriteStream} from 'node:fs';
185 - .then(res => { 311 +import {pipeline} from 'node:stream';
186 - const dest = fs.createWriteStream('./octocat.png'); 312 +import {promisify} from 'node:util'
187 - res.body.pipe(dest); 313 +import fetch from 'node-fetch';
188 - }); 314 +
315 +const streamPipeline = promisify(pipeline);
316 +
317 +const response = await fetch('https://github.githubassets.com/images/modules/logos_page/Octocat.png');
318 +
319 +if (!response.ok) throw new Error(`unexpected response ${response.statusText}`);
320 +
321 +await streamPipeline(response.body, createWriteStream('./octocat.png'));
189 ``` 322 ```
190 323
191 -#### Buffer 324 +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch
192 -If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) 325 +errors -- the longer a response runs, the more likely it is to encounter an error.
193 326
194 ```js 327 ```js
195 -const fileType = require('file-type'); 328 +import fetch from 'node-fetch';
196 329
197 -fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') 330 +const response = await fetch('https://httpbin.org/stream/3');
198 - .then(res => res.buffer()) 331 +
199 - .then(buffer => fileType(buffer)) 332 +try {
200 - .then(type => { /* ... */ }); 333 + for await (const chunk of response.body) {
334 + console.dir(JSON.parse(chunk.toString()));
335 + }
336 +} catch (err) {
337 + console.error(err.stack);
338 +}
201 ``` 339 ```
202 340
203 -#### Accessing Headers and other Meta data 341 +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams
342 +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors
343 +directly from the stream and wait on it response to fully close.
344 +
204 ```js 345 ```js
205 -fetch('https://github.com/') 346 +import fetch from 'node-fetch';
206 - .then(res => { 347 +
207 - console.log(res.ok); 348 +const read = async body => {
208 - console.log(res.status); 349 + let error;
209 - console.log(res.statusText); 350 + body.on('error', err => {
210 - console.log(res.headers.raw()); 351 + error = err;
211 - console.log(res.headers.get('content-type')); 352 + });
212 - }); 353 +
213 -``` 354 + for await (const chunk of body) {
355 + console.dir(JSON.parse(chunk.toString()));
356 + }
357 +
358 + return new Promise((resolve, reject) => {
359 + body.on('close', () => {
360 + error ? reject(error) : resolve();
361 + });
362 + });
363 +};
214 364
215 -#### Extract Set-Cookie Header 365 +try {
366 + const response = await fetch('https://httpbin.org/stream/3');
367 + await read(response.body);
368 +} catch (err) {
369 + console.error(err.stack);
370 +}
371 +```
216 372
217 -Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. 373 +### Accessing Headers and other Metadata
218 374
219 ```js 375 ```js
220 -fetch(url).then(res => { 376 +import fetch from 'node-fetch';
221 - // returns an array of values, instead of a string of comma-separated values 377 +
222 - console.log(res.headers.raw()['set-cookie']); 378 +const response = await fetch('https://github.com/');
223 -}); 379 +
380 +console.log(response.ok);
381 +console.log(response.status);
382 +console.log(response.statusText);
383 +console.log(response.headers.raw());
384 +console.log(response.headers.get('content-type'));
224 ``` 385 ```
225 386
226 -#### Post data using a file stream 387 +### Extract Set-Cookie Header
388 +
389 +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.
227 390
228 ```js 391 ```js
229 -const { createReadStream } = require('fs'); 392 +import fetch from 'node-fetch';
230 393
231 -const stream = createReadStream('input.txt'); 394 +const response = await fetch('https://example.com');
232 395
233 -fetch('https://httpbin.org/post', { method: 'POST', body: stream }) 396 +// Returns an array of values, instead of a string of comma-separated values
234 - .then(res => res.json()) 397 +console.log(response.headers.raw()['set-cookie']);
235 - .then(json => console.log(json));
236 ``` 398 ```
237 399
238 -#### Post with form-data (detect multipart) 400 +### Post data using a file
239 401
240 ```js 402 ```js
241 -const FormData = require('form-data'); 403 +import fetch {
404 + Blob,
405 + blobFrom,
406 + blobFromSync,
407 + File,
408 + fileFrom,
409 + fileFromSync,
410 +} from 'node-fetch'
411 +
412 +const mimetype = 'text/plain'
413 +const blob = fileFromSync('./input.txt', mimetype)
414 +const url = 'https://httpbin.org/post'
415 +
416 +const response = await fetch(url, { method: 'POST', body: blob })
417 +const data = await response.json()
418 +
419 +console.log(data)
420 +```
242 421
243 -const form = new FormData(); 422 +node-fetch comes with a spec-compliant [FormData] implementations for posting
244 -form.append('a', 1); 423 +multipart/form-data payloads
245 424
246 -fetch('https://httpbin.org/post', { method: 'POST', body: form }) 425 +```js
247 - .then(res => res.json()) 426 +import fetch, { FormData, File, fileFrom } from 'node-fetch'
248 - .then(json => console.log(json));
249 427
250 -// OR, using custom headers 428 +const httpbin = 'https://httpbin.org/post'
251 -// NOTE: getHeaders() is non-standard API 429 +const formData = new FormData()
430 +const binary = new Uint8Array([ 97, 98, 99 ])
431 +const abc = new File([binary], 'abc.txt'), { type: 'text/plain' })
252 432
253 -const form = new FormData(); 433 +formData.set('greeting', 'Hello, world!')
254 -form.append('a', 1); 434 +formData.set('file-upload', abc, 'new name.txt')
255 435
256 -const options = { 436 +const response = await fetch(httpbin, { method: 'POST', body: formData })
257 - method: 'POST', 437 +const data = await response.json()
258 - body: form,
259 - headers: form.getHeaders()
260 -}
261 438
262 -fetch('https://httpbin.org/post', options) 439 +console.log(data)
263 - .then(res => res.json())
264 - .then(json => console.log(json));
265 ``` 440 ```
266 441
267 -#### Request cancellation with AbortSignal 442 +If you for some reason need to post a stream coming from any arbitrary place,
443 +then you can append a [Blob] or a [File] look-a-like item.
444 +
445 +The minium requirement is that it has:
446 +1. A `Symbol.toStringTag` getter or property that is either `Blob` or `File`
447 +2. A known size.
448 +3. And either a `stream()` method or a `arrayBuffer()` method that returns a ArrayBuffer.
268 449
269 -> NOTE: You may cancel streamed requests only on Node >= v8.0.0 450 +The `stream()` must return any async iterable object as long as it yields Uint8Array (or Buffer)
451 +so Node.Readable streams and whatwg streams works just fine.
452 +
453 +```js
454 +formData.append('upload', {
455 + [Symbol.toStringTag]: 'Blob',
456 + size: 3,
457 + *stream() {
458 + yield new Uint8Array([97, 98, 99])
459 + },
460 + arrayBuffer() {
461 + return new Uint8Array([97, 98, 99]).buffer
462 + }
463 +}, 'abc.txt')
464 +```
465 +
466 +### Request cancellation with AbortSignal
270 467
271 You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). 468 You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).
272 469
273 An example of timing out a request after 150ms could be achieved as the following: 470 An example of timing out a request after 150ms could be achieved as the following:
274 471
275 ```js 472 ```js
276 -import AbortController from 'abort-controller'; 473 +import fetch, { AbortError } from 'node-fetch';
474 +
475 +// AbortController was added in node v14.17.0 globally
476 +const AbortController = globalThis.AbortController || await import('abort-controller')
277 477
278 const controller = new AbortController(); 478 const controller = new AbortController();
279 -const timeout = setTimeout( 479 +const timeout = setTimeout(() => {
280 - () => { controller.abort(); }, 480 + controller.abort();
281 - 150, 481 +}, 150);
282 -); 482 +
283 - 483 +try {
284 -fetch(url, { signal: controller.signal }) 484 + const response = await fetch('https://example.com', {signal: controller.signal});
285 - .then(res => res.json()) 485 + const data = await response.json();
286 - .then( 486 +} catch (error) {
287 - data => { 487 + if (error instanceof AbortError) {
288 - useData(data) 488 + console.log('request was aborted');
289 - }, 489 + }
290 - err => { 490 +} finally {
291 - if (err.name === 'AbortError') { 491 + clearTimeout(timeout);
292 - // request was aborted 492 +}
293 - }
294 - },
295 - )
296 - .finally(() => {
297 - clearTimeout(timeout);
298 - });
299 ``` 493 ```
300 494
301 -See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. 495 +See [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.
302 -
303 496
304 ## API 497 ## API
305 498
...@@ -311,47 +504,51 @@ See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) ...@@ -311,47 +504,51 @@ See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js)
311 504
312 Perform an HTTP(S) fetch. 505 Perform an HTTP(S) fetch.
313 506
314 -`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. 507 +`url` should be an absolute URL, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.
315 508
316 <a id="fetch-options"></a> 509 <a id="fetch-options"></a>
510 +
317 ### Options 511 ### Options
318 512
319 The default values are shown after each option key. 513 The default values are shown after each option key.
320 514
321 ```js 515 ```js
322 { 516 {
323 - // These properties are part of the Fetch Standard 517 + // These properties are part of the Fetch Standard
324 - method: 'GET', 518 + method: 'GET',
325 - headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) 519 + headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)
326 - body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream 520 + body: null, // Request body. can be null, or a Node.js Readable stream
327 - redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect 521 + redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect
328 - signal: null, // pass an instance of AbortSignal to optionally abort requests 522 + signal: null, // Pass an instance of AbortSignal to optionally abort requests
329 - 523 +
330 - // The following properties are node-fetch extensions 524 + // The following properties are node-fetch extensions
331 - follow: 20, // maximum redirect count. 0 to not follow redirect 525 + follow: 20, // maximum redirect count. 0 to not follow redirect
332 - timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. 526 + compress: true, // support gzip/deflate content encoding. false to disable
333 - compress: true, // support gzip/deflate content encoding. false to disable 527 + size: 0, // maximum response body size in bytes. 0 to disable
334 - size: 0, // maximum response body size in bytes. 0 to disable 528 + agent: null, // http(s).Agent instance or function that returns an instance (see below)
335 - agent: null // http(s).Agent instance or function that returns an instance (see below) 529 + highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.
530 + insecureHTTPParser: false // Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.
336 } 531 }
337 ``` 532 ```
338 533
339 -##### Default Headers 534 +#### Default Headers
340 535
341 If no values are set, the following request headers will be sent automatically: 536 If no values are set, the following request headers will be sent automatically:
342 537
343 -Header | Value 538 +| Header | Value |
344 -------------------- | -------------------------------------------------------- 539 +| ------------------- | ------------------------------------------------------ |
345 -`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ 540 +| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |
346 -`Accept` | `*/*` 541 +| `Accept` | `*/*` |
347 -`Connection` | `close` _(when no `options.agent` is present)_ 542 +| `Connection` | `close` _(when no `options.agent` is present)_ |
348 -`Content-Length` | _(automatically calculated, if possible)_ 543 +| `Content-Length` | _(automatically calculated, if possible)_ |
349 -`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ 544 +| `Host` | _(host and port information from the target URI)_ |
350 -`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` 545 +| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |
546 +| `User-Agent` | `node-fetch` |
547 +
351 548
352 Note: when `body` is a `Stream`, `Content-Length` is not set automatically. 549 Note: when `body` is a `Stream`, `Content-Length` is not set automatically.
353 550
354 -##### Custom Agent 551 +#### Custom Agent
355 552
356 The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: 553 The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:
357 554
...@@ -364,25 +561,85 @@ See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for ...@@ -364,25 +561,85 @@ See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for
364 In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. 561 In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.
365 562
366 ```js 563 ```js
564 +import http from 'node:http';
565 +import https from 'node:https';
566 +
367 const httpAgent = new http.Agent({ 567 const httpAgent = new http.Agent({
368 - keepAlive: true 568 + keepAlive: true
369 }); 569 });
370 const httpsAgent = new https.Agent({ 570 const httpsAgent = new https.Agent({
371 - keepAlive: true 571 + keepAlive: true
372 }); 572 });
373 573
374 const options = { 574 const options = {
375 - agent: function (_parsedURL) { 575 + agent: function(_parsedURL) {
376 - if (_parsedURL.protocol == 'http:') { 576 + if (_parsedURL.protocol == 'http:') {
377 - return httpAgent; 577 + return httpAgent;
378 - } else { 578 + } else {
379 - return httpsAgent; 579 + return httpsAgent;
380 - } 580 + }
381 - } 581 + }
582 +};
583 +```
584 +
585 +<a id="custom-highWaterMark"></a>
586 +
587 +#### Custom highWaterMark
588 +
589 +Stream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.
590 +
591 +The recommended way to fix this problem is to resolve cloned response in parallel:
592 +
593 +```js
594 +import fetch from 'node-fetch';
595 +
596 +const response = await fetch('https://example.com');
597 +const r1 = await response.clone();
598 +
599 +const results = await Promise.all([response.json(), r1.text()]);
600 +
601 +console.log(results[0]);
602 +console.log(results[1]);
603 +```
604 +
605 +If for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:
606 +
607 +```js
608 +import fetch from 'node-fetch';
609 +
610 +const response = await fetch('https://example.com', {
611 + // About 1MB
612 + highWaterMark: 1024 * 1024
613 +});
614 +
615 +const result = await res.clone().arrayBuffer();
616 +console.dir(result);
617 +```
618 +
619 +#### Insecure HTTP Parser
620 +
621 +Passed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.
622 +
623 +#### Manual Redirect
624 +
625 +The `redirect: 'manual'` option for node-fetch is different from the browser & specification, which
626 +results in an [opaque-redirect filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect).
627 +node-fetch gives you the typical [basic filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-basic) instead.
628 +
629 +```js
630 +const fetch = require('node-fetch');
631 +
632 +const response = await fetch('https://httpbin.org/status/301', { redirect: 'manual' });
633 +
634 +if (response.status === 301 || response.status === 302) {
635 + const locationURL = new URL(response.headers.get('location'), response.url);
636 + const response2 = await fetch(locationURL, { redirect: 'manual' });
637 + console.dir(response2);
382 } 638 }
383 ``` 639 ```
384 640
385 <a id="class-request"></a> 641 <a id="class-request"></a>
642 +
386 ### Class: Request 643 ### Class: Request
387 644
388 An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. 645 An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.
...@@ -391,8 +648,6 @@ Due to the nature of Node.js, the following properties are not implemented at th ...@@ -391,8 +648,6 @@ Due to the nature of Node.js, the following properties are not implemented at th
391 648
392 - `type` 649 - `type`
393 - `destination` 650 - `destination`
394 -- `referrer`
395 -- `referrerPolicy`
396 - `mode` 651 - `mode`
397 - `credentials` 652 - `credentials`
398 - `cache` 653 - `cache`
...@@ -405,35 +660,34 @@ The following node-fetch extension properties are provided: ...@@ -405,35 +660,34 @@ The following node-fetch extension properties are provided:
405 - `compress` 660 - `compress`
406 - `counter` 661 - `counter`
407 - `agent` 662 - `agent`
663 +- `highWaterMark`
408 664
409 See [options](#fetch-options) for exact meaning of these extensions. 665 See [options](#fetch-options) for exact meaning of these extensions.
410 666
411 #### new Request(input[, options]) 667 #### new Request(input[, options])
412 668
413 -<small>*(spec-compliant)*</small> 669 +<small>_(spec-compliant)_</small>
414 670
415 - `input` A string representing a URL, or another `Request` (which will be cloned) 671 - `input` A string representing a URL, or another `Request` (which will be cloned)
416 -- `options` [Options][#fetch-options] for the HTTP(S) request 672 +- `options` [Options](#fetch-options) for the HTTP(S) request
417 673
418 Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). 674 Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).
419 675
420 In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. 676 In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.
421 677
422 <a id="class-response"></a> 678 <a id="class-response"></a>
679 +
423 ### Class: Response 680 ### Class: Response
424 681
425 An HTTP(S) response. This class implements the [Body](#iface-body) interface. 682 An HTTP(S) response. This class implements the [Body](#iface-body) interface.
426 683
427 The following properties are not implemented in node-fetch at this moment: 684 The following properties are not implemented in node-fetch at this moment:
428 685
429 -- `Response.error()`
430 -- `Response.redirect()`
431 -- `type`
432 - `trailer` 686 - `trailer`
433 687
434 #### new Response([body[, options]]) 688 #### new Response([body[, options]])
435 689
436 -<small>*(spec-compliant)*</small> 690 +<small>_(spec-compliant)_</small>
437 691
438 - `body` A `String` or [`Readable` stream][node-readable] 692 - `body` A `String` or [`Readable` stream][node-readable]
439 - `options` A [`ResponseInit`][response-init] options dictionary 693 - `options` A [`ResponseInit`][response-init] options dictionary
...@@ -444,24 +698,31 @@ Because Node.js does not implement service workers (for which this class was des ...@@ -444,24 +698,31 @@ Because Node.js does not implement service workers (for which this class was des
444 698
445 #### response.ok 699 #### response.ok
446 700
447 -<small>*(spec-compliant)*</small> 701 +<small>_(spec-compliant)_</small>
448 702
449 Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. 703 Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.
450 704
451 #### response.redirected 705 #### response.redirected
452 706
453 -<small>*(spec-compliant)*</small> 707 +<small>_(spec-compliant)_</small>
454 708
455 Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. 709 Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.
456 710
711 +#### response.type
712 +
713 +<small>_(deviation from spec)_</small>
714 +
715 +Convenience property representing the response's type. node-fetch only supports `'default'` and `'error'` and does not make use of [filtered responses](https://fetch.spec.whatwg.org/#concept-filtered-response).
716 +
457 <a id="class-headers"></a> 717 <a id="class-headers"></a>
718 +
458 ### Class: Headers 719 ### Class: Headers
459 720
460 This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. 721 This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.
461 722
462 #### new Headers([init]) 723 #### new Headers([init])
463 724
464 -<small>*(spec-compliant)*</small> 725 +<small>_(spec-compliant)_</small>
465 726
466 - `init` Optional argument to pre-fill the `Headers` object 727 - `init` Optional argument to pre-fill the `Headers` object
467 728
...@@ -469,122 +730,142 @@ Construct a new `Headers` object. `init` can be either `null`, a `Headers` objec ...@@ -469,122 +730,142 @@ Construct a new `Headers` object. `init` can be either `null`, a `Headers` objec
469 730
470 ```js 731 ```js
471 // Example adapted from https://fetch.spec.whatwg.org/#example-headers-class 732 // Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
733 +import {Headers} from 'node-fetch';
472 734
473 const meta = { 735 const meta = {
474 - 'Content-Type': 'text/xml', 736 + 'Content-Type': 'text/xml'
475 - 'Breaking-Bad': '<3'
476 }; 737 };
477 const headers = new Headers(meta); 738 const headers = new Headers(meta);
478 739
479 // The above is equivalent to 740 // The above is equivalent to
480 -const meta = [ 741 +const meta = [['Content-Type', 'text/xml']];
481 - [ 'Content-Type', 'text/xml' ],
482 - [ 'Breaking-Bad', '<3' ]
483 -];
484 const headers = new Headers(meta); 742 const headers = new Headers(meta);
485 743
486 // You can in fact use any iterable objects, like a Map or even another Headers 744 // You can in fact use any iterable objects, like a Map or even another Headers
487 const meta = new Map(); 745 const meta = new Map();
488 meta.set('Content-Type', 'text/xml'); 746 meta.set('Content-Type', 'text/xml');
489 -meta.set('Breaking-Bad', '<3');
490 const headers = new Headers(meta); 747 const headers = new Headers(meta);
491 const copyOfHeaders = new Headers(headers); 748 const copyOfHeaders = new Headers(headers);
492 ``` 749 ```
493 750
494 <a id="iface-body"></a> 751 <a id="iface-body"></a>
752 +
495 ### Interface: Body 753 ### Interface: Body
496 754
497 `Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. 755 `Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.
498 756
499 -The following methods are not yet implemented in node-fetch at this moment:
500 -
501 -- `formData()`
502 -
503 #### body.body 757 #### body.body
504 758
505 -<small>*(deviation from spec)*</small> 759 +<small>_(deviation from spec)_</small>
506 760
507 -* Node.js [`Readable` stream][node-readable] 761 +- Node.js [`Readable` stream][node-readable]
508 762
509 Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. 763 Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].
510 764
511 #### body.bodyUsed 765 #### body.bodyUsed
512 766
513 -<small>*(spec-compliant)*</small> 767 +<small>_(spec-compliant)_</small>
514 768
515 -* `Boolean` 769 +- `Boolean`
516 770
517 A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. 771 A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.
518 772
519 #### body.arrayBuffer() 773 #### body.arrayBuffer()
520 -#### body.blob()
521 -#### body.json()
522 -#### body.text()
523 -
524 -<small>*(spec-compliant)*</small>
525 -
526 -* Returns: <code>Promise</code>
527 -
528 -Consume the body and return a promise that will resolve to one of these formats.
529 774
530 -#### body.buffer() 775 +#### body.formData()
531 776
532 -<small>*(node-fetch extension)*</small> 777 +#### body.blob()
533 -
534 -* Returns: <code>Promise&lt;Buffer&gt;</code>
535 778
536 -Consume the body and return a promise that will resolve to a Buffer. 779 +#### body.json()
537 780
538 -#### body.textConverted() 781 +#### body.text()
539 782
540 -<small>*(node-fetch extension)*</small> 783 +`fetch` comes with methods to parse `multipart/form-data` payloads as well as
784 +`x-www-form-urlencoded` bodies using `.formData()` this comes from the idea that
785 +Service Worker can intercept such messages before it's sent to the server to
786 +alter them. This is useful for anybody building a server so you can use it to
787 +parse & consume payloads.
541 788
542 -* Returns: <code>Promise&lt;String&gt;</code> 789 +<details>
790 +<summary>Code example</summary>
543 791
544 -Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. 792 +```js
793 +import http from 'node:http'
794 +import { Response } from 'node-fetch'
795 +
796 +http.createServer(async function (req, res) {
797 + const formData = await new Response(req, {
798 + headers: req.headers // Pass along the boundary value
799 + }).formData()
800 + const allFields = [...formData]
801 +
802 + const file = formData.get('uploaded-files')
803 + const arrayBuffer = await file.arrayBuffer()
804 + const text = await file.text()
805 + const whatwgReadableStream = file.stream()
806 +
807 + // other was to consume the request could be to do:
808 + const json = await new Response(req).json()
809 + const text = await new Response(req).text()
810 + const arrayBuffer = await new Response(req).arrayBuffer()
811 + const blob = await new Response(req, {
812 + headers: req.headers // So that `type` inherits `Content-Type`
813 + }.blob()
814 +})
815 +```
545 816
546 -(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) 817 +</details>
547 818
548 <a id="class-fetcherror"></a> 819 <a id="class-fetcherror"></a>
820 +
549 ### Class: FetchError 821 ### Class: FetchError
550 822
551 -<small>*(node-fetch extension)*</small> 823 +<small>_(node-fetch extension)_</small>
552 824
553 An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. 825 An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.
554 826
555 <a id="class-aborterror"></a> 827 <a id="class-aborterror"></a>
828 +
556 ### Class: AbortError 829 ### Class: AbortError
557 830
558 -<small>*(node-fetch extension)*</small> 831 +<small>_(node-fetch extension)_</small>
559 832
560 An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. 833 An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.
561 834
835 +## TypeScript
836 +
837 +**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**
838 +
839 +For older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):
840 +
841 +```sh
842 +npm install --save-dev @types/node-fetch@2.x
843 +```
844 +
562 ## Acknowledgement 845 ## Acknowledgement
563 846
564 Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. 847 Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.
565 848
566 -`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). 849 +## Team
850 +
851 +| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |
852 +| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
853 +| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.ch) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |
854 +
855 +###### Former
856 +
857 +- [Timothy Gu](https://github.com/timothygu)
858 +- [Jared Kantrowitz](https://github.com/jkantr)
567 859
568 ## License 860 ## License
569 861
570 -MIT 862 +[MIT](LICENSE.md)
571 - 863 +
572 -[npm-image]: https://flat.badgen.net/npm/v/node-fetch
573 -[npm-url]: https://www.npmjs.com/package/node-fetch
574 -[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch
575 -[travis-url]: https://travis-ci.org/bitinn/node-fetch
576 -[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master
577 -[codecov-url]: https://codecov.io/gh/bitinn/node-fetch
578 -[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch
579 -[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch
580 -[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square
581 -[discord-url]: https://discord.gg/Zxbndcm
582 -[opencollective-image]: https://opencollective.com/node-fetch/backers.svg
583 -[opencollective-url]: https://opencollective.com/node-fetch
584 [whatwg-fetch]: https://fetch.spec.whatwg.org/ 864 [whatwg-fetch]: https://fetch.spec.whatwg.org/
585 [response-init]: https://fetch.spec.whatwg.org/#responseinit 865 [response-init]: https://fetch.spec.whatwg.org/#responseinit
586 [node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams 866 [node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams
587 [mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers 867 [mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers
588 -[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md 868 +[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md
589 -[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md 869 +[FormData]: https://developer.mozilla.org/en-US/docs/Web/API/FormData
590 -[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md 870 +[Blob]: https://developer.mozilla.org/en-US/docs/Web/API/Blob
871 +[File]: https://developer.mozilla.org/en-US/docs/Web/API/File
......
1 { 1 {
2 - "name": "node-fetch", 2 + "name": "node-fetch",
3 - "version": "2.6.7", 3 + "version": "3.2.4",
4 - "description": "A light-weight module that brings window.fetch to node.js", 4 + "description": "A light-weight module that brings Fetch API to node.js",
5 - "main": "lib/index.js", 5 + "main": "./src/index.js",
6 - "browser": "./browser.js", 6 + "sideEffects": false,
7 - "module": "lib/index.mjs", 7 + "type": "module",
8 - "files": [ 8 + "files": [
9 - "lib/index.js", 9 + "src",
10 - "lib/index.mjs", 10 + "@types/index.d.ts"
11 - "lib/index.es.js", 11 + ],
12 - "browser.js" 12 + "types": "./@types/index.d.ts",
13 + "engines": {
14 + "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
15 + },
16 + "scripts": {
17 + "test": "mocha",
18 + "coverage": "c8 report --reporter=text-lcov | coveralls",
19 + "test-types": "tsd",
20 + "lint": "xo"
21 + },
22 + "repository": {
23 + "type": "git",
24 + "url": "https://github.com/node-fetch/node-fetch.git"
25 + },
26 + "keywords": [
27 + "fetch",
28 + "http",
29 + "promise",
30 + "request",
31 + "curl",
32 + "wget",
33 + "xhr",
34 + "whatwg"
35 + ],
36 + "author": "David Frank",
37 + "license": "MIT",
38 + "bugs": {
39 + "url": "https://github.com/node-fetch/node-fetch/issues"
40 + },
41 + "homepage": "https://github.com/node-fetch/node-fetch",
42 + "funding": {
43 + "type": "opencollective",
44 + "url": "https://opencollective.com/node-fetch"
45 + },
46 + "devDependencies": {
47 + "abort-controller": "^3.0.0",
48 + "abortcontroller-polyfill": "^1.7.1",
49 + "busboy": "^1.4.0",
50 + "c8": "^7.7.2",
51 + "chai": "^4.3.4",
52 + "chai-as-promised": "^7.1.1",
53 + "chai-iterator": "^3.0.2",
54 + "chai-string": "^1.5.0",
55 + "coveralls": "^3.1.0",
56 + "form-data": "^4.0.0",
57 + "formdata-node": "^4.2.4",
58 + "mocha": "^9.1.3",
59 + "p-timeout": "^5.0.0",
60 + "stream-consumers": "^1.0.1",
61 + "tsd": "^0.14.0",
62 + "xo": "^0.39.1"
63 + },
64 + "dependencies": {
65 + "data-uri-to-buffer": "^4.0.0",
66 + "fetch-blob": "^3.1.4",
67 + "formdata-polyfill": "^4.0.10"
68 + },
69 + "tsd": {
70 + "cwd": "@types",
71 + "compilerOptions": {
72 + "esModuleInterop": true
73 + }
74 + },
75 + "xo": {
76 + "envs": [
77 + "node",
78 + "browser"
13 ], 79 ],
14 - "engines": { 80 + "ignores": [
15 - "node": "4.x || >=6.0.0" 81 + "example.js"
16 - },
17 - "scripts": {
18 - "build": "cross-env BABEL_ENV=rollup rollup -c",
19 - "prepare": "npm run build",
20 - "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js",
21 - "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js",
22 - "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json"
23 - },
24 - "repository": {
25 - "type": "git",
26 - "url": "https://github.com/bitinn/node-fetch.git"
27 - },
28 - "keywords": [
29 - "fetch",
30 - "http",
31 - "promise"
32 ], 82 ],
33 - "author": "David Frank", 83 + "rules": {
34 - "license": "MIT", 84 + "complexity": 0,
35 - "bugs": { 85 + "import/extensions": 0,
36 - "url": "https://github.com/bitinn/node-fetch/issues" 86 + "import/no-useless-path-segments": 0,
87 + "import/no-anonymous-default-export": 0,
88 + "import/no-named-as-default": 0,
89 + "unicorn/import-index": 0,
90 + "unicorn/no-array-reduce": 0,
91 + "unicorn/prefer-node-protocol": 0,
92 + "unicorn/numeric-separators-style": 0,
93 + "unicorn/explicit-length-check": 0,
94 + "capitalized-comments": 0,
95 + "node/no-unsupported-features/es-syntax": 0,
96 + "@typescript-eslint/member-ordering": 0
37 }, 97 },
38 - "homepage": "https://github.com/bitinn/node-fetch", 98 + "overrides": [
39 - "dependencies": { 99 + {
40 - "whatwg-url": "^5.0.0" 100 + "files": "test/**/*.js",
41 - }, 101 + "envs": [
42 - "peerDependencies": { 102 + "node",
43 - "encoding": "^0.1.0" 103 + "mocha"
44 - }, 104 + ],
45 - "peerDependenciesMeta": { 105 + "rules": {
46 - "encoding": { 106 + "max-nested-callbacks": 0,
47 - "optional": true 107 + "no-unused-expressions": 0,
108 + "no-warning-comments": 0,
109 + "new-cap": 0,
110 + "guard-for-in": 0,
111 + "unicorn/no-array-for-each": 0,
112 + "unicorn/prevent-abbreviations": 0,
113 + "promise/prefer-await-to-then": 0,
114 + "ava/no-import-test-files": 0
48 } 115 }
49 - }, 116 + }
50 - "devDependencies": { 117 + ]
51 - "@ungap/url-search-params": "^0.1.2", 118 + },
52 - "abort-controller": "^1.1.0", 119 + "runkitExampleFilename": "example.js",
53 - "abortcontroller-polyfill": "^1.3.0", 120 + "release": {
54 - "babel-core": "^6.26.3", 121 + "branches": [
55 - "babel-plugin-istanbul": "^4.1.6", 122 + "+([0-9]).x",
56 - "babel-preset-env": "^1.6.1", 123 + "main",
57 - "babel-register": "^6.16.3", 124 + "next",
58 - "chai": "^3.5.0", 125 + {
59 - "chai-as-promised": "^7.1.1", 126 + "name": "beta",
60 - "chai-iterator": "^1.1.1", 127 + "prerelease": true
61 - "chai-string": "~1.3.0", 128 + }
62 - "codecov": "3.3.0", 129 + ]
63 - "cross-env": "^5.2.0", 130 + }
64 - "form-data": "^2.3.3",
65 - "is-builtin-module": "^1.0.0",
66 - "mocha": "^5.0.0",
67 - "nyc": "11.9.0",
68 - "parted": "^0.1.1",
69 - "promise": "^8.0.3",
70 - "resumer": "0.0.0",
71 - "rollup": "^0.63.4",
72 - "rollup-plugin-babel": "^3.0.7",
73 - "string-to-arraybuffer": "^1.0.2",
74 - "teeny-request": "3.7.0"
75 - }
76 } 131 }
......
1 +
2 +/**
3 + * Body.js
4 + *
5 + * Body interface provides common methods for Request and Response
6 + */
7 +
8 +import Stream, {PassThrough} from 'node:stream';
9 +import {types, deprecate, promisify} from 'node:util';
10 +import {Buffer} from 'node:buffer';
11 +
12 +import Blob from 'fetch-blob';
13 +import {FormData, formDataToBlob} from 'formdata-polyfill/esm.min.js';
14 +
15 +import {FetchError} from './errors/fetch-error.js';
16 +import {FetchBaseError} from './errors/base.js';
17 +import {isBlob, isURLSearchParameters} from './utils/is.js';
18 +
19 +const pipeline = promisify(Stream.pipeline);
20 +const INTERNALS = Symbol('Body internals');
21 +
22 +/**
23 + * Body mixin
24 + *
25 + * Ref: https://fetch.spec.whatwg.org/#body
26 + *
27 + * @param Stream body Readable stream
28 + * @param Object opts Response options
29 + * @return Void
30 + */
31 +export default class Body {
32 + constructor(body, {
33 + size = 0
34 + } = {}) {
35 + let boundary = null;
36 +
37 + if (body === null) {
38 + // Body is undefined or null
39 + body = null;
40 + } else if (isURLSearchParameters(body)) {
41 + // Body is a URLSearchParams
42 + body = Buffer.from(body.toString());
43 + } else if (isBlob(body)) {
44 + // Body is blob
45 + } else if (Buffer.isBuffer(body)) {
46 + // Body is Buffer
47 + } else if (types.isAnyArrayBuffer(body)) {
48 + // Body is ArrayBuffer
49 + body = Buffer.from(body);
50 + } else if (ArrayBuffer.isView(body)) {
51 + // Body is ArrayBufferView
52 + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
53 + } else if (body instanceof Stream) {
54 + // Body is stream
55 + } else if (body instanceof FormData) {
56 + // Body is FormData
57 + body = formDataToBlob(body);
58 + boundary = body.type.split('=')[1];
59 + } else {
60 + // None of the above
61 + // coerce to string then buffer
62 + body = Buffer.from(String(body));
63 + }
64 +
65 + let stream = body;
66 +
67 + if (Buffer.isBuffer(body)) {
68 + stream = Stream.Readable.from(body);
69 + } else if (isBlob(body)) {
70 + stream = Stream.Readable.from(body.stream());
71 + }
72 +
73 + this[INTERNALS] = {
74 + body,
75 + stream,
76 + boundary,
77 + disturbed: false,
78 + error: null
79 + };
80 + this.size = size;
81 +
82 + if (body instanceof Stream) {
83 + body.on('error', error_ => {
84 + const error = error_ instanceof FetchBaseError ?
85 + error_ :
86 + new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_);
87 + this[INTERNALS].error = error;
88 + });
89 + }
90 + }
91 +
92 + get body() {
93 + return this[INTERNALS].stream;
94 + }
95 +
96 + get bodyUsed() {
97 + return this[INTERNALS].disturbed;
98 + }
99 +
100 + /**
101 + * Decode response as ArrayBuffer
102 + *
103 + * @return Promise
104 + */
105 + async arrayBuffer() {
106 + const {buffer, byteOffset, byteLength} = await consumeBody(this);
107 + return buffer.slice(byteOffset, byteOffset + byteLength);
108 + }
109 +
110 + async formData() {
111 + const ct = this.headers.get('content-type');
112 +
113 + if (ct.startsWith('application/x-www-form-urlencoded')) {
114 + const formData = new FormData();
115 + const parameters = new URLSearchParams(await this.text());
116 +
117 + for (const [name, value] of parameters) {
118 + formData.append(name, value);
119 + }
120 +
121 + return formData;
122 + }
123 +
124 + const {toFormData} = await import('./utils/multipart-parser.js');
125 + return toFormData(this.body, ct);
126 + }
127 +
128 + /**
129 + * Return raw response as Blob
130 + *
131 + * @return Promise
132 + */
133 + async blob() {
134 + const ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || '';
135 + const buf = await this.arrayBuffer();
136 +
137 + return new Blob([buf], {
138 + type: ct
139 + });
140 + }
141 +
142 + /**
143 + * Decode response as json
144 + *
145 + * @return Promise
146 + */
147 + async json() {
148 + const text = await this.text();
149 + return JSON.parse(text);
150 + }
151 +
152 + /**
153 + * Decode response as text
154 + *
155 + * @return Promise
156 + */
157 + async text() {
158 + const buffer = await consumeBody(this);
159 + return new TextDecoder().decode(buffer);
160 + }
161 +
162 + /**
163 + * Decode response as buffer (non-spec api)
164 + *
165 + * @return Promise
166 + */
167 + buffer() {
168 + return consumeBody(this);
169 + }
170 +}
171 +
172 +Body.prototype.buffer = deprecate(Body.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer');
173 +
174 +// In browsers, all properties are enumerable.
175 +Object.defineProperties(Body.prototype, {
176 + body: {enumerable: true},
177 + bodyUsed: {enumerable: true},
178 + arrayBuffer: {enumerable: true},
179 + blob: {enumerable: true},
180 + json: {enumerable: true},
181 + text: {enumerable: true},
182 + data: {get: deprecate(() => {},
183 + 'data doesn\'t exist, use json(), text(), arrayBuffer(), or body instead',
184 + 'https://github.com/node-fetch/node-fetch/issues/1000 (response)')}
185 +});
186 +
187 +/**
188 + * Consume and convert an entire Body to a Buffer.
189 + *
190 + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
191 + *
192 + * @return Promise
193 + */
194 +async function consumeBody(data) {
195 + if (data[INTERNALS].disturbed) {
196 + throw new TypeError(`body used already for: ${data.url}`);
197 + }
198 +
199 + data[INTERNALS].disturbed = true;
200 +
201 + if (data[INTERNALS].error) {
202 + throw data[INTERNALS].error;
203 + }
204 +
205 + const {body} = data;
206 +
207 + // Body is null
208 + if (body === null) {
209 + return Buffer.alloc(0);
210 + }
211 +
212 + /* c8 ignore next 3 */
213 + if (!(body instanceof Stream)) {
214 + return Buffer.alloc(0);
215 + }
216 +
217 + // Body is stream
218 + // get ready to actually consume the body
219 + const accum = [];
220 + let accumBytes = 0;
221 +
222 + try {
223 + for await (const chunk of body) {
224 + if (data.size > 0 && accumBytes + chunk.length > data.size) {
225 + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size');
226 + body.destroy(error);
227 + throw error;
228 + }
229 +
230 + accumBytes += chunk.length;
231 + accum.push(chunk);
232 + }
233 + } catch (error) {
234 + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error);
235 + throw error_;
236 + }
237 +
238 + if (body.readableEnded === true || body._readableState.ended === true) {
239 + try {
240 + if (accum.every(c => typeof c === 'string')) {
241 + return Buffer.from(accum.join(''));
242 + }
243 +
244 + return Buffer.concat(accum, accumBytes);
245 + } catch (error) {
246 + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error);
247 + }
248 + } else {
249 + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
250 + }
251 +}
252 +
253 +/**
254 + * Clone body given Res/Req instance
255 + *
256 + * @param Mixed instance Response or Request instance
257 + * @param String highWaterMark highWaterMark for both PassThrough body streams
258 + * @return Mixed
259 + */
260 +export const clone = (instance, highWaterMark) => {
261 + let p1;
262 + let p2;
263 + let {body} = instance[INTERNALS];
264 +
265 + // Don't allow cloning a used body
266 + if (instance.bodyUsed) {
267 + throw new Error('cannot clone body after it is used');
268 + }
269 +
270 + // Check that body is a stream and not form-data object
271 + // note: we can't clone the form-data object without having it as a dependency
272 + if ((body instanceof Stream) && (typeof body.getBoundary !== 'function')) {
273 + // Tee instance body
274 + p1 = new PassThrough({highWaterMark});
275 + p2 = new PassThrough({highWaterMark});
276 + body.pipe(p1);
277 + body.pipe(p2);
278 + // Set instance body to teed body and return the other teed body
279 + instance[INTERNALS].stream = p1;
280 + body = p2;
281 + }
282 +
283 + return body;
284 +};
285 +
286 +const getNonSpecFormDataBoundary = deprecate(
287 + body => body.getBoundary(),
288 + 'form-data doesn\'t follow the spec and requires special treatment. Use alternative package',
289 + 'https://github.com/node-fetch/node-fetch/issues/1167'
290 +);
291 +
292 +/**
293 + * Performs the operation "extract a `Content-Type` value from |object|" as
294 + * specified in the specification:
295 + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
296 + *
297 + * This function assumes that instance.body is present.
298 + *
299 + * @param {any} body Any options.body input
300 + * @returns {string | null}
301 + */
302 +export const extractContentType = (body, request) => {
303 + // Body is null or undefined
304 + if (body === null) {
305 + return null;
306 + }
307 +
308 + // Body is string
309 + if (typeof body === 'string') {
310 + return 'text/plain;charset=UTF-8';
311 + }
312 +
313 + // Body is a URLSearchParams
314 + if (isURLSearchParameters(body)) {
315 + return 'application/x-www-form-urlencoded;charset=UTF-8';
316 + }
317 +
318 + // Body is blob
319 + if (isBlob(body)) {
320 + return body.type || null;
321 + }
322 +
323 + // Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView)
324 + if (Buffer.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
325 + return null;
326 + }
327 +
328 + if (body instanceof FormData) {
329 + return `multipart/form-data; boundary=${request[INTERNALS].boundary}`;
330 + }
331 +
332 + // Detect form data input from form-data module
333 + if (body && typeof body.getBoundary === 'function') {
334 + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
335 + }
336 +
337 + // Body is stream - can't really do much about this
338 + if (body instanceof Stream) {
339 + return null;
340 + }
341 +
342 + // Body constructor defaults other things to string
343 + return 'text/plain;charset=UTF-8';
344 +};
345 +
346 +/**
347 + * The Fetch Standard treats this as if "total bytes" is a property on the body.
348 + * For us, we have to explicitly get it with a function.
349 + *
350 + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
351 + *
352 + * @param {any} obj.body Body object from the Body instance.
353 + * @returns {number | null}
354 + */
355 +export const getTotalBytes = request => {
356 + const {body} = request[INTERNALS];
357 +
358 + // Body is null or undefined
359 + if (body === null) {
360 + return 0;
361 + }
362 +
363 + // Body is Blob
364 + if (isBlob(body)) {
365 + return body.size;
366 + }
367 +
368 + // Body is Buffer
369 + if (Buffer.isBuffer(body)) {
370 + return body.length;
371 + }
372 +
373 + // Detect form data input from form-data module
374 + if (body && typeof body.getLengthSync === 'function') {
375 + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
376 + }
377 +
378 + // Body is stream
379 + return null;
380 +};
381 +
382 +/**
383 + * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
384 + *
385 + * @param {Stream.Writable} dest The stream to write to.
386 + * @param obj.body Body object from the Body instance.
387 + * @returns {Promise<void>}
388 + */
389 +export const writeToStream = async (dest, {body}) => {
390 + if (body === null) {
391 + // Body is null
392 + dest.end();
393 + } else {
394 + // Body is stream
395 + await pipeline(body, dest);
396 + }
397 +};
1 +import {FetchBaseError} from './base.js';
2 +
3 +/**
4 + * AbortError interface for cancelled requests
5 + */
6 +export class AbortError extends FetchBaseError {
7 + constructor(message, type = 'aborted') {
8 + super(message, type);
9 + }
10 +}
1 +export class FetchBaseError extends Error {
2 + constructor(message, type) {
3 + super(message);
4 + // Hide custom error implementation details from end-users
5 + Error.captureStackTrace(this, this.constructor);
6 +
7 + this.type = type;
8 + }
9 +
10 + get name() {
11 + return this.constructor.name;
12 + }
13 +
14 + get [Symbol.toStringTag]() {
15 + return this.constructor.name;
16 + }
17 +}
1 +
2 +import {FetchBaseError} from './base.js';
3 +
4 +/**
5 + * @typedef {{ address?: string, code: string, dest?: string, errno: number, info?: object, message: string, path?: string, port?: number, syscall: string}} SystemError
6 +*/
7 +
8 +/**
9 + * FetchError interface for operational errors
10 + */
11 +export class FetchError extends FetchBaseError {
12 + /**
13 + * @param {string} message - Error message for human
14 + * @param {string} [type] - Error type for machine
15 + * @param {SystemError} [systemError] - For Node.js system error
16 + */
17 + constructor(message, type, systemError) {
18 + super(message, type);
19 + // When err.type is `system`, err.erroredSysCall contains system error and err.code contains system error code
20 + if (systemError) {
21 + // eslint-disable-next-line no-multi-assign
22 + this.code = this.errno = systemError.code;
23 + this.erroredSysCall = systemError.syscall;
24 + }
25 + }
26 +}
1 +/**
2 + * Headers.js
3 + *
4 + * Headers class offers convenient helpers
5 + */
6 +
7 +import {types} from 'node:util';
8 +import http from 'node:http';
9 +
10 +/* c8 ignore next 9 */
11 +const validateHeaderName = typeof http.validateHeaderName === 'function' ?
12 + http.validateHeaderName :
13 + name => {
14 + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
15 + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`);
16 + Object.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'});
17 + throw error;
18 + }
19 + };
20 +
21 +/* c8 ignore next 9 */
22 +const validateHeaderValue = typeof http.validateHeaderValue === 'function' ?
23 + http.validateHeaderValue :
24 + (name, value) => {
25 + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
26 + const error = new TypeError(`Invalid character in header content ["${name}"]`);
27 + Object.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'});
28 + throw error;
29 + }
30 + };
31 +
32 +/**
33 + * @typedef {Headers | Record<string, string> | Iterable<readonly [string, string]> | Iterable<Iterable<string>>} HeadersInit
34 + */
35 +
36 +/**
37 + * This Fetch API interface allows you to perform various actions on HTTP request and response headers.
38 + * These actions include retrieving, setting, adding to, and removing.
39 + * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.
40 + * You can add to this using methods like append() (see Examples.)
41 + * In all methods of this interface, header names are matched by case-insensitive byte sequence.
42 + *
43 + */
44 +export default class Headers extends URLSearchParams {
45 + /**
46 + * Headers class
47 + *
48 + * @constructor
49 + * @param {HeadersInit} [init] - Response headers
50 + */
51 + constructor(init) {
52 + // Validate and normalize init object in [name, value(s)][]
53 + /** @type {string[][]} */
54 + let result = [];
55 + if (init instanceof Headers) {
56 + const raw = init.raw();
57 + for (const [name, values] of Object.entries(raw)) {
58 + result.push(...values.map(value => [name, value]));
59 + }
60 + } else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq
61 + // No op
62 + } else if (typeof init === 'object' && !types.isBoxedPrimitive(init)) {
63 + const method = init[Symbol.iterator];
64 + // eslint-disable-next-line no-eq-null, eqeqeq
65 + if (method == null) {
66 + // Record<ByteString, ByteString>
67 + result.push(...Object.entries(init));
68 + } else {
69 + if (typeof method !== 'function') {
70 + throw new TypeError('Header pairs must be iterable');
71 + }
72 +
73 + // Sequence<sequence<ByteString>>
74 + // Note: per spec we have to first exhaust the lists then process them
75 + result = [...init]
76 + .map(pair => {
77 + if (
78 + typeof pair !== 'object' || types.isBoxedPrimitive(pair)
79 + ) {
80 + throw new TypeError('Each header pair must be an iterable object');
81 + }
82 +
83 + return [...pair];
84 + }).map(pair => {
85 + if (pair.length !== 2) {
86 + throw new TypeError('Each header pair must be a name/value tuple');
87 + }
88 +
89 + return [...pair];
90 + });
91 + }
92 + } else {
93 + throw new TypeError('Failed to construct \'Headers\': The provided value is not of type \'(sequence<sequence<ByteString>> or record<ByteString, ByteString>)');
94 + }
95 +
96 + // Validate and lowercase
97 + result =
98 + result.length > 0 ?
99 + result.map(([name, value]) => {
100 + validateHeaderName(name);
101 + validateHeaderValue(name, String(value));
102 + return [String(name).toLowerCase(), String(value)];
103 + }) :
104 + undefined;
105 +
106 + super(result);
107 +
108 + // Returning a Proxy that will lowercase key names, validate parameters and sort keys
109 + // eslint-disable-next-line no-constructor-return
110 + return new Proxy(this, {
111 + get(target, p, receiver) {
112 + switch (p) {
113 + case 'append':
114 + case 'set':
115 + return (name, value) => {
116 + validateHeaderName(name);
117 + validateHeaderValue(name, String(value));
118 + return URLSearchParams.prototype[p].call(
119 + target,
120 + String(name).toLowerCase(),
121 + String(value)
122 + );
123 + };
124 +
125 + case 'delete':
126 + case 'has':
127 + case 'getAll':
128 + return name => {
129 + validateHeaderName(name);
130 + return URLSearchParams.prototype[p].call(
131 + target,
132 + String(name).toLowerCase()
133 + );
134 + };
135 +
136 + case 'keys':
137 + return () => {
138 + target.sort();
139 + return new Set(URLSearchParams.prototype.keys.call(target)).keys();
140 + };
141 +
142 + default:
143 + return Reflect.get(target, p, receiver);
144 + }
145 + }
146 + });
147 + /* c8 ignore next */
148 + }
149 +
150 + get [Symbol.toStringTag]() {
151 + return this.constructor.name;
152 + }
153 +
154 + toString() {
155 + return Object.prototype.toString.call(this);
156 + }
157 +
158 + get(name) {
159 + const values = this.getAll(name);
160 + if (values.length === 0) {
161 + return null;
162 + }
163 +
164 + let value = values.join(', ');
165 + if (/^content-encoding$/i.test(name)) {
166 + value = value.toLowerCase();
167 + }
168 +
169 + return value;
170 + }
171 +
172 + forEach(callback, thisArg = undefined) {
173 + for (const name of this.keys()) {
174 + Reflect.apply(callback, thisArg, [this.get(name), name, this]);
175 + }
176 + }
177 +
178 + * values() {
179 + for (const name of this.keys()) {
180 + yield this.get(name);
181 + }
182 + }
183 +
184 + /**
185 + * @type {() => IterableIterator<[string, string]>}
186 + */
187 + * entries() {
188 + for (const name of this.keys()) {
189 + yield [name, this.get(name)];
190 + }
191 + }
192 +
193 + [Symbol.iterator]() {
194 + return this.entries();
195 + }
196 +
197 + /**
198 + * Node-fetch non-spec method
199 + * returning all headers and their values as array
200 + * @returns {Record<string, string[]>}
201 + */
202 + raw() {
203 + return [...this.keys()].reduce((result, key) => {
204 + result[key] = this.getAll(key);
205 + return result;
206 + }, {});
207 + }
208 +
209 + /**
210 + * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
211 + */
212 + [Symbol.for('nodejs.util.inspect.custom')]() {
213 + return [...this.keys()].reduce((result, key) => {
214 + const values = this.getAll(key);
215 + // Http.request() only supports string as Host header.
216 + // This hack makes specifying custom Host header possible.
217 + if (key === 'host') {
218 + result[key] = values[0];
219 + } else {
220 + result[key] = values.length > 1 ? values : values[0];
221 + }
222 +
223 + return result;
224 + }, {});
225 + }
226 +}
227 +
228 +/**
229 + * Re-shaping object for Web IDL tests
230 + * Only need to do it for overridden methods
231 + */
232 +Object.defineProperties(
233 + Headers.prototype,
234 + ['get', 'entries', 'forEach', 'values'].reduce((result, property) => {
235 + result[property] = {enumerable: true};
236 + return result;
237 + }, {})
238 +);
239 +
240 +/**
241 + * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do
242 + * not conform to HTTP grammar productions.
243 + * @param {import('http').IncomingMessage['rawHeaders']} headers
244 + */
245 +export function fromRawHeaders(headers = []) {
246 + return new Headers(
247 + headers
248 + // Split into pairs
249 + .reduce((result, value, index, array) => {
250 + if (index % 2 === 0) {
251 + result.push(array.slice(index, index + 2));
252 + }
253 +
254 + return result;
255 + }, [])
256 + .filter(([name, value]) => {
257 + try {
258 + validateHeaderName(name);
259 + validateHeaderValue(name, String(value));
260 + return true;
261 + } catch {
262 + return false;
263 + }
264 + })
265 +
266 + );
267 +}
1 +/**
2 + * Index.js
3 + *
4 + * a request API compatible with window.fetch
5 + *
6 + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
7 + */
8 +
9 +import http from 'node:http';
10 +import https from 'node:https';
11 +import zlib from 'node:zlib';
12 +import Stream, {PassThrough, pipeline as pump} from 'node:stream';
13 +import {Buffer} from 'node:buffer';
14 +
15 +import dataUriToBuffer from 'data-uri-to-buffer';
16 +
17 +import {writeToStream, clone} from './body.js';
18 +import Response from './response.js';
19 +import Headers, {fromRawHeaders} from './headers.js';
20 +import Request, {getNodeRequestOptions} from './request.js';
21 +import {FetchError} from './errors/fetch-error.js';
22 +import {AbortError} from './errors/abort-error.js';
23 +import {isRedirect} from './utils/is-redirect.js';
24 +import {FormData} from 'formdata-polyfill/esm.min.js';
25 +import {isDomainOrSubdomain} from './utils/is.js';
26 +import {parseReferrerPolicyFromHeader} from './utils/referrer.js';
27 +import {
28 + Blob,
29 + File,
30 + fileFromSync,
31 + fileFrom,
32 + blobFromSync,
33 + blobFrom
34 +} from 'fetch-blob/from.js';
35 +
36 +export {FormData, Headers, Request, Response, FetchError, AbortError, isRedirect};
37 +export {Blob, File, fileFromSync, fileFrom, blobFromSync, blobFrom};
38 +
39 +const supportedSchemas = new Set(['data:', 'http:', 'https:']);
40 +
41 +/**
42 + * Fetch function
43 + *
44 + * @param {string | URL | import('./request').default} url - Absolute url or Request instance
45 + * @param {*} [options_] - Fetch options
46 + * @return {Promise<import('./response').default>}
47 + */
48 +export default async function fetch(url, options_) {
49 + return new Promise((resolve, reject) => {
50 + // Build request object
51 + const request = new Request(url, options_);
52 + const {parsedURL, options} = getNodeRequestOptions(request);
53 + if (!supportedSchemas.has(parsedURL.protocol)) {
54 + throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, '')}" is not supported.`);
55 + }
56 +
57 + if (parsedURL.protocol === 'data:') {
58 + const data = dataUriToBuffer(request.url);
59 + const response = new Response(data, {headers: {'Content-Type': data.typeFull}});
60 + resolve(response);
61 + return;
62 + }
63 +
64 + // Wrap http.request into fetch
65 + const send = (parsedURL.protocol === 'https:' ? https : http).request;
66 + const {signal} = request;
67 + let response = null;
68 +
69 + const abort = () => {
70 + const error = new AbortError('The operation was aborted.');
71 + reject(error);
72 + if (request.body && request.body instanceof Stream.Readable) {
73 + request.body.destroy(error);
74 + }
75 +
76 + if (!response || !response.body) {
77 + return;
78 + }
79 +
80 + response.body.emit('error', error);
81 + };
82 +
83 + if (signal && signal.aborted) {
84 + abort();
85 + return;
86 + }
87 +
88 + const abortAndFinalize = () => {
89 + abort();
90 + finalize();
91 + };
92 +
93 + // Send request
94 + const request_ = send(parsedURL.toString(), options);
95 +
96 + if (signal) {
97 + signal.addEventListener('abort', abortAndFinalize);
98 + }
99 +
100 + const finalize = () => {
101 + request_.abort();
102 + if (signal) {
103 + signal.removeEventListener('abort', abortAndFinalize);
104 + }
105 + };
106 +
107 + request_.on('error', error => {
108 + reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));
109 + finalize();
110 + });
111 +
112 + fixResponseChunkedTransferBadEnding(request_, error => {
113 + response.body.destroy(error);
114 + });
115 +
116 + /* c8 ignore next 18 */
117 + if (process.version < 'v14') {
118 + // Before Node.js 14, pipeline() does not fully support async iterators and does not always
119 + // properly handle when the socket close/end events are out of order.
120 + request_.on('socket', s => {
121 + let endedWithEventsCount;
122 + s.prependListener('end', () => {
123 + endedWithEventsCount = s._eventsCount;
124 + });
125 + s.prependListener('close', hadError => {
126 + // if end happened before close but the socket didn't emit an error, do it now
127 + if (response && endedWithEventsCount < s._eventsCount && !hadError) {
128 + const error = new Error('Premature close');
129 + error.code = 'ERR_STREAM_PREMATURE_CLOSE';
130 + response.body.emit('error', error);
131 + }
132 + });
133 + });
134 + }
135 +
136 + request_.on('response', response_ => {
137 + request_.setTimeout(0);
138 + const headers = fromRawHeaders(response_.rawHeaders);
139 +
140 + // HTTP fetch step 5
141 + if (isRedirect(response_.statusCode)) {
142 + // HTTP fetch step 5.2
143 + const location = headers.get('Location');
144 +
145 + // HTTP fetch step 5.3
146 + let locationURL = null;
147 + try {
148 + locationURL = location === null ? null : new URL(location, request.url);
149 + } catch {
150 + // error here can only be invalid URL in Location: header
151 + // do not throw when options.redirect == manual
152 + // let the user extract the errorneous redirect URL
153 + if (request.redirect !== 'manual') {
154 + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
155 + finalize();
156 + return;
157 + }
158 + }
159 +
160 + // HTTP fetch step 5.5
161 + switch (request.redirect) {
162 + case 'error':
163 + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
164 + finalize();
165 + return;
166 + case 'manual':
167 + // Nothing to do
168 + break;
169 + case 'follow': {
170 + // HTTP-redirect fetch step 2
171 + if (locationURL === null) {
172 + break;
173 + }
174 +
175 + // HTTP-redirect fetch step 5
176 + if (request.counter >= request.follow) {
177 + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
178 + finalize();
179 + return;
180 + }
181 +
182 + // HTTP-redirect fetch step 6 (counter increment)
183 + // Create a new Request object.
184 + const requestOptions = {
185 + headers: new Headers(request.headers),
186 + follow: request.follow,
187 + counter: request.counter + 1,
188 + agent: request.agent,
189 + compress: request.compress,
190 + method: request.method,
191 + body: clone(request),
192 + signal: request.signal,
193 + size: request.size,
194 + referrer: request.referrer,
195 + referrerPolicy: request.referrerPolicy
196 + };
197 +
198 + // when forwarding sensitive headers like "Authorization",
199 + // "WWW-Authenticate", and "Cookie" to untrusted targets,
200 + // headers will be ignored when following a redirect to a domain
201 + // that is not a subdomain match or exact match of the initial domain.
202 + // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com"
203 + // will forward the sensitive headers, but a redirect to "bar.com" will not.
204 + if (!isDomainOrSubdomain(request.url, locationURL)) {
205 + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
206 + requestOptions.headers.delete(name);
207 + }
208 + }
209 +
210 + // HTTP-redirect fetch step 9
211 + if (response_.statusCode !== 303 && request.body && options_.body instanceof Stream.Readable) {
212 + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
213 + finalize();
214 + return;
215 + }
216 +
217 + // HTTP-redirect fetch step 11
218 + if (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) {
219 + requestOptions.method = 'GET';
220 + requestOptions.body = undefined;
221 + requestOptions.headers.delete('content-length');
222 + }
223 +
224 + // HTTP-redirect fetch step 14
225 + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
226 + if (responseReferrerPolicy) {
227 + requestOptions.referrerPolicy = responseReferrerPolicy;
228 + }
229 +
230 + // HTTP-redirect fetch step 15
231 + resolve(fetch(new Request(locationURL, requestOptions)));
232 + finalize();
233 + return;
234 + }
235 +
236 + default:
237 + return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));
238 + }
239 + }
240 +
241 + // Prepare response
242 + if (signal) {
243 + response_.once('end', () => {
244 + signal.removeEventListener('abort', abortAndFinalize);
245 + });
246 + }
247 +
248 + let body = pump(response_, new PassThrough(), error => {
249 + if (error) {
250 + reject(error);
251 + }
252 + });
253 + // see https://github.com/nodejs/node/pull/29376
254 + /* c8 ignore next 3 */
255 + if (process.version < 'v12.10') {
256 + response_.on('aborted', abortAndFinalize);
257 + }
258 +
259 + const responseOptions = {
260 + url: request.url,
261 + status: response_.statusCode,
262 + statusText: response_.statusMessage,
263 + headers,
264 + size: request.size,
265 + counter: request.counter,
266 + highWaterMark: request.highWaterMark
267 + };
268 +
269 + // HTTP-network fetch step 12.1.1.3
270 + const codings = headers.get('Content-Encoding');
271 +
272 + // HTTP-network fetch step 12.1.1.4: handle content codings
273 +
274 + // in following scenarios we ignore compression support
275 + // 1. compression support is disabled
276 + // 2. HEAD request
277 + // 3. no Content-Encoding header
278 + // 4. no content response (204)
279 + // 5. content not modified response (304)
280 + if (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
281 + response = new Response(body, responseOptions);
282 + resolve(response);
283 + return;
284 + }
285 +
286 + // For Node v6+
287 + // Be less strict when decoding compressed responses, since sometimes
288 + // servers send slightly invalid responses that are still accepted
289 + // by common browsers.
290 + // Always using Z_SYNC_FLUSH is what cURL does.
291 + const zlibOptions = {
292 + flush: zlib.Z_SYNC_FLUSH,
293 + finishFlush: zlib.Z_SYNC_FLUSH
294 + };
295 +
296 + // For gzip
297 + if (codings === 'gzip' || codings === 'x-gzip') {
298 + body = pump(body, zlib.createGunzip(zlibOptions), error => {
299 + if (error) {
300 + reject(error);
301 + }
302 + });
303 + response = new Response(body, responseOptions);
304 + resolve(response);
305 + return;
306 + }
307 +
308 + // For deflate
309 + if (codings === 'deflate' || codings === 'x-deflate') {
310 + // Handle the infamous raw deflate response from old servers
311 + // a hack for old IIS and Apache servers
312 + const raw = pump(response_, new PassThrough(), error => {
313 + if (error) {
314 + reject(error);
315 + }
316 + });
317 + raw.once('data', chunk => {
318 + // See http://stackoverflow.com/questions/37519828
319 + if ((chunk[0] & 0x0F) === 0x08) {
320 + body = pump(body, zlib.createInflate(), error => {
321 + if (error) {
322 + reject(error);
323 + }
324 + });
325 + } else {
326 + body = pump(body, zlib.createInflateRaw(), error => {
327 + if (error) {
328 + reject(error);
329 + }
330 + });
331 + }
332 +
333 + response = new Response(body, responseOptions);
334 + resolve(response);
335 + });
336 + raw.once('end', () => {
337 + // Some old IIS servers return zero-length OK deflate responses, so
338 + // 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903
339 + if (!response) {
340 + response = new Response(body, responseOptions);
341 + resolve(response);
342 + }
343 + });
344 + return;
345 + }
346 +
347 + // For br
348 + if (codings === 'br') {
349 + body = pump(body, zlib.createBrotliDecompress(), error => {
350 + if (error) {
351 + reject(error);
352 + }
353 + });
354 + response = new Response(body, responseOptions);
355 + resolve(response);
356 + return;
357 + }
358 +
359 + // Otherwise, use response as-is
360 + response = new Response(body, responseOptions);
361 + resolve(response);
362 + });
363 +
364 + // eslint-disable-next-line promise/prefer-await-to-then
365 + writeToStream(request_, request).catch(reject);
366 + });
367 +}
368 +
369 +function fixResponseChunkedTransferBadEnding(request, errorCallback) {
370 + const LAST_CHUNK = Buffer.from('0\r\n\r\n');
371 +
372 + let isChunkedTransfer = false;
373 + let properLastChunkReceived = false;
374 + let previousChunk;
375 +
376 + request.on('response', response => {
377 + const {headers} = response;
378 + isChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length'];
379 + });
380 +
381 + request.on('socket', socket => {
382 + const onSocketClose = () => {
383 + if (isChunkedTransfer && !properLastChunkReceived) {
384 + const error = new Error('Premature close');
385 + error.code = 'ERR_STREAM_PREMATURE_CLOSE';
386 + errorCallback(error);
387 + }
388 + };
389 +
390 + socket.prependListener('close', onSocketClose);
391 +
392 + request.on('abort', () => {
393 + socket.removeListener('close', onSocketClose);
394 + });
395 +
396 + socket.on('data', buf => {
397 + properLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0;
398 +
399 + // Sometimes final 0-length chunk and end of message code are in separate packets
400 + if (!properLastChunkReceived && previousChunk) {
401 + properLastChunkReceived = (
402 + Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 &&
403 + Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0
404 + );
405 + }
406 +
407 + previousChunk = buf;
408 + });
409 + });
410 +}
1 +/**
2 + * Request.js
3 + *
4 + * Request class contains server only options
5 + *
6 + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
7 + */
8 +
9 +import {format as formatUrl} from 'node:url';
10 +import {deprecate} from 'node:util';
11 +import Headers from './headers.js';
12 +import Body, {clone, extractContentType, getTotalBytes} from './body.js';
13 +import {isAbortSignal} from './utils/is.js';
14 +import {getSearch} from './utils/get-search.js';
15 +import {
16 + validateReferrerPolicy, determineRequestsReferrer, DEFAULT_REFERRER_POLICY
17 +} from './utils/referrer.js';
18 +
19 +const INTERNALS = Symbol('Request internals');
20 +
21 +/**
22 + * Check if `obj` is an instance of Request.
23 + *
24 + * @param {*} object
25 + * @return {boolean}
26 + */
27 +const isRequest = object => {
28 + return (
29 + typeof object === 'object' &&
30 + typeof object[INTERNALS] === 'object'
31 + );
32 +};
33 +
34 +const doBadDataWarn = deprecate(() => {},
35 + '.data is not a valid RequestInit property, use .body instead',
36 + 'https://github.com/node-fetch/node-fetch/issues/1000 (request)');
37 +
38 +/**
39 + * Request class
40 + *
41 + * Ref: https://fetch.spec.whatwg.org/#request-class
42 + *
43 + * @param Mixed input Url or Request instance
44 + * @param Object init Custom options
45 + * @return Void
46 + */
47 +export default class Request extends Body {
48 + constructor(input, init = {}) {
49 + let parsedURL;
50 +
51 + // Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245)
52 + if (isRequest(input)) {
53 + parsedURL = new URL(input.url);
54 + } else {
55 + parsedURL = new URL(input);
56 + input = {};
57 + }
58 +
59 + if (parsedURL.username !== '' || parsedURL.password !== '') {
60 + throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
61 + }
62 +
63 + let method = init.method || input.method || 'GET';
64 + if (/^(delete|get|head|options|post|put)$/i.test(method)) {
65 + method = method.toUpperCase();
66 + }
67 +
68 + if ('data' in init) {
69 + doBadDataWarn();
70 + }
71 +
72 + // eslint-disable-next-line no-eq-null, eqeqeq
73 + if ((init.body != null || (isRequest(input) && input.body !== null)) &&
74 + (method === 'GET' || method === 'HEAD')) {
75 + throw new TypeError('Request with GET/HEAD method cannot have body');
76 + }
77 +
78 + const inputBody = init.body ?
79 + init.body :
80 + (isRequest(input) && input.body !== null ?
81 + clone(input) :
82 + null);
83 +
84 + super(inputBody, {
85 + size: init.size || input.size || 0
86 + });
87 +
88 + const headers = new Headers(init.headers || input.headers || {});
89 +
90 + if (inputBody !== null && !headers.has('Content-Type')) {
91 + const contentType = extractContentType(inputBody, this);
92 + if (contentType) {
93 + headers.set('Content-Type', contentType);
94 + }
95 + }
96 +
97 + let signal = isRequest(input) ?
98 + input.signal :
99 + null;
100 + if ('signal' in init) {
101 + signal = init.signal;
102 + }
103 +
104 + // eslint-disable-next-line no-eq-null, eqeqeq
105 + if (signal != null && !isAbortSignal(signal)) {
106 + throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget');
107 + }
108 +
109 + // §5.4, Request constructor steps, step 15.1
110 + // eslint-disable-next-line no-eq-null, eqeqeq
111 + let referrer = init.referrer == null ? input.referrer : init.referrer;
112 + if (referrer === '') {
113 + // §5.4, Request constructor steps, step 15.2
114 + referrer = 'no-referrer';
115 + } else if (referrer) {
116 + // §5.4, Request constructor steps, step 15.3.1, 15.3.2
117 + const parsedReferrer = new URL(referrer);
118 + // §5.4, Request constructor steps, step 15.3.3, 15.3.4
119 + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer;
120 + } else {
121 + referrer = undefined;
122 + }
123 +
124 + this[INTERNALS] = {
125 + method,
126 + redirect: init.redirect || input.redirect || 'follow',
127 + headers,
128 + parsedURL,
129 + signal,
130 + referrer
131 + };
132 +
133 + // Node-fetch-only options
134 + this.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow;
135 + this.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress;
136 + this.counter = init.counter || input.counter || 0;
137 + this.agent = init.agent || input.agent;
138 + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;
139 + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;
140 +
141 + // §5.4, Request constructor steps, step 16.
142 + // Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy
143 + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || '';
144 + }
145 +
146 + /** @returns {string} */
147 + get method() {
148 + return this[INTERNALS].method;
149 + }
150 +
151 + /** @returns {string} */
152 + get url() {
153 + return formatUrl(this[INTERNALS].parsedURL);
154 + }
155 +
156 + /** @returns {Headers} */
157 + get headers() {
158 + return this[INTERNALS].headers;
159 + }
160 +
161 + get redirect() {
162 + return this[INTERNALS].redirect;
163 + }
164 +
165 + /** @returns {AbortSignal} */
166 + get signal() {
167 + return this[INTERNALS].signal;
168 + }
169 +
170 + // https://fetch.spec.whatwg.org/#dom-request-referrer
171 + get referrer() {
172 + if (this[INTERNALS].referrer === 'no-referrer') {
173 + return '';
174 + }
175 +
176 + if (this[INTERNALS].referrer === 'client') {
177 + return 'about:client';
178 + }
179 +
180 + if (this[INTERNALS].referrer) {
181 + return this[INTERNALS].referrer.toString();
182 + }
183 +
184 + return undefined;
185 + }
186 +
187 + get referrerPolicy() {
188 + return this[INTERNALS].referrerPolicy;
189 + }
190 +
191 + set referrerPolicy(referrerPolicy) {
192 + this[INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy);
193 + }
194 +
195 + /**
196 + * Clone this request
197 + *
198 + * @return Request
199 + */
200 + clone() {
201 + return new Request(this);
202 + }
203 +
204 + get [Symbol.toStringTag]() {
205 + return 'Request';
206 + }
207 +}
208 +
209 +Object.defineProperties(Request.prototype, {
210 + method: {enumerable: true},
211 + url: {enumerable: true},
212 + headers: {enumerable: true},
213 + redirect: {enumerable: true},
214 + clone: {enumerable: true},
215 + signal: {enumerable: true},
216 + referrer: {enumerable: true},
217 + referrerPolicy: {enumerable: true}
218 +});
219 +
220 +/**
221 + * Convert a Request to Node.js http request options.
222 + *
223 + * @param {Request} request - A Request instance
224 + * @return The options object to be passed to http.request
225 + */
226 +export const getNodeRequestOptions = request => {
227 + const {parsedURL} = request[INTERNALS];
228 + const headers = new Headers(request[INTERNALS].headers);
229 +
230 + // Fetch step 1.3
231 + if (!headers.has('Accept')) {
232 + headers.set('Accept', '*/*');
233 + }
234 +
235 + // HTTP-network-or-cache fetch steps 2.4-2.7
236 + let contentLengthValue = null;
237 + if (request.body === null && /^(post|put)$/i.test(request.method)) {
238 + contentLengthValue = '0';
239 + }
240 +
241 + if (request.body !== null) {
242 + const totalBytes = getTotalBytes(request);
243 + // Set Content-Length if totalBytes is a number (that is not NaN)
244 + if (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) {
245 + contentLengthValue = String(totalBytes);
246 + }
247 + }
248 +
249 + if (contentLengthValue) {
250 + headers.set('Content-Length', contentLengthValue);
251 + }
252 +
253 + // 4.1. Main fetch, step 2.6
254 + // > If request's referrer policy is the empty string, then set request's referrer policy to the
255 + // > default referrer policy.
256 + if (request.referrerPolicy === '') {
257 + request.referrerPolicy = DEFAULT_REFERRER_POLICY;
258 + }
259 +
260 + // 4.1. Main fetch, step 2.7
261 + // > If request's referrer is not "no-referrer", set request's referrer to the result of invoking
262 + // > determine request's referrer.
263 + if (request.referrer && request.referrer !== 'no-referrer') {
264 + request[INTERNALS].referrer = determineRequestsReferrer(request);
265 + } else {
266 + request[INTERNALS].referrer = 'no-referrer';
267 + }
268 +
269 + // 4.5. HTTP-network-or-cache fetch, step 6.9
270 + // > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized
271 + // > and isomorphic encoded, to httpRequest's header list.
272 + if (request[INTERNALS].referrer instanceof URL) {
273 + headers.set('Referer', request.referrer);
274 + }
275 +
276 + // HTTP-network-or-cache fetch step 2.11
277 + if (!headers.has('User-Agent')) {
278 + headers.set('User-Agent', 'node-fetch');
279 + }
280 +
281 + // HTTP-network-or-cache fetch step 2.15
282 + if (request.compress && !headers.has('Accept-Encoding')) {
283 + headers.set('Accept-Encoding', 'gzip,deflate,br');
284 + }
285 +
286 + let {agent} = request;
287 + if (typeof agent === 'function') {
288 + agent = agent(parsedURL);
289 + }
290 +
291 + if (!headers.has('Connection') && !agent) {
292 + headers.set('Connection', 'close');
293 + }
294 +
295 + // HTTP-network fetch step 4.2
296 + // chunked encoding is handled by Node.js
297 +
298 + const search = getSearch(parsedURL);
299 +
300 + // Pass the full URL directly to request(), but overwrite the following
301 + // options:
302 + const options = {
303 + // Overwrite search to retain trailing ? (issue #776)
304 + path: parsedURL.pathname + search,
305 + // The following options are not expressed in the URL
306 + method: request.method,
307 + headers: headers[Symbol.for('nodejs.util.inspect.custom')](),
308 + insecureHTTPParser: request.insecureHTTPParser,
309 + agent
310 + };
311 +
312 + return {
313 + /** @type {URL} */
314 + parsedURL,
315 + options
316 + };
317 +};
1 +/**
2 + * Response.js
3 + *
4 + * Response class provides content decoding
5 + */
6 +
7 +import Headers from './headers.js';
8 +import Body, {clone, extractContentType} from './body.js';
9 +import {isRedirect} from './utils/is-redirect.js';
10 +
11 +const INTERNALS = Symbol('Response internals');
12 +
13 +/**
14 + * Response class
15 + *
16 + * Ref: https://fetch.spec.whatwg.org/#response-class
17 + *
18 + * @param Stream body Readable stream
19 + * @param Object opts Response options
20 + * @return Void
21 + */
22 +export default class Response extends Body {
23 + constructor(body = null, options = {}) {
24 + super(body, options);
25 +
26 + // eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition
27 + const status = options.status != null ? options.status : 200;
28 +
29 + const headers = new Headers(options.headers);
30 +
31 + if (body !== null && !headers.has('Content-Type')) {
32 + const contentType = extractContentType(body, this);
33 + if (contentType) {
34 + headers.append('Content-Type', contentType);
35 + }
36 + }
37 +
38 + this[INTERNALS] = {
39 + type: 'default',
40 + url: options.url,
41 + status,
42 + statusText: options.statusText || '',
43 + headers,
44 + counter: options.counter,
45 + highWaterMark: options.highWaterMark
46 + };
47 + }
48 +
49 + get type() {
50 + return this[INTERNALS].type;
51 + }
52 +
53 + get url() {
54 + return this[INTERNALS].url || '';
55 + }
56 +
57 + get status() {
58 + return this[INTERNALS].status;
59 + }
60 +
61 + /**
62 + * Convenience property representing if the request ended normally
63 + */
64 + get ok() {
65 + return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300;
66 + }
67 +
68 + get redirected() {
69 + return this[INTERNALS].counter > 0;
70 + }
71 +
72 + get statusText() {
73 + return this[INTERNALS].statusText;
74 + }
75 +
76 + get headers() {
77 + return this[INTERNALS].headers;
78 + }
79 +
80 + get highWaterMark() {
81 + return this[INTERNALS].highWaterMark;
82 + }
83 +
84 + /**
85 + * Clone this response
86 + *
87 + * @return Response
88 + */
89 + clone() {
90 + return new Response(clone(this, this.highWaterMark), {
91 + type: this.type,
92 + url: this.url,
93 + status: this.status,
94 + statusText: this.statusText,
95 + headers: this.headers,
96 + ok: this.ok,
97 + redirected: this.redirected,
98 + size: this.size,
99 + highWaterMark: this.highWaterMark
100 + });
101 + }
102 +
103 + /**
104 + * @param {string} url The URL that the new response is to originate from.
105 + * @param {number} status An optional status code for the response (e.g., 302.)
106 + * @returns {Response} A Response object.
107 + */
108 + static redirect(url, status = 302) {
109 + if (!isRedirect(status)) {
110 + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
111 + }
112 +
113 + return new Response(null, {
114 + headers: {
115 + location: new URL(url).toString()
116 + },
117 + status
118 + });
119 + }
120 +
121 + static error() {
122 + const response = new Response(null, {status: 0, statusText: ''});
123 + response[INTERNALS].type = 'error';
124 + return response;
125 + }
126 +
127 + get [Symbol.toStringTag]() {
128 + return 'Response';
129 + }
130 +}
131 +
132 +Object.defineProperties(Response.prototype, {
133 + type: {enumerable: true},
134 + url: {enumerable: true},
135 + status: {enumerable: true},
136 + ok: {enumerable: true},
137 + redirected: {enumerable: true},
138 + statusText: {enumerable: true},
139 + headers: {enumerable: true},
140 + clone: {enumerable: true}
141 +});
1 +export const getSearch = parsedURL => {
2 + if (parsedURL.search) {
3 + return parsedURL.search;
4 + }
5 +
6 + const lastOffset = parsedURL.href.length - 1;
7 + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : '');
8 + return parsedURL.href[lastOffset - hash.length] === '?' ? '?' : '';
9 +};
1 +const redirectStatus = new Set([301, 302, 303, 307, 308]);
2 +
3 +/**
4 + * Redirect code matching
5 + *
6 + * @param {number} code - Status code
7 + * @return {boolean}
8 + */
9 +export const isRedirect = code => {
10 + return redirectStatus.has(code);
11 +};
1 +/**
2 + * Is.js
3 + *
4 + * Object type checks.
5 + */
6 +
7 +const NAME = Symbol.toStringTag;
8 +
9 +/**
10 + * Check if `obj` is a URLSearchParams object
11 + * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143
12 + * @param {*} object - Object to check for
13 + * @return {boolean}
14 + */
15 +export const isURLSearchParameters = object => {
16 + return (
17 + typeof object === 'object' &&
18 + typeof object.append === 'function' &&
19 + typeof object.delete === 'function' &&
20 + typeof object.get === 'function' &&
21 + typeof object.getAll === 'function' &&
22 + typeof object.has === 'function' &&
23 + typeof object.set === 'function' &&
24 + typeof object.sort === 'function' &&
25 + object[NAME] === 'URLSearchParams'
26 + );
27 +};
28 +
29 +/**
30 + * Check if `object` is a W3C `Blob` object (which `File` inherits from)
31 + * @param {*} object - Object to check for
32 + * @return {boolean}
33 + */
34 +export const isBlob = object => {
35 + return (
36 + object &&
37 + typeof object === 'object' &&
38 + typeof object.arrayBuffer === 'function' &&
39 + typeof object.type === 'string' &&
40 + typeof object.stream === 'function' &&
41 + typeof object.constructor === 'function' &&
42 + /^(Blob|File)$/.test(object[NAME])
43 + );
44 +};
45 +
46 +/**
47 + * Check if `obj` is an instance of AbortSignal.
48 + * @param {*} object - Object to check for
49 + * @return {boolean}
50 + */
51 +export const isAbortSignal = object => {
52 + return (
53 + typeof object === 'object' && (
54 + object[NAME] === 'AbortSignal' ||
55 + object[NAME] === 'EventTarget'
56 + )
57 + );
58 +};
59 +
60 +/**
61 + * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of
62 + * the parent domain.
63 + *
64 + * Both domains must already be in canonical form.
65 + * @param {string|URL} original
66 + * @param {string|URL} destination
67 + */
68 +export const isDomainOrSubdomain = (destination, original) => {
69 + const orig = new URL(original).hostname;
70 + const dest = new URL(destination).hostname;
71 +
72 + return orig === dest || orig.endsWith(`.${dest}`);
73 +};
1 +import {File} from 'fetch-blob/from.js';
2 +import {FormData} from 'formdata-polyfill/esm.min.js';
3 +
4 +let s = 0;
5 +const S = {
6 + START_BOUNDARY: s++,
7 + HEADER_FIELD_START: s++,
8 + HEADER_FIELD: s++,
9 + HEADER_VALUE_START: s++,
10 + HEADER_VALUE: s++,
11 + HEADER_VALUE_ALMOST_DONE: s++,
12 + HEADERS_ALMOST_DONE: s++,
13 + PART_DATA_START: s++,
14 + PART_DATA: s++,
15 + END: s++
16 +};
17 +
18 +let f = 1;
19 +const F = {
20 + PART_BOUNDARY: f,
21 + LAST_BOUNDARY: f *= 2
22 +};
23 +
24 +const LF = 10;
25 +const CR = 13;
26 +const SPACE = 32;
27 +const HYPHEN = 45;
28 +const COLON = 58;
29 +const A = 97;
30 +const Z = 122;
31 +
32 +const lower = c => c | 0x20;
33 +
34 +const noop = () => {};
35 +
36 +class MultipartParser {
37 + /**
38 + * @param {string} boundary
39 + */
40 + constructor(boundary) {
41 + this.index = 0;
42 + this.flags = 0;
43 +
44 + this.onHeaderEnd = noop;
45 + this.onHeaderField = noop;
46 + this.onHeadersEnd = noop;
47 + this.onHeaderValue = noop;
48 + this.onPartBegin = noop;
49 + this.onPartData = noop;
50 + this.onPartEnd = noop;
51 +
52 + this.boundaryChars = {};
53 +
54 + boundary = '\r\n--' + boundary;
55 + const ui8a = new Uint8Array(boundary.length);
56 + for (let i = 0; i < boundary.length; i++) {
57 + ui8a[i] = boundary.charCodeAt(i);
58 + this.boundaryChars[ui8a[i]] = true;
59 + }
60 +
61 + this.boundary = ui8a;
62 + this.lookbehind = new Uint8Array(this.boundary.length + 8);
63 + this.state = S.START_BOUNDARY;
64 + }
65 +
66 + /**
67 + * @param {Uint8Array} data
68 + */
69 + write(data) {
70 + let i = 0;
71 + const length_ = data.length;
72 + let previousIndex = this.index;
73 + let {lookbehind, boundary, boundaryChars, index, state, flags} = this;
74 + const boundaryLength = this.boundary.length;
75 + const boundaryEnd = boundaryLength - 1;
76 + const bufferLength = data.length;
77 + let c;
78 + let cl;
79 +
80 + const mark = name => {
81 + this[name + 'Mark'] = i;
82 + };
83 +
84 + const clear = name => {
85 + delete this[name + 'Mark'];
86 + };
87 +
88 + const callback = (callbackSymbol, start, end, ui8a) => {
89 + if (start === undefined || start !== end) {
90 + this[callbackSymbol](ui8a && ui8a.subarray(start, end));
91 + }
92 + };
93 +
94 + const dataCallback = (name, clear) => {
95 + const markSymbol = name + 'Mark';
96 + if (!(markSymbol in this)) {
97 + return;
98 + }
99 +
100 + if (clear) {
101 + callback(name, this[markSymbol], i, data);
102 + delete this[markSymbol];
103 + } else {
104 + callback(name, this[markSymbol], data.length, data);
105 + this[markSymbol] = 0;
106 + }
107 + };
108 +
109 + for (i = 0; i < length_; i++) {
110 + c = data[i];
111 +
112 + switch (state) {
113 + case S.START_BOUNDARY:
114 + if (index === boundary.length - 2) {
115 + if (c === HYPHEN) {
116 + flags |= F.LAST_BOUNDARY;
117 + } else if (c !== CR) {
118 + return;
119 + }
120 +
121 + index++;
122 + break;
123 + } else if (index - 1 === boundary.length - 2) {
124 + if (flags & F.LAST_BOUNDARY && c === HYPHEN) {
125 + state = S.END;
126 + flags = 0;
127 + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) {
128 + index = 0;
129 + callback('onPartBegin');
130 + state = S.HEADER_FIELD_START;
131 + } else {
132 + return;
133 + }
134 +
135 + break;
136 + }
137 +
138 + if (c !== boundary[index + 2]) {
139 + index = -2;
140 + }
141 +
142 + if (c === boundary[index + 2]) {
143 + index++;
144 + }
145 +
146 + break;
147 + case S.HEADER_FIELD_START:
148 + state = S.HEADER_FIELD;
149 + mark('onHeaderField');
150 + index = 0;
151 + // falls through
152 + case S.HEADER_FIELD:
153 + if (c === CR) {
154 + clear('onHeaderField');
155 + state = S.HEADERS_ALMOST_DONE;
156 + break;
157 + }
158 +
159 + index++;
160 + if (c === HYPHEN) {
161 + break;
162 + }
163 +
164 + if (c === COLON) {
165 + if (index === 1) {
166 + // empty header field
167 + return;
168 + }
169 +
170 + dataCallback('onHeaderField', true);
171 + state = S.HEADER_VALUE_START;
172 + break;
173 + }
174 +
175 + cl = lower(c);
176 + if (cl < A || cl > Z) {
177 + return;
178 + }
179 +
180 + break;
181 + case S.HEADER_VALUE_START:
182 + if (c === SPACE) {
183 + break;
184 + }
185 +
186 + mark('onHeaderValue');
187 + state = S.HEADER_VALUE;
188 + // falls through
189 + case S.HEADER_VALUE:
190 + if (c === CR) {
191 + dataCallback('onHeaderValue', true);
192 + callback('onHeaderEnd');
193 + state = S.HEADER_VALUE_ALMOST_DONE;
194 + }
195 +
196 + break;
197 + case S.HEADER_VALUE_ALMOST_DONE:
198 + if (c !== LF) {
199 + return;
200 + }
201 +
202 + state = S.HEADER_FIELD_START;
203 + break;
204 + case S.HEADERS_ALMOST_DONE:
205 + if (c !== LF) {
206 + return;
207 + }
208 +
209 + callback('onHeadersEnd');
210 + state = S.PART_DATA_START;
211 + break;
212 + case S.PART_DATA_START:
213 + state = S.PART_DATA;
214 + mark('onPartData');
215 + // falls through
216 + case S.PART_DATA:
217 + previousIndex = index;
218 +
219 + if (index === 0) {
220 + // boyer-moore derrived algorithm to safely skip non-boundary data
221 + i += boundaryEnd;
222 + while (i < bufferLength && !(data[i] in boundaryChars)) {
223 + i += boundaryLength;
224 + }
225 +
226 + i -= boundaryEnd;
227 + c = data[i];
228 + }
229 +
230 + if (index < boundary.length) {
231 + if (boundary[index] === c) {
232 + if (index === 0) {
233 + dataCallback('onPartData', true);
234 + }
235 +
236 + index++;
237 + } else {
238 + index = 0;
239 + }
240 + } else if (index === boundary.length) {
241 + index++;
242 + if (c === CR) {
243 + // CR = part boundary
244 + flags |= F.PART_BOUNDARY;
245 + } else if (c === HYPHEN) {
246 + // HYPHEN = end boundary
247 + flags |= F.LAST_BOUNDARY;
248 + } else {
249 + index = 0;
250 + }
251 + } else if (index - 1 === boundary.length) {
252 + if (flags & F.PART_BOUNDARY) {
253 + index = 0;
254 + if (c === LF) {
255 + // unset the PART_BOUNDARY flag
256 + flags &= ~F.PART_BOUNDARY;
257 + callback('onPartEnd');
258 + callback('onPartBegin');
259 + state = S.HEADER_FIELD_START;
260 + break;
261 + }
262 + } else if (flags & F.LAST_BOUNDARY) {
263 + if (c === HYPHEN) {
264 + callback('onPartEnd');
265 + state = S.END;
266 + flags = 0;
267 + } else {
268 + index = 0;
269 + }
270 + } else {
271 + index = 0;
272 + }
273 + }
274 +
275 + if (index > 0) {
276 + // when matching a possible boundary, keep a lookbehind reference
277 + // in case it turns out to be a false lead
278 + lookbehind[index - 1] = c;
279 + } else if (previousIndex > 0) {
280 + // if our boundary turned out to be rubbish, the captured lookbehind
281 + // belongs to partData
282 + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
283 + callback('onPartData', 0, previousIndex, _lookbehind);
284 + previousIndex = 0;
285 + mark('onPartData');
286 +
287 + // reconsider the current character even so it interrupted the sequence
288 + // it could be the beginning of a new sequence
289 + i--;
290 + }
291 +
292 + break;
293 + case S.END:
294 + break;
295 + default:
296 + throw new Error(`Unexpected state entered: ${state}`);
297 + }
298 + }
299 +
300 + dataCallback('onHeaderField');
301 + dataCallback('onHeaderValue');
302 + dataCallback('onPartData');
303 +
304 + // Update properties for the next call
305 + this.index = index;
306 + this.state = state;
307 + this.flags = flags;
308 + }
309 +
310 + end() {
311 + if ((this.state === S.HEADER_FIELD_START && this.index === 0) ||
312 + (this.state === S.PART_DATA && this.index === this.boundary.length)) {
313 + this.onPartEnd();
314 + } else if (this.state !== S.END) {
315 + throw new Error('MultipartParser.end(): stream ended unexpectedly');
316 + }
317 + }
318 +}
319 +
320 +function _fileName(headerValue) {
321 + // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
322 + const m = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
323 + if (!m) {
324 + return;
325 + }
326 +
327 + const match = m[2] || m[3] || '';
328 + let filename = match.slice(match.lastIndexOf('\\') + 1);
329 + filename = filename.replace(/%22/g, '"');
330 + filename = filename.replace(/&#(\d{4});/g, (m, code) => {
331 + return String.fromCharCode(code);
332 + });
333 + return filename;
334 +}
335 +
336 +export async function toFormData(Body, ct) {
337 + if (!/multipart/i.test(ct)) {
338 + throw new TypeError('Failed to fetch');
339 + }
340 +
341 + const m = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
342 +
343 + if (!m) {
344 + throw new TypeError('no or bad content-type header, no multipart boundary');
345 + }
346 +
347 + const parser = new MultipartParser(m[1] || m[2]);
348 +
349 + let headerField;
350 + let headerValue;
351 + let entryValue;
352 + let entryName;
353 + let contentType;
354 + let filename;
355 + const entryChunks = [];
356 + const formData = new FormData();
357 +
358 + const onPartData = ui8a => {
359 + entryValue += decoder.decode(ui8a, {stream: true});
360 + };
361 +
362 + const appendToFile = ui8a => {
363 + entryChunks.push(ui8a);
364 + };
365 +
366 + const appendFileToFormData = () => {
367 + const file = new File(entryChunks, filename, {type: contentType});
368 + formData.append(entryName, file);
369 + };
370 +
371 + const appendEntryToFormData = () => {
372 + formData.append(entryName, entryValue);
373 + };
374 +
375 + const decoder = new TextDecoder('utf-8');
376 + decoder.decode();
377 +
378 + parser.onPartBegin = function () {
379 + parser.onPartData = onPartData;
380 + parser.onPartEnd = appendEntryToFormData;
381 +
382 + headerField = '';
383 + headerValue = '';
384 + entryValue = '';
385 + entryName = '';
386 + contentType = '';
387 + filename = null;
388 + entryChunks.length = 0;
389 + };
390 +
391 + parser.onHeaderField = function (ui8a) {
392 + headerField += decoder.decode(ui8a, {stream: true});
393 + };
394 +
395 + parser.onHeaderValue = function (ui8a) {
396 + headerValue += decoder.decode(ui8a, {stream: true});
397 + };
398 +
399 + parser.onHeaderEnd = function () {
400 + headerValue += decoder.decode();
401 + headerField = headerField.toLowerCase();
402 +
403 + if (headerField === 'content-disposition') {
404 + // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
405 + const m = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
406 +
407 + if (m) {
408 + entryName = m[2] || m[3] || '';
409 + }
410 +
411 + filename = _fileName(headerValue);
412 +
413 + if (filename) {
414 + parser.onPartData = appendToFile;
415 + parser.onPartEnd = appendFileToFormData;
416 + }
417 + } else if (headerField === 'content-type') {
418 + contentType = headerValue;
419 + }
420 +
421 + headerValue = '';
422 + headerField = '';
423 + };
424 +
425 + for await (const chunk of Body) {
426 + parser.write(chunk);
427 + }
428 +
429 + parser.end();
430 +
431 + return formData;
432 +}
1 +import {isIP} from 'node:net';
2 +
3 +/**
4 + * @external URL
5 + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL}
6 + */
7 +
8 +/**
9 + * @module utils/referrer
10 + * @private
11 + */
12 +
13 +/**
14 + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy §8.4. Strip url for use as a referrer}
15 + * @param {string} URL
16 + * @param {boolean} [originOnly=false]
17 + */
18 +export function stripURLForUseAsAReferrer(url, originOnly = false) {
19 + // 1. If url is null, return no referrer.
20 + if (url == null) { // eslint-disable-line no-eq-null, eqeqeq
21 + return 'no-referrer';
22 + }
23 +
24 + url = new URL(url);
25 +
26 + // 2. If url's scheme is a local scheme, then return no referrer.
27 + if (/^(about|blob|data):$/.test(url.protocol)) {
28 + return 'no-referrer';
29 + }
30 +
31 + // 3. Set url's username to the empty string.
32 + url.username = '';
33 +
34 + // 4. Set url's password to null.
35 + // Note: `null` appears to be a mistake as this actually results in the password being `"null"`.
36 + url.password = '';
37 +
38 + // 5. Set url's fragment to null.
39 + // Note: `null` appears to be a mistake as this actually results in the fragment being `"#null"`.
40 + url.hash = '';
41 +
42 + // 6. If the origin-only flag is true, then:
43 + if (originOnly) {
44 + // 6.1. Set url's path to null.
45 + // Note: `null` appears to be a mistake as this actually results in the path being `"/null"`.
46 + url.pathname = '';
47 +
48 + // 6.2. Set url's query to null.
49 + // Note: `null` appears to be a mistake as this actually results in the query being `"?null"`.
50 + url.search = '';
51 + }
52 +
53 + // 7. Return url.
54 + return url;
55 +}
56 +
57 +/**
58 + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy}
59 + */
60 +export const ReferrerPolicy = new Set([
61 + '',
62 + 'no-referrer',
63 + 'no-referrer-when-downgrade',
64 + 'same-origin',
65 + 'origin',
66 + 'strict-origin',
67 + 'origin-when-cross-origin',
68 + 'strict-origin-when-cross-origin',
69 + 'unsafe-url'
70 +]);
71 +
72 +/**
73 + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy}
74 + */
75 +export const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin';
76 +
77 +/**
78 + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy §3. Referrer Policies}
79 + * @param {string} referrerPolicy
80 + * @returns {string} referrerPolicy
81 + */
82 +export function validateReferrerPolicy(referrerPolicy) {
83 + if (!ReferrerPolicy.has(referrerPolicy)) {
84 + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
85 + }
86 +
87 + return referrerPolicy;
88 +}
89 +
90 +/**
91 + * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?}
92 + * @param {external:URL} url
93 + * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
94 + */
95 +export function isOriginPotentiallyTrustworthy(url) {
96 + // 1. If origin is an opaque origin, return "Not Trustworthy".
97 + // Not applicable
98 +
99 + // 2. Assert: origin is a tuple origin.
100 + // Not for implementations
101 +
102 + // 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy".
103 + if (/^(http|ws)s:$/.test(url.protocol)) {
104 + return true;
105 + }
106 +
107 + // 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy".
108 + const hostIp = url.host.replace(/(^\[)|(]$)/g, '');
109 + const hostIPVersion = isIP(hostIp);
110 +
111 + if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
112 + return true;
113 + }
114 +
115 + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
116 + return true;
117 + }
118 +
119 + // 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy".
120 + // We are returning FALSE here because we cannot ensure conformance to
121 + // let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)
122 + if (/^(.+\.)*localhost$/.test(url.host)) {
123 + return false;
124 + }
125 +
126 + // 6. If origin's scheme component is file, return "Potentially Trustworthy".
127 + if (url.protocol === 'file:') {
128 + return true;
129 + }
130 +
131 + // 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy".
132 + // Not supported
133 +
134 + // 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy".
135 + // Not supported
136 +
137 + // 9. Return "Not Trustworthy".
138 + return false;
139 +}
140 +
141 +/**
142 + * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?}
143 + * @param {external:URL} url
144 + * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
145 + */
146 +export function isUrlPotentiallyTrustworthy(url) {
147 + // 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy".
148 + if (/^about:(blank|srcdoc)$/.test(url)) {
149 + return true;
150 + }
151 +
152 + // 2. If url's scheme is "data", return "Potentially Trustworthy".
153 + if (url.protocol === 'data:') {
154 + return true;
155 + }
156 +
157 + // Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were
158 + // created. Therefore, blobs created in a trustworthy origin will themselves be potentially
159 + // trustworthy.
160 + if (/^(blob|filesystem):$/.test(url.protocol)) {
161 + return true;
162 + }
163 +
164 + // 3. Return the result of executing §3.2 Is origin potentially trustworthy? on url's origin.
165 + return isOriginPotentiallyTrustworthy(url);
166 +}
167 +
168 +/**
169 + * Modifies the referrerURL to enforce any extra security policy considerations.
170 + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7
171 + * @callback module:utils/referrer~referrerURLCallback
172 + * @param {external:URL} referrerURL
173 + * @returns {external:URL} modified referrerURL
174 + */
175 +
176 +/**
177 + * Modifies the referrerOrigin to enforce any extra security policy considerations.
178 + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7
179 + * @callback module:utils/referrer~referrerOriginCallback
180 + * @param {external:URL} referrerOrigin
181 + * @returns {external:URL} modified referrerOrigin
182 + */
183 +
184 +/**
185 + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}
186 + * @param {Request} request
187 + * @param {object} o
188 + * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback
189 + * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback
190 + * @returns {external:URL} Request's referrer
191 + */
192 +export function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) {
193 + // There are 2 notes in the specification about invalid pre-conditions. We return null, here, for
194 + // these cases:
195 + // > Note: If request's referrer is "no-referrer", Fetch will not call into this algorithm.
196 + // > Note: If request's referrer policy is the empty string, Fetch will not call into this
197 + // > algorithm.
198 + if (request.referrer === 'no-referrer' || request.referrerPolicy === '') {
199 + return null;
200 + }
201 +
202 + // 1. Let policy be request's associated referrer policy.
203 + const policy = request.referrerPolicy;
204 +
205 + // 2. Let environment be request's client.
206 + // not applicable to node.js
207 +
208 + // 3. Switch on request's referrer:
209 + if (request.referrer === 'about:client') {
210 + return 'no-referrer';
211 + }
212 +
213 + // "a URL": Let referrerSource be request's referrer.
214 + const referrerSource = request.referrer;
215 +
216 + // 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer.
217 + let referrerURL = stripURLForUseAsAReferrer(referrerSource);
218 +
219 + // 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the
220 + // origin-only flag set to true.
221 + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
222 +
223 + // 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set
224 + // referrerURL to referrerOrigin.
225 + if (referrerURL.toString().length > 4096) {
226 + referrerURL = referrerOrigin;
227 + }
228 +
229 + // 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary
230 + // policy considerations in the interests of minimizing data leakage. For example, the user
231 + // agent could strip the URL down to an origin, modify its host, replace it with an empty
232 + // string, etc.
233 + if (referrerURLCallback) {
234 + referrerURL = referrerURLCallback(referrerURL);
235 + }
236 +
237 + if (referrerOriginCallback) {
238 + referrerOrigin = referrerOriginCallback(referrerOrigin);
239 + }
240 +
241 + // 8.Execute the statements corresponding to the value of policy:
242 + const currentURL = new URL(request.url);
243 +
244 + switch (policy) {
245 + case 'no-referrer':
246 + return 'no-referrer';
247 +
248 + case 'origin':
249 + return referrerOrigin;
250 +
251 + case 'unsafe-url':
252 + return referrerURL;
253 +
254 + case 'strict-origin':
255 + // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a
256 + // potentially trustworthy URL, then return no referrer.
257 + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
258 + return 'no-referrer';
259 + }
260 +
261 + // 2. Return referrerOrigin.
262 + return referrerOrigin.toString();
263 +
264 + case 'strict-origin-when-cross-origin':
265 + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then
266 + // return referrerURL.
267 + if (referrerURL.origin === currentURL.origin) {
268 + return referrerURL;
269 + }
270 +
271 + // 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a
272 + // potentially trustworthy URL, then return no referrer.
273 + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
274 + return 'no-referrer';
275 + }
276 +
277 + // 3. Return referrerOrigin.
278 + return referrerOrigin;
279 +
280 + case 'same-origin':
281 + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then
282 + // return referrerURL.
283 + if (referrerURL.origin === currentURL.origin) {
284 + return referrerURL;
285 + }
286 +
287 + // 2. Return no referrer.
288 + return 'no-referrer';
289 +
290 + case 'origin-when-cross-origin':
291 + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then
292 + // return referrerURL.
293 + if (referrerURL.origin === currentURL.origin) {
294 + return referrerURL;
295 + }
296 +
297 + // Return referrerOrigin.
298 + return referrerOrigin;
299 +
300 + case 'no-referrer-when-downgrade':
301 + // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a
302 + // potentially trustworthy URL, then return no referrer.
303 + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
304 + return 'no-referrer';
305 + }
306 +
307 + // 2. Return referrerURL.
308 + return referrerURL;
309 +
310 + default:
311 + throw new TypeError(`Invalid referrerPolicy: ${policy}`);
312 + }
313 +}
314 +
315 +/**
316 + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header}
317 + * @param {Headers} headers Response headers
318 + * @returns {string} policy
319 + */
320 +export function parseReferrerPolicyFromHeader(headers) {
321 + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy`
322 + // and response’s header list.
323 + const policyTokens = (headers.get('referrer-policy') || '').split(/[,\s]+/);
324 +
325 + // 2. Let policy be the empty string.
326 + let policy = '';
327 +
328 + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty
329 + // string, then set policy to token.
330 + // Note: This algorithm loops over multiple policy values to allow deployment of new policy
331 + // values with fallbacks for older user agents, as described in § 11.1 Unknown Policy Values.
332 + for (const token of policyTokens) {
333 + if (token && ReferrerPolicy.has(token)) {
334 + policy = token;
335 + }
336 + }
337 +
338 + // 4. Return policy.
339 + return policy;
340 +}
1 +The MIT License (MIT)
2 +
3 +Copyright (c) 2020 Mattias Buelens
4 +Copyright (c) 2016 Diwank Singh Tomer
5 +
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to deal
8 +in the Software without restriction, including without limitation the rights
9 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 +copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be included in all
14 +copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 +SOFTWARE.
1 +# web-streams-polyfill
2 +
3 +Web Streams, based on the WHATWG spec reference implementation.
4 +
5 +[![build status](https://api.travis-ci.com/MattiasBuelens/web-streams-polyfill.svg?branch=master)](https://travis-ci.com/MattiasBuelens/web-streams-polyfill)
6 +[![npm version](https://img.shields.io/npm/v/web-streams-polyfill.svg)](https://www.npmjs.com/package/web-streams-polyfill)
7 +[![license](https://img.shields.io/npm/l/web-streams-polyfill.svg)](https://github.com/MattiasBuelens/web-streams-polyfill/blob/master/LICENSE)
8 +[![Join the chat at https://gitter.im/web-streams-polyfill/Lobby](https://badges.gitter.im/web-streams-polyfill/Lobby.svg)](https://gitter.im/web-streams-polyfill/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
9 +
10 +## Links
11 +
12 + - [Official spec][spec]
13 + - [Reference implementation][ref-impl]
14 +
15 +## Usage
16 +
17 +This library comes in multiple variants:
18 +* `web-streams-polyfill`: a polyfill that replaces the native stream implementations.
19 + Recommended for use in web apps supporting older browsers through a `<script>` tag.
20 +* `web-streams-polyfill/es6`: a polyfill targeting ES2015+ environments.
21 + Recommended for use in web apps supporting modern browsers through a `<script>` tag.
22 +* `web-streams-polyfill/es2018`: a polyfill targeting ES2018+ environments.
23 +* `web-streams-polyfill/ponyfill`: a [ponyfill] that provides
24 + the stream implementations without replacing any globals.
25 + Recommended for use in legacy Node applications, or in web libraries supporting older browsers.
26 +* `web-streams-polyfill/ponyfill/es6`: a ponyfill targeting ES2015+ environments.
27 + Recommended for use in Node 6+ applications, or in web libraries supporting modern browsers.
28 +* `web-streams-polyfill/ponyfill/es2018`: a ponyfill targeting ES2018+ environments.
29 + Recommended for use in Node 10+ applications.
30 +
31 +Each variant also includes TypeScript type definitions, compatible with the DOM type definitions for streams included in TypeScript.
32 +
33 +Usage as a polyfill:
34 +```html
35 +<!-- option 1: hosted by unpkg CDN -->
36 +<script src="https://unpkg.com/web-streams-polyfill/dist/polyfill.min.js"></script>
37 +<!-- option 2: self hosted -->
38 +<script src="/path/to/web-streams-polyfill/dist/polyfill.min.js"></script>
39 +<script>
40 +var readable = new ReadableStream();
41 +</script>
42 +```
43 +Usage as a Node module:
44 +```js
45 +var streams = require("web-streams-polyfill/ponyfill");
46 +var readable = new streams.ReadableStream();
47 +```
48 +Usage as a ES2015 module:
49 +```js
50 +import { ReadableStream } from "web-streams-polyfill/ponyfill";
51 +const readable = new ReadableStream();
52 +```
53 +
54 +### Compatibility
55 +
56 +The `polyfill` and `ponyfill` variants work in any ES5-compatible environment that has a global `Promise`.
57 +If you need to support older browsers or Node versions that do not have a native `Promise` implementation
58 +(check the [support table][promise-support]), you must first include a `Promise` polyfill
59 +(e.g. [promise-polyfill][promise-polyfill]).
60 +
61 +The `polyfill/es6` and `ponyfill/es6` variants work in any ES2015-compatible environment.
62 +
63 +The `polyfill/es2018` and `ponyfill/es2018` variants work in any ES2018-compatible environment.
64 +
65 +[Async iterable support for `ReadableStream`][rs-asynciterator] is available in all variants, but requires an ES2018-compatible environment or a polyfill for `Symbol.asyncIterator`.
66 +
67 +[`WritableStreamDefaultController.signal`][ws-controller-signal] is available in all variants, but requires a global `AbortController` constructor. If necessary, consider using a polyfill such as [abortcontroller-polyfill].
68 +
69 +### Compliance
70 +
71 +The polyfill implements [version `4b6b93c` (25 Oct 2021)][spec-snapshot] of the streams specification.
72 +
73 +The polyfill is tested against the same [web platform tests][wpt] that are used by browsers to test their native implementations.
74 +The polyfill aims to pass all tests, although it allows some exceptions for practical reasons:
75 +* The `es2018` variant passes all of the tests, except for the ["bad buffers and views" tests for readable byte streams][wpt-bad-buffers].
76 + These tests require the implementation to synchronously transfer the contents of an `ArrayBuffer`, which is not yet possible from JavaScript (although there is a [proposal][proposal-arraybuffer-transfer] to make it possible).
77 + The reference implementation "cheats" on these tests [by making a copy instead][ref-impl-transferarraybuffer], but that is unacceptable for the polyfill's performance ([#3][issue-3]).
78 +* The `es6` variant passes the same tests as the `es2018` variant, except for the [test for the prototype of `ReadableStream`'s async iterator][wpt-async-iterator-prototype].
79 + Retrieving the correct `%AsyncIteratorPrototype%` requires using an async generator (`async function* () {}`), which is invalid syntax before ES2018.
80 + Instead, the polyfill [creates its own version][stub-async-iterator-prototype] which is functionally equivalent to the real prototype.
81 +* The `es5` variant passes the same tests as the `es6` variant, except for various tests about specific characteristics of the constructors, properties and methods.
82 + These test failures do not affect the run-time behavior of the polyfill.
83 + For example:
84 + * The `name` property of down-leveled constructors is incorrect.
85 + * The `length` property of down-leveled constructors and methods with optional arguments is incorrect.
86 + * Not all properties and methods are correctly marked as non-enumerable.
87 + * Down-leveled class methods are not correctly marked as non-constructable.
88 +
89 +The type definitions are compatible with the built-in stream types of TypeScript 3.3.
90 +
91 +### Contributors
92 +
93 +Thanks to these people for their work on [the original polyfill][creatorrr-polyfill]:
94 +
95 + - Diwank Singh Tomer ([creatorrr](https://github.com/creatorrr))
96 + - Anders Riutta ([ariutta](https://github.com/ariutta))
97 +
98 +[spec]: https://streams.spec.whatwg.org
99 +[ref-impl]: https://github.com/whatwg/streams
100 +[ponyfill]: https://github.com/sindresorhus/ponyfill
101 +[promise-support]: https://kangax.github.io/compat-table/es6/#test-Promise
102 +[promise-polyfill]: https://www.npmjs.com/package/promise-polyfill
103 +[rs-asynciterator]: https://streams.spec.whatwg.org/#rs-asynciterator
104 +[ws-controller-signal]: https://streams.spec.whatwg.org/#ws-default-controller-signal
105 +[abortcontroller-polyfill]: https://www.npmjs.com/package/abortcontroller-polyfill
106 +[spec-snapshot]: https://streams.spec.whatwg.org/commit-snapshots/4b6b93c69e531e2fe45a6ed4cb1484a7ba4eb8bb/
107 +[wpt]: https://github.com/web-platform-tests/wpt/tree/96ca25f0f7526282c0d47e6bf6a7edd439da1968/streams
108 +[wpt-bad-buffers]: https://github.com/web-platform-tests/wpt/blob/96ca25f0f7526282c0d47e6bf6a7edd439da1968/streams/readable-byte-streams/bad-buffers-and-views.any.js
109 +[proposal-arraybuffer-transfer]: https://github.com/domenic/proposal-arraybuffer-transfer
110 +[ref-impl-transferarraybuffer]: https://github.com/whatwg/streams/blob/4b6b93c69e531e2fe45a6ed4cb1484a7ba4eb8bb/reference-implementation/lib/abstract-ops/ecmascript.js#L16
111 +[issue-3]: https://github.com/MattiasBuelens/web-streams-polyfill/issues/3
112 +[wpt-async-iterator-prototype]: https://github.com/web-platform-tests/wpt/blob/96ca25f0f7526282c0d47e6bf6a7edd439da1968/streams/readable-streams/async-iterator.any.js#L24
113 +[stub-async-iterator-prototype]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v2.0.0/src/target/es5/stub/async-iterator-prototype.ts
114 +[creatorrr-polyfill]: https://github.com/creatorrr/web-streams-polyfill
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
1 +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}const o="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function n(e){return"object"==typeof e&&null!==e||"function"==typeof e}const a=r,i=Promise,l=Promise.prototype.then,s=Promise.resolve.bind(i),u=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return s(e)}function f(e){return u(e)}function b(e,t,r){return l.call(e,t,r)}function h(e,t,r){b(b(e,t,r),void 0,a)}function _(e,t){h(e,t)}function m(e,t){h(e,void 0,t)}function p(e,t,r){return b(e,t,r)}function y(e){b(e,void 0,a)}const g=(()=>{const e=o&&o.queueMicrotask;if("function"==typeof e)return e;const t=d(void 0);return e=>b(t,e)})();function S(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function v(e,t,r){try{return d(S(e,t,r))}catch(e){return f(e)}}class w{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function R(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?q(e):"closed"===t._state?function(e){q(e),O(e)}(e):E(e,t._storedError)}function T(e,t){return br(e._ownerReadableStream,t)}function C(e){"readable"===e._ownerReadableStream._state?W(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){E(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function P(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function q(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function E(e,t){q(e),W(e,t)}function W(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function O(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const B=t("[[AbortSteps]]"),k=t("[[ErrorSteps]]"),j=t("[[CancelSteps]]"),A=t("[[PullSteps]]"),z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function L(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function F(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function I(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Q(e){return Number(e)}function Y(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Y(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Y(D(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function N(e,t){if(!dr(e))throw new TypeError(`${t} is not a ReadableStream.`)}function H(e){return new ReadableStreamDefaultReader(e)}function V(e,t){e._reader._readRequests.push(t)}function U(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function G(e){return e._reader._readRequests.length}function X(e){const t=e._reader;return void 0!==t&&!!J(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),N(e,"First parameter"),fr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");R(this,e),this._readRequests=new w}get closed(){return J(this)?this._closedPromise:f(Z("closed"))}cancel(e){return J(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(Z("cancel"))}read(){if(!J(this))return f(Z("read"));if(void 0===this._ownerReadableStream)return f(P("read from"));let e,t;const r=c(((r,o)=>{e=r,t=o}));return K(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!J(this))throw Z("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}}}function J(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function K(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[A](t)}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});const ee=Object.getPrototypeOf(Object.getPrototypeOf((async function*(){})).prototype);class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return f(P("iterate"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return K(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,g((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return f(P("finish iterating"));if(!this._preventCancel){const r=T(t,e);return C(t),p(r,(()=>({value:e,done:!0})))}return C(t),d({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():f(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):f(ne("return"))}};function oe(e){if(!n(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==ee&&Object.setPrototypeOf(re,ee);const ae=Number.isNaN||function(e){return e!=e};function ie(e){return e.slice()}function le(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function se(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return le(n,0,e,t,o),n}function ue(e){const t=se(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ce(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function de(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function fe(e){e._queue=new w,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!he(this))throw De("view");return this._view}respond(e){if(!he(this))throw De("respond");if($(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,je(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!he(this))throw De("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,Ae(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!be(this))throw Le("byobRequest");return Be(this)}get desiredSize(){if(!be(this))throw Le("desiredSize");return ke(this)}close(){if(!be(this))throw Le("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Ee(this)}enqueue(e){if(!be(this))throw Le("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);We(this,e)}error(e){if(!be(this))throw Le("error");Oe(this,e)}[j](e){me(this),fe(this);const t=this._cancelAlgorithm(e);return qe(this),t}[A](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,we(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}V(t,e),_e(this)}}function be(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function he(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function _e(e){if(!function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(X(t)&&G(t)>0)return!0;if(Me(t)&&$e(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,_e(e))}),(t=>{Oe(e,t)}))}function me(e){Re(e),e._pendingPullIntos=new w}function pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=ye(t);"default"===t.readerType?U(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function ye(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function ge(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function Se(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;le(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,ve(e,o,t),l-=o}return s}function ve(e,t,r){r.bytesFilled+=t}function we(e){0===e._queueTotalSize&&e._closeRequested?(qe(e),hr(e._controlledReadableByteStream)):_e(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Se(e,t)&&(Pe(e),pe(e._controlledReadableByteStream,t))}}function Ce(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){const r=e._controlledReadableByteStream;if(Me(r))for(;$e(r)>0;)pe(r,Pe(e))}(e):function(e,t,r){if(ve(0,t,r),r.bytesFilled<r.elementSize)return;Pe(e);const o=r.bytesFilled%r.elementSize;if(o>0){const t=r.byteOffset+r.bytesFilled,n=se(r.buffer,t-o,t);ge(e,n,0,n.byteLength)}r.bytesFilled-=o,pe(e._controlledReadableByteStream,r),Te(e)}(e,t,r),_e(e)}function Pe(e){return e._pendingPullIntos.shift()}function qe(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ee(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Oe(e,t),t}}qe(e),hr(t)}}function We(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,t.buffer=t.buffer}if(Re(e),X(r))if(0===G(r))ge(e,i,n,a);else{e._pendingPullIntos.length>0&&Pe(e);U(r,new Uint8Array(i,n,a),!1)}else Me(r)?(ge(e,i,n,a),Te(e)):ge(e,i,n,a);_e(e)}function Oe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(me(e),fe(e),qe(e),_r(r,t))}function Be(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function je(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,Ce(e,t)}function Ae(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,Ce(e,o)}function ze(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,fe(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new w,e._readableStreamController=t;h(d(r()),(()=>{t._started=!0,_e(t)}),(e=>{Oe(t,e)}))}function De(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Le(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Fe(e){return new ReadableStreamBYOBReader(e)}function Ie(e,t){e._reader._readIntoRequests.push(t)}function $e(e){return e._reader._readIntoRequests.length}function Me(e){const t=e._reader;return void 0!==t&&!!Qe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),N(e,"First parameter"),fr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!be(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");R(this,e),this._readIntoRequests=new w}get closed(){return Qe(this)?this._closedPromise:f(xe("closed"))}cancel(e){return Qe(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(xe("cancel"))}read(e){if(!Qe(this))return f(xe("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(P("read from"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return Ye(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Qe(this))throw xe("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}}}function Qe(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ye(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void Ie(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(Se(e,l)){const t=ye(l);return we(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Oe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),Ie(o,r),_e(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}function xe(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Ne(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function He(e){const{size:t}=e;return t||(()=>1)}function Ve(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Q(r),size:void 0===o?void 0:Ue(o,`${t} has member 'size' that`)}}function Ue(e,t){return F(e,t),t=>Q(e(t))}function Ge(e,t,r){return F(e,r),r=>v(e,t,[r])}function Xe(e,t,r){return F(e,r),()=>v(e,t,[])}function Je(e,t,r){return F(e,r),r=>S(e,t,[r])}function Ke(e,t,r){return F(e,r),(r,o)=>v(e,t,[r,o])}function Ze(e,t){if(!ot(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const et="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:I(e,"First parameter");const r=Ve(t,"Second parameter"),o=function(e,t){L(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ge(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:Xe(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:Je(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ke(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");rt(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=He(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a=()=>{},i=()=>d(void 0),l=()=>d(void 0),s=()=>d(void 0);void 0!==t.start&&(a=()=>t.start(n));void 0!==t.write&&(i=e=>t.write(e,n));void 0!==t.close&&(l=()=>t.close());void 0!==t.abort&&(s=e=>t.abort(e));vt(e,n,a,i,l,s,r,o)}(this,o,Ne(r,1),n)}get locked(){if(!ot(this))throw Et("locked");return nt(this)}abort(e){return ot(this)?nt(this)?f(new TypeError("Cannot abort a stream that already has a writer")):at(this,e):f(Et("abort"))}close(){return ot(this)?nt(this)?f(new TypeError("Cannot close a stream that already has a writer")):ct(this)?f(new TypeError("Cannot close an already-closing stream")):it(this):f(Et("close"))}getWriter(){if(!ot(this))throw Et("getWriter");return tt(this)}}function tt(e){return new WritableStreamDefaultWriter(e)}function rt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new w,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function ot(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function nt(e){return void 0!==e._writer}function at(e,t){var r;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort();const o=e._state;if("closed"===o||"errored"===o)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=c(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||st(e,t),a}function it(e){const t=e._state;if("closed"===t||"errored"===t)return f(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=c(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&$t(o),de(n=e._writableStreamController,gt,0),Tt(n),r}function lt(e,t){"writable"!==e._state?ut(e):st(e,t)}function st(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&mt(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&ut(e)}function ut(e){e._state="errored",e._writableStreamController[k]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new w,void 0===e._pendingAbortRequest)return void dt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void dt(e);h(e._writableStreamController[B](r._reason),(()=>{r._resolve(),dt(e)}),(t=>{r._reject(t),dt(e)}))}function ct(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function dt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&At(t,e._storedError)}function ft(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Dt(e)}(r):$t(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStream.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),Ze(e,"First parameter"),nt(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!ct(e)&&e._backpressure?Dt(this):Ft(this),kt(this);else if("erroring"===t)Lt(this,e._storedError),kt(this);else if("closed"===t)Ft(this),kt(r=this),zt(r);else{const t=e._storedError;Lt(this,t),jt(this,t)}var r}get closed(){return bt(this)?this._closedPromise:f(Ot("closed"))}get desiredSize(){if(!bt(this))throw Ot("desiredSize");if(void 0===this._ownerWritableStream)throw Bt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Rt(t._writableStreamController)}(this)}get ready(){return bt(this)?this._readyPromise:f(Ot("ready"))}abort(e){return bt(this)?void 0===this._ownerWritableStream?f(Bt("abort")):function(e,t){return at(e._ownerWritableStream,t)}(this,e):f(Ot("abort"))}close(){if(!bt(this))return f(Ot("close"));const e=this._ownerWritableStream;return void 0===e?f(Bt("close")):ct(e)?f(new TypeError("Cannot close an already-closing stream")):ht(this)}releaseLock(){if(!bt(this))throw Ot("releaseLock");void 0!==this._ownerWritableStream&&pt(this)}write(e){return bt(this)?void 0===this._ownerWritableStream?f(Bt("write to")):yt(this,e):f(Ot("write"))}}function bt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function ht(e){return it(e._ownerWritableStream)}function _t(e,t){"pending"===e._closedPromiseState?At(e,t):function(e,t){jt(e,t)}(e,t)}function mt(e,t){"pending"===e._readyPromiseState?It(e,t):function(e,t){Lt(e,t)}(e,t)}function pt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");mt(e,r),_t(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function yt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Ct(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return f(Bt("write to"));const a=r._state;if("errored"===a)return f(r._storedError);if(ct(r)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(r._storedError);const i=function(e){return c(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{de(e,t,r)}catch(t){return void Ct(e,t)}const o=e._controlledWritableStream;if(!ct(o)&&"writable"===o._state){ft(o,Pt(e))}Tt(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const gt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!St(this))throw Wt("abortReason");return this._abortReason}get signal(){if(!St(this))throw Wt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!St(this))throw Wt("error");"writable"===this._controlledWritableStream._state&&qt(this,e)}[B](e){const t=this._abortAlgorithm(e);return wt(this),t}[k](){fe(this)}}function St(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function vt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,fe(t),t._abortReason=void 0,t._abortController=function(){if(et)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Pt(t);ft(e,s);h(d(r()),(()=>{t._started=!0,Tt(t)}),(r=>{t._started=!0,lt(e,r)}))}function wt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Rt(e){return e._strategyHWM-e._queueTotalSize}function Tt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void ut(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===gt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ce(e);const r=e._closeAlgorithm();wt(e),h(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&zt(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),lt(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);h(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ce(e),!ct(r)&&"writable"===t){const t=Pt(e);ft(r,t)}Tt(e)}),(t=>{"writable"===r._state&&wt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,lt(e,t)}(r,t)}))}(e,r)}function Ct(e,t){"writable"===e._controlledWritableStream._state&&qt(e,t)}function Pt(e){return Rt(e)<=0}function qt(e,t){const r=e._controlledWritableStream;wt(e),st(r,t)}function Et(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Wt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Ot(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Bt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function kt(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function jt(e,t){kt(e),At(e,t)}function At(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function zt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Dt(e){e._readyPromise=c(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Lt(e,t){Dt(e),It(e,t)}function Ft(e){Dt(e),$t(e)}function It(e,t){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function $t(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Mt="undefined"!=typeof DOMException?DOMException:void 0;const Qt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Mt)?Mt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function Yt(e,t,o,n,a,i){const l=H(e),s=tt(t);e._disturbed=!0;let u=!1,p=d(void 0);return c(((g,S)=>{let v;if(void 0!==i){if(v=()=>{const r=new Qt("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===t._state?at(t,r):d(void 0))),a||o.push((()=>"readable"===e._state?br(e,r):d(void 0))),E((()=>Promise.all(o.map((e=>e())))),!0,r)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(q(e,l._closedPromise,(e=>{n?W(!0,e):E((()=>at(t,e)),!0,e)})),q(t,s._closedPromise,(t=>{a?W(!0,t):E((()=>br(e,t)),!0,t)})),w=e,R=l._closedPromise,T=()=>{o?W():E((()=>function(e){const t=e._ownerWritableStream,r=t._state;return ct(t)||"closed"===r?d(void 0):"errored"===r?f(t._storedError):ht(e)}(s)))},"closed"===w._state?T():_(R,T),ct(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,t):E((()=>br(e,t)),!0,t)}function P(){const e=p;return b(p,(()=>e!==p?P():void 0))}function q(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function E(e,r,o){function n(){h(e(),(()=>O(r,o)),(e=>O(!0,e)))}u||(u=!0,"writable"!==t._state||ct(t)?n():_(P(),n))}function W(e,r){u||(u=!0,"writable"!==t._state||ct(t)?O(e,r):_(P(),(()=>O(e,r))))}function O(e,t){pt(s),C(l),void 0!==i&&i.removeEventListener("abort",v),e?S(t):g(void 0)}y(c(((e,t)=>{!function o(n){n?e():b(u?d(!0):b(s._readyPromise,(()=>c(((e,t)=>{K(l,{_chunkSteps:t=>{p=b(yt(s,t),void 0,r),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),o,t)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!xt(this))throw er("desiredSize");return Jt(this)}close(){if(!xt(this))throw er("close");if(!Kt(this))throw new TypeError("The stream is not in a state that permits close");Ut(this)}enqueue(e){if(!xt(this))throw er("enqueue");if(!Kt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Gt(this,e)}error(e){if(!xt(this))throw er("error");Xt(this,e)}[j](e){fe(this);const t=this._cancelAlgorithm(e);return Vt(this),t}[A](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ce(this);this._closeRequested&&0===this._queue.length?(Vt(this),hr(t)):Nt(this),e._chunkSteps(r)}else V(t,e),Nt(this)}}function xt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function Nt(e){if(!Ht(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Nt(e))}),(t=>{Xt(e,t)}))}function Ht(e){const t=e._controlledReadableStream;if(!Kt(e))return!1;if(!e._started)return!1;if(fr(t)&&G(t)>0)return!0;return Jt(e)>0}function Vt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ut(e){if(!Kt(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Vt(e),hr(t))}function Gt(e,t){if(!Kt(e))return;const r=e._controlledReadableStream;if(fr(r)&&G(r)>0)U(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Xt(e,t),t}try{de(e,t,r)}catch(t){throw Xt(e,t),t}}Nt(e)}function Xt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(fe(e),Vt(e),_r(r,t))}function Jt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Kt(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Zt(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,fe(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;h(d(r()),(()=>{t._started=!0,Nt(t)}),(e=>{Xt(t,e)}))}function er(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function tr(e,t){return be(e._readableStreamController)?function(e){let t,r,o,n,a,i=H(e),l=!1,s=!1,u=!1,f=!1,b=!1;const h=c((e=>{a=e}));function _(e){m(e._closedPromise,(t=>{e===i&&(Oe(o._readableStreamController,t),Oe(n._readableStreamController,t),f&&b||a(void 0))}))}function p(){Qe(i)&&(C(i),i=H(e),_(i));K(i,{_chunkSteps:t=>{g((()=>{s=!1,u=!1;const r=t;let i=t;if(!f&&!b)try{i=ue(t)}catch(t){return Oe(o._readableStreamController,t),Oe(n._readableStreamController,t),void a(br(e,t))}f||We(o._readableStreamController,r),b||We(n._readableStreamController,i),l=!1,s?S():u&&v()}))},_closeSteps:()=>{l=!1,f||Ee(o._readableStreamController),b||Ee(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&je(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&je(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function y(t,r){J(i)&&(C(i),i=Fe(e),_(i));const c=r?n:o,d=r?o:n;Ye(i,t,{_chunkSteps:t=>{g((()=>{s=!1,u=!1;const o=r?b:f;if(r?f:b)o||Ae(c._readableStreamController,t);else{let r;try{r=ue(t)}catch(t){return Oe(c._readableStreamController,t),Oe(d._readableStreamController,t),void a(br(e,t))}o||Ae(c._readableStreamController,t),We(d._readableStreamController,r)}l=!1,s?S():u&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||Ee(c._readableStreamController),o||Ee(d._readableStreamController),void 0!==e&&(t||Ae(c._readableStreamController,e),!o&&d._readableStreamController._pendingPullIntos.length>0&&je(d._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function S(){if(l)return s=!0,d(void 0);l=!0;const e=Be(o._readableStreamController);return null===e?p():y(e._view,!1),d(void 0)}function v(){if(l)return u=!0,d(void 0);l=!0;const e=Be(n._readableStreamController);return null===e?p():y(e._view,!0),d(void 0)}function w(o){if(f=!0,t=o,b){const o=ie([t,r]),n=br(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=ie([t,r]),n=br(e,o);a(n)}return h}function T(){}return o=ur(T,S,w),n=ur(T,v,R),_(i),[o,n]}(e):function(e,t){const r=H(e);let o,n,a,i,l,s=!1,u=!1,f=!1,b=!1;const h=c((e=>{l=e}));function _(){if(s)return u=!0,d(void 0);s=!0;return K(r,{_chunkSteps:e=>{g((()=>{u=!1;const t=e,r=e;f||Gt(a._readableStreamController,t),b||Gt(i._readableStreamController,r),s=!1,u&&_()}))},_closeSteps:()=>{s=!1,f||Ut(a._readableStreamController),b||Ut(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{s=!1}}),d(void 0)}function p(t){if(f=!0,o=t,b){const t=ie([o,n]),r=br(e,t);l(r)}return h}function y(t){if(b=!0,n=t,f){const t=ie([o,n]),r=br(e,t);l(r)}return h}function S(){}return a=sr(S,_,p),i=sr(S,_,y),m(r._closedPromise,(e=>{Xt(a._readableStreamController,e),Xt(i._readableStreamController,e),f&&b||l(void 0)})),[a,i]}(e)}function rr(e,t,r){return F(e,r),r=>v(e,t,[r])}function or(e,t,r){return F(e,r),r=>v(e,t,[r])}function nr(e,t,r){return F(e,r),r=>S(e,t,[r])}function ar(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function ir(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function lr(e,t){L(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:I(e,"First parameter");const r=Ve(t,"Second parameter"),o=function(e,t){L(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:rr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:or(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:nr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:ar(l,`${t} has member 'type' that`)}}(e,"First parameter");if(cr(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n=()=>{},a=()=>d(void 0),i=()=>d(void 0);void 0!==t.start&&(n=()=>t.start(o)),void 0!==t.pull&&(a=()=>t.pull(o)),void 0!==t.cancel&&(i=e=>t.cancel(e));const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");ze(e,o,n,a,i,r,l)}(this,o,Ne(r,0))}else{const e=He(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a=()=>{},i=()=>d(void 0),l=()=>d(void 0);void 0!==t.start&&(a=()=>t.start(n)),void 0!==t.pull&&(i=()=>t.pull(n)),void 0!==t.cancel&&(l=e=>t.cancel(e)),Zt(e,n,a,i,l,r,o)}(this,o,Ne(r,1),e)}}get locked(){if(!dr(this))throw mr("locked");return fr(this)}cancel(e){return dr(this)?fr(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):br(this,e):f(mr("cancel"))}getReader(e){if(!dr(this))throw mr("getReader");return void 0===function(e,t){L(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:ir(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?H(this):Fe(this)}pipeThrough(e,t={}){if(!dr(this))throw mr("pipeThrough");$(e,1,"pipeThrough");const r=function(e,t){L(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),N(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),Ze(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=lr(t,"Second parameter");if(fr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(nt(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(Yt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!dr(this))return f(mr("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!ot(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=lr(t,"Second parameter")}catch(e){return f(e)}return fr(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):nt(e)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Yt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!dr(this))throw mr("tee");return ie(tr(this))}values(e){if(!dr(this))throw mr("values");return function(e,t){const r=H(e),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){L(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function sr(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);cr(a);return Zt(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function ur(e,t,r){const o=Object.create(ReadableStream.prototype);cr(o);return ze(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function cr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function dr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function fr(e){return void 0!==e._reader}function br(e,t){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);hr(e);const o=e._reader;void 0!==o&&Qe(o)&&(o._readIntoRequests.forEach((e=>{e._closeSteps(void 0)})),o._readIntoRequests=new w);return p(e._readableStreamController[j](t),r)}function hr(e){e._state="closed";const t=e._reader;void 0!==t&&(O(t),J(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new w))}function _r(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(W(r,t),J(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new w):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new w))}function mr(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function pr(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Q(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStream.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(ReadableStream.prototype,t.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const yr=e=>e.byteLength;try{Object.defineProperty(yr,"name",{value:"size",configurable:!0})}catch(e){}class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=pr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Sr(this))throw gr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Sr(this))throw gr("size");return yr}}function gr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Sr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const vr=()=>1;try{Object.defineProperty(vr,"name",{value:"size",configurable:!0})}catch(e){}class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=pr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Rr(this))throw wr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Rr(this))throw wr("size");return vr}}function wr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Rr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Tr(e,t,r){return F(e,r),r=>v(e,t,[r])}function Cr(e,t,r){return F(e,r),r=>S(e,t,[r])}function Pr(e,t,r){return F(e,r),(r,o)=>v(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ve(t,"Second parameter"),n=Ve(r,"Third parameter"),a=function(e,t){L(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:Tr(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:Cr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:Pr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=Ne(n,0),l=He(n),s=Ne(o,1),u=He(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return Ar(r,t)}))}return Ar(r,t)}(e,t)}function s(t){return function(e,t){return Er(e,t),d(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,o=r._flushAlgorithm();return kr(r),p(o,(()=>{if("errored"===t._state)throw t._storedError;Ut(t._readableStreamController)}),(r=>{throw Er(e,r),t._storedError}))}(e)}function c(){return function(e){return Or(e,!1),e._backpressureChangePromise}(e)}function f(t){return Wr(e,t),d(void 0)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return rt(i),vt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,u,s,r,o),e._readable=sr(i,c,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Or(e,!0),e._transformStreamController=void 0}(this,c((e=>{b=e})),s,u,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o=e=>{try{return jr(r,e),d(void 0)}catch(e){return f(e)}},n=()=>d(void 0);void 0!==t.transform&&(o=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!qr(this))throw Dr("readable");return this._readable}get writable(){if(!qr(this))throw Dr("writable");return this._writable}}function qr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function Er(e,t){Xt(e._readable._readableStreamController,t),Wr(e,t)}function Wr(e,t){kr(e._transformStreamController),Ct(e._writable._writableStreamController,t),e._backpressure&&Or(e,!1)}function Or(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStream.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Br(this))throw zr("desiredSize");return Jt(this._controlledTransformStream._readable._readableStreamController)}enqueue(e){if(!Br(this))throw zr("enqueue");jr(this,e)}error(e){if(!Br(this))throw zr("error");var t;t=e,Er(this._controlledTransformStream,t)}terminate(){if(!Br(this))throw zr("terminate");!function(e){const t=e._controlledTransformStream;Ut(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Wr(t,r)}(this)}}function Br(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function kr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function jr(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!Kt(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{Gt(o,t)}catch(e){throw Wr(r,e),r._readable._storedError}(function(e){return!Ht(e)})(o)!==r._backpressure&&Or(r,!0)}function Ar(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw Er(e._controlledTransformStream,t),t}))}function zr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Dr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const Lr={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==o)for(const e in Lr)Object.prototype.hasOwnProperty.call(Lr,e)&&Object.defineProperty(o,e,{value:Lr[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter,Object.defineProperty(e,"__esModule",{value:!0})}));
2 +//# sourceMappingURL=polyfill.es2018.min.js.map
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
1 +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}const o="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function n(e){return"object"==typeof e&&null!==e||"function"==typeof e}const a=r,i=Promise,l=Promise.prototype.then,s=Promise.resolve.bind(i),u=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return s(e)}function f(e){return u(e)}function b(e,t,r){return l.call(e,t,r)}function h(e,t,r){b(b(e,t,r),void 0,a)}function _(e,t){h(e,t)}function m(e,t){h(e,void 0,t)}function p(e,t,r){return b(e,t,r)}function y(e){b(e,void 0,a)}const S=(()=>{const e=o&&o.queueMicrotask;if("function"==typeof e)return e;const t=d(void 0);return e=>b(t,e)})();function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function v(e,t,r){try{return d(g(e,t,r))}catch(e){return f(e)}}class w{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function R(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?q(e):"closed"===t._state?function(e){q(e),O(e)}(e):E(e,t._storedError)}function T(e,t){return br(e._ownerReadableStream,t)}function C(e){"readable"===e._ownerReadableStream._state?W(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){E(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function P(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function q(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function E(e,t){q(e),W(e,t)}function W(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function O(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const B=t("[[AbortSteps]]"),k=t("[[ErrorSteps]]"),j=t("[[CancelSteps]]"),A=t("[[PullSteps]]"),z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function I(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function L(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function F(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Q(e){return Number(e)}function Y(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Y(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Y(D(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function N(e,t){if(!dr(e))throw new TypeError(`${t} is not a ReadableStream.`)}function H(e){return new ReadableStreamDefaultReader(e)}function V(e,t){e._reader._readRequests.push(t)}function U(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function G(e){return e._reader._readRequests.length}function X(e){const t=e._reader;return void 0!==t&&!!J(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),N(e,"First parameter"),fr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");R(this,e),this._readRequests=new w}get closed(){return J(this)?this._closedPromise:f(Z("closed"))}cancel(e){return J(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(Z("cancel"))}read(){if(!J(this))return f(Z("read"));if(void 0===this._ownerReadableStream)return f(P("read from"));let e,t;const r=c(((r,o)=>{e=r,t=o}));return K(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!J(this))throw Z("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}}}function J(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function K(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[A](t)}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}let ee;Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof t.asyncIterator&&(ee={[t.asyncIterator](){return this}},Object.defineProperty(ee,t.asyncIterator,{enumerable:!1}));class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return f(P("iterate"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return K(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,S((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return f(P("finish iterating"));if(!this._preventCancel){const r=T(t,e);return C(t),p(r,(()=>({value:e,done:!0})))}return C(t),d({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():f(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):f(ne("return"))}};function oe(e){if(!n(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==ee&&Object.setPrototypeOf(re,ee);const ae=Number.isNaN||function(e){return e!=e};function ie(e){return e.slice()}function le(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function se(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return le(n,0,e,t,o),n}function ue(e){const t=se(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ce(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function de(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function fe(e){e._queue=new w,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!he(this))throw De("view");return this._view}respond(e){if(!he(this))throw De("respond");if($(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,je(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!he(this))throw De("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,Ae(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!be(this))throw Ie("byobRequest");return Be(this)}get desiredSize(){if(!be(this))throw Ie("desiredSize");return ke(this)}close(){if(!be(this))throw Ie("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Ee(this)}enqueue(e){if(!be(this))throw Ie("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);We(this,e)}error(e){if(!be(this))throw Ie("error");Oe(this,e)}[j](e){me(this),fe(this);const t=this._cancelAlgorithm(e);return qe(this),t}[A](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,we(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}V(t,e),_e(this)}}function be(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function he(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function _e(e){if(!function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(X(t)&&G(t)>0)return!0;if(Me(t)&&$e(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,_e(e))}),(t=>{Oe(e,t)}))}function me(e){Re(e),e._pendingPullIntos=new w}function pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=ye(t);"default"===t.readerType?U(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function ye(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Se(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ge(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;le(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,ve(e,o,t),l-=o}return s}function ve(e,t,r){r.bytesFilled+=t}function we(e){0===e._queueTotalSize&&e._closeRequested?(qe(e),hr(e._controlledReadableByteStream)):_e(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();ge(e,t)&&(Pe(e),pe(e._controlledReadableByteStream,t))}}function Ce(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){const r=e._controlledReadableByteStream;if(Me(r))for(;$e(r)>0;)pe(r,Pe(e))}(e):function(e,t,r){if(ve(0,t,r),r.bytesFilled<r.elementSize)return;Pe(e);const o=r.bytesFilled%r.elementSize;if(o>0){const t=r.byteOffset+r.bytesFilled,n=se(r.buffer,t-o,t);Se(e,n,0,n.byteLength)}r.bytesFilled-=o,pe(e._controlledReadableByteStream,r),Te(e)}(e,t,r),_e(e)}function Pe(e){return e._pendingPullIntos.shift()}function qe(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ee(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Oe(e,t),t}}qe(e),hr(t)}}function We(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,t.buffer=t.buffer}if(Re(e),X(r))if(0===G(r))Se(e,i,n,a);else{e._pendingPullIntos.length>0&&Pe(e);U(r,new Uint8Array(i,n,a),!1)}else Me(r)?(Se(e,i,n,a),Te(e)):Se(e,i,n,a);_e(e)}function Oe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(me(e),fe(e),qe(e),_r(r,t))}function Be(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function je(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,Ce(e,t)}function Ae(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,Ce(e,o)}function ze(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,fe(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new w,e._readableStreamController=t;h(d(r()),(()=>{t._started=!0,_e(t)}),(e=>{Oe(t,e)}))}function De(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ie(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Le(e){return new ReadableStreamBYOBReader(e)}function Fe(e,t){e._reader._readIntoRequests.push(t)}function $e(e){return e._reader._readIntoRequests.length}function Me(e){const t=e._reader;return void 0!==t&&!!Qe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),N(e,"First parameter"),fr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!be(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");R(this,e),this._readIntoRequests=new w}get closed(){return Qe(this)?this._closedPromise:f(xe("closed"))}cancel(e){return Qe(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(xe("cancel"))}read(e){if(!Qe(this))return f(xe("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(P("read from"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return Ye(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Qe(this))throw xe("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}}}function Qe(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ye(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void Fe(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(ge(e,l)){const t=ye(l);return we(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Oe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),Fe(o,r),_e(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}function xe(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Ne(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function He(e){const{size:t}=e;return t||(()=>1)}function Ve(e,t){I(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Q(r),size:void 0===o?void 0:Ue(o,`${t} has member 'size' that`)}}function Ue(e,t){return L(e,t),t=>Q(e(t))}function Ge(e,t,r){return L(e,r),r=>v(e,t,[r])}function Xe(e,t,r){return L(e,r),()=>v(e,t,[])}function Je(e,t,r){return L(e,r),r=>g(e,t,[r])}function Ke(e,t,r){return L(e,r),(r,o)=>v(e,t,[r,o])}function Ze(e,t){if(!ot(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const et="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=Ve(t,"Second parameter"),o=function(e,t){I(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ge(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:Xe(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:Je(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ke(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");rt(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=He(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a=()=>{},i=()=>d(void 0),l=()=>d(void 0),s=()=>d(void 0);void 0!==t.start&&(a=()=>t.start(n));void 0!==t.write&&(i=e=>t.write(e,n));void 0!==t.close&&(l=()=>t.close());void 0!==t.abort&&(s=e=>t.abort(e));vt(e,n,a,i,l,s,r,o)}(this,o,Ne(r,1),n)}get locked(){if(!ot(this))throw Et("locked");return nt(this)}abort(e){return ot(this)?nt(this)?f(new TypeError("Cannot abort a stream that already has a writer")):at(this,e):f(Et("abort"))}close(){return ot(this)?nt(this)?f(new TypeError("Cannot close a stream that already has a writer")):ct(this)?f(new TypeError("Cannot close an already-closing stream")):it(this):f(Et("close"))}getWriter(){if(!ot(this))throw Et("getWriter");return tt(this)}}function tt(e){return new WritableStreamDefaultWriter(e)}function rt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new w,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function ot(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function nt(e){return void 0!==e._writer}function at(e,t){var r;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort();const o=e._state;if("closed"===o||"errored"===o)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=c(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||st(e,t),a}function it(e){const t=e._state;if("closed"===t||"errored"===t)return f(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=c(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&$t(o),de(n=e._writableStreamController,St,0),Tt(n),r}function lt(e,t){"writable"!==e._state?ut(e):st(e,t)}function st(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&mt(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&ut(e)}function ut(e){e._state="errored",e._writableStreamController[k]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new w,void 0===e._pendingAbortRequest)return void dt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void dt(e);h(e._writableStreamController[B](r._reason),(()=>{r._resolve(),dt(e)}),(t=>{r._reject(t),dt(e)}))}function ct(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function dt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&At(t,e._storedError)}function ft(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Dt(e)}(r):$t(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStream.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),Ze(e,"First parameter"),nt(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!ct(e)&&e._backpressure?Dt(this):Lt(this),kt(this);else if("erroring"===t)It(this,e._storedError),kt(this);else if("closed"===t)Lt(this),kt(r=this),zt(r);else{const t=e._storedError;It(this,t),jt(this,t)}var r}get closed(){return bt(this)?this._closedPromise:f(Ot("closed"))}get desiredSize(){if(!bt(this))throw Ot("desiredSize");if(void 0===this._ownerWritableStream)throw Bt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Rt(t._writableStreamController)}(this)}get ready(){return bt(this)?this._readyPromise:f(Ot("ready"))}abort(e){return bt(this)?void 0===this._ownerWritableStream?f(Bt("abort")):function(e,t){return at(e._ownerWritableStream,t)}(this,e):f(Ot("abort"))}close(){if(!bt(this))return f(Ot("close"));const e=this._ownerWritableStream;return void 0===e?f(Bt("close")):ct(e)?f(new TypeError("Cannot close an already-closing stream")):ht(this)}releaseLock(){if(!bt(this))throw Ot("releaseLock");void 0!==this._ownerWritableStream&&pt(this)}write(e){return bt(this)?void 0===this._ownerWritableStream?f(Bt("write to")):yt(this,e):f(Ot("write"))}}function bt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function ht(e){return it(e._ownerWritableStream)}function _t(e,t){"pending"===e._closedPromiseState?At(e,t):function(e,t){jt(e,t)}(e,t)}function mt(e,t){"pending"===e._readyPromiseState?Ft(e,t):function(e,t){It(e,t)}(e,t)}function pt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");mt(e,r),_t(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function yt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Ct(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return f(Bt("write to"));const a=r._state;if("errored"===a)return f(r._storedError);if(ct(r)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(r._storedError);const i=function(e){return c(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{de(e,t,r)}catch(t){return void Ct(e,t)}const o=e._controlledWritableStream;if(!ct(o)&&"writable"===o._state){ft(o,Pt(e))}Tt(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const St={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!gt(this))throw Wt("abortReason");return this._abortReason}get signal(){if(!gt(this))throw Wt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!gt(this))throw Wt("error");"writable"===this._controlledWritableStream._state&&qt(this,e)}[B](e){const t=this._abortAlgorithm(e);return wt(this),t}[k](){fe(this)}}function gt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function vt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,fe(t),t._abortReason=void 0,t._abortController=function(){if(et)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Pt(t);ft(e,s);h(d(r()),(()=>{t._started=!0,Tt(t)}),(r=>{t._started=!0,lt(e,r)}))}function wt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Rt(e){return e._strategyHWM-e._queueTotalSize}function Tt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void ut(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===St?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ce(e);const r=e._closeAlgorithm();wt(e),h(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&zt(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),lt(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);h(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ce(e),!ct(r)&&"writable"===t){const t=Pt(e);ft(r,t)}Tt(e)}),(t=>{"writable"===r._state&&wt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,lt(e,t)}(r,t)}))}(e,r)}function Ct(e,t){"writable"===e._controlledWritableStream._state&&qt(e,t)}function Pt(e){return Rt(e)<=0}function qt(e,t){const r=e._controlledWritableStream;wt(e),st(r,t)}function Et(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Wt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Ot(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Bt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function kt(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function jt(e,t){kt(e),At(e,t)}function At(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function zt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Dt(e){e._readyPromise=c(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function It(e,t){Dt(e),Ft(e,t)}function Lt(e){Dt(e),$t(e)}function Ft(e,t){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function $t(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Mt="undefined"!=typeof DOMException?DOMException:void 0;const Qt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Mt)?Mt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function Yt(e,t,o,n,a,i){const l=H(e),s=tt(t);e._disturbed=!0;let u=!1,p=d(void 0);return c(((S,g)=>{let v;if(void 0!==i){if(v=()=>{const r=new Qt("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===t._state?at(t,r):d(void 0))),a||o.push((()=>"readable"===e._state?br(e,r):d(void 0))),E((()=>Promise.all(o.map((e=>e())))),!0,r)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(q(e,l._closedPromise,(e=>{n?W(!0,e):E((()=>at(t,e)),!0,e)})),q(t,s._closedPromise,(t=>{a?W(!0,t):E((()=>br(e,t)),!0,t)})),w=e,R=l._closedPromise,T=()=>{o?W():E((()=>function(e){const t=e._ownerWritableStream,r=t._state;return ct(t)||"closed"===r?d(void 0):"errored"===r?f(t._storedError):ht(e)}(s)))},"closed"===w._state?T():_(R,T),ct(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,t):E((()=>br(e,t)),!0,t)}function P(){const e=p;return b(p,(()=>e!==p?P():void 0))}function q(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function E(e,r,o){function n(){h(e(),(()=>O(r,o)),(e=>O(!0,e)))}u||(u=!0,"writable"!==t._state||ct(t)?n():_(P(),n))}function W(e,r){u||(u=!0,"writable"!==t._state||ct(t)?O(e,r):_(P(),(()=>O(e,r))))}function O(e,t){pt(s),C(l),void 0!==i&&i.removeEventListener("abort",v),e?g(t):S(void 0)}y(c(((e,t)=>{!function o(n){n?e():b(u?d(!0):b(s._readyPromise,(()=>c(((e,t)=>{K(l,{_chunkSteps:t=>{p=b(yt(s,t),void 0,r),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),o,t)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!xt(this))throw er("desiredSize");return Jt(this)}close(){if(!xt(this))throw er("close");if(!Kt(this))throw new TypeError("The stream is not in a state that permits close");Ut(this)}enqueue(e){if(!xt(this))throw er("enqueue");if(!Kt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Gt(this,e)}error(e){if(!xt(this))throw er("error");Xt(this,e)}[j](e){fe(this);const t=this._cancelAlgorithm(e);return Vt(this),t}[A](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ce(this);this._closeRequested&&0===this._queue.length?(Vt(this),hr(t)):Nt(this),e._chunkSteps(r)}else V(t,e),Nt(this)}}function xt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function Nt(e){if(!Ht(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Nt(e))}),(t=>{Xt(e,t)}))}function Ht(e){const t=e._controlledReadableStream;if(!Kt(e))return!1;if(!e._started)return!1;if(fr(t)&&G(t)>0)return!0;return Jt(e)>0}function Vt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ut(e){if(!Kt(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Vt(e),hr(t))}function Gt(e,t){if(!Kt(e))return;const r=e._controlledReadableStream;if(fr(r)&&G(r)>0)U(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Xt(e,t),t}try{de(e,t,r)}catch(t){throw Xt(e,t),t}}Nt(e)}function Xt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(fe(e),Vt(e),_r(r,t))}function Jt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Kt(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Zt(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,fe(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;h(d(r()),(()=>{t._started=!0,Nt(t)}),(e=>{Xt(t,e)}))}function er(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function tr(e,t){return be(e._readableStreamController)?function(e){let t,r,o,n,a,i=H(e),l=!1,s=!1,u=!1,f=!1,b=!1;const h=c((e=>{a=e}));function _(e){m(e._closedPromise,(t=>{e===i&&(Oe(o._readableStreamController,t),Oe(n._readableStreamController,t),f&&b||a(void 0))}))}function p(){Qe(i)&&(C(i),i=H(e),_(i));K(i,{_chunkSteps:t=>{S((()=>{s=!1,u=!1;const r=t;let i=t;if(!f&&!b)try{i=ue(t)}catch(t){return Oe(o._readableStreamController,t),Oe(n._readableStreamController,t),void a(br(e,t))}f||We(o._readableStreamController,r),b||We(n._readableStreamController,i),l=!1,s?g():u&&v()}))},_closeSteps:()=>{l=!1,f||Ee(o._readableStreamController),b||Ee(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&je(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&je(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function y(t,r){J(i)&&(C(i),i=Le(e),_(i));const c=r?n:o,d=r?o:n;Ye(i,t,{_chunkSteps:t=>{S((()=>{s=!1,u=!1;const o=r?b:f;if(r?f:b)o||Ae(c._readableStreamController,t);else{let r;try{r=ue(t)}catch(t){return Oe(c._readableStreamController,t),Oe(d._readableStreamController,t),void a(br(e,t))}o||Ae(c._readableStreamController,t),We(d._readableStreamController,r)}l=!1,s?g():u&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||Ee(c._readableStreamController),o||Ee(d._readableStreamController),void 0!==e&&(t||Ae(c._readableStreamController,e),!o&&d._readableStreamController._pendingPullIntos.length>0&&je(d._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function g(){if(l)return s=!0,d(void 0);l=!0;const e=Be(o._readableStreamController);return null===e?p():y(e._view,!1),d(void 0)}function v(){if(l)return u=!0,d(void 0);l=!0;const e=Be(n._readableStreamController);return null===e?p():y(e._view,!0),d(void 0)}function w(o){if(f=!0,t=o,b){const o=ie([t,r]),n=br(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=ie([t,r]),n=br(e,o);a(n)}return h}function T(){}return o=ur(T,g,w),n=ur(T,v,R),_(i),[o,n]}(e):function(e,t){const r=H(e);let o,n,a,i,l,s=!1,u=!1,f=!1,b=!1;const h=c((e=>{l=e}));function _(){if(s)return u=!0,d(void 0);s=!0;return K(r,{_chunkSteps:e=>{S((()=>{u=!1;const t=e,r=e;f||Gt(a._readableStreamController,t),b||Gt(i._readableStreamController,r),s=!1,u&&_()}))},_closeSteps:()=>{s=!1,f||Ut(a._readableStreamController),b||Ut(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{s=!1}}),d(void 0)}function p(t){if(f=!0,o=t,b){const t=ie([o,n]),r=br(e,t);l(r)}return h}function y(t){if(b=!0,n=t,f){const t=ie([o,n]),r=br(e,t);l(r)}return h}function g(){}return a=sr(g,_,p),i=sr(g,_,y),m(r._closedPromise,(e=>{Xt(a._readableStreamController,e),Xt(i._readableStreamController,e),f&&b||l(void 0)})),[a,i]}(e)}function rr(e,t,r){return L(e,r),r=>v(e,t,[r])}function or(e,t,r){return L(e,r),r=>v(e,t,[r])}function nr(e,t,r){return L(e,r),r=>g(e,t,[r])}function ar(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function ir(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function lr(e,t){I(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=Ve(t,"Second parameter"),o=function(e,t){I(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:rr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:or(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:nr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:ar(l,`${t} has member 'type' that`)}}(e,"First parameter");if(cr(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n=()=>{},a=()=>d(void 0),i=()=>d(void 0);void 0!==t.start&&(n=()=>t.start(o)),void 0!==t.pull&&(a=()=>t.pull(o)),void 0!==t.cancel&&(i=e=>t.cancel(e));const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");ze(e,o,n,a,i,r,l)}(this,o,Ne(r,0))}else{const e=He(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a=()=>{},i=()=>d(void 0),l=()=>d(void 0);void 0!==t.start&&(a=()=>t.start(n)),void 0!==t.pull&&(i=()=>t.pull(n)),void 0!==t.cancel&&(l=e=>t.cancel(e)),Zt(e,n,a,i,l,r,o)}(this,o,Ne(r,1),e)}}get locked(){if(!dr(this))throw mr("locked");return fr(this)}cancel(e){return dr(this)?fr(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):br(this,e):f(mr("cancel"))}getReader(e){if(!dr(this))throw mr("getReader");return void 0===function(e,t){I(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:ir(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?H(this):Le(this)}pipeThrough(e,t={}){if(!dr(this))throw mr("pipeThrough");$(e,1,"pipeThrough");const r=function(e,t){I(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),N(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),Ze(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=lr(t,"Second parameter");if(fr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(nt(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(Yt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!dr(this))return f(mr("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!ot(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=lr(t,"Second parameter")}catch(e){return f(e)}return fr(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):nt(e)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Yt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!dr(this))throw mr("tee");return ie(tr(this))}values(e){if(!dr(this))throw mr("values");return function(e,t){const r=H(e),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){I(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function sr(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);cr(a);return Zt(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function ur(e,t,r){const o=Object.create(ReadableStream.prototype);cr(o);return ze(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function cr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function dr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function fr(e){return void 0!==e._reader}function br(e,t){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);hr(e);const o=e._reader;void 0!==o&&Qe(o)&&(o._readIntoRequests.forEach((e=>{e._closeSteps(void 0)})),o._readIntoRequests=new w);return p(e._readableStreamController[j](t),r)}function hr(e){e._state="closed";const t=e._reader;void 0!==t&&(O(t),J(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new w))}function _r(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(W(r,t),J(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new w):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new w))}function mr(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function pr(e,t){I(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Q(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStream.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(ReadableStream.prototype,t.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const yr=e=>e.byteLength;try{Object.defineProperty(yr,"name",{value:"size",configurable:!0})}catch(e){}class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=pr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!gr(this))throw Sr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!gr(this))throw Sr("size");return yr}}function Sr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function gr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const vr=()=>1;try{Object.defineProperty(vr,"name",{value:"size",configurable:!0})}catch(e){}class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=pr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Rr(this))throw wr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Rr(this))throw wr("size");return vr}}function wr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Rr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Tr(e,t,r){return L(e,r),r=>v(e,t,[r])}function Cr(e,t,r){return L(e,r),r=>g(e,t,[r])}function Pr(e,t,r){return L(e,r),(r,o)=>v(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ve(t,"Second parameter"),n=Ve(r,"Third parameter"),a=function(e,t){I(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:Tr(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:Cr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:Pr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=Ne(n,0),l=He(n),s=Ne(o,1),u=He(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return Ar(r,t)}))}return Ar(r,t)}(e,t)}function s(t){return function(e,t){return Er(e,t),d(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,o=r._flushAlgorithm();return kr(r),p(o,(()=>{if("errored"===t._state)throw t._storedError;Ut(t._readableStreamController)}),(r=>{throw Er(e,r),t._storedError}))}(e)}function c(){return function(e){return Or(e,!1),e._backpressureChangePromise}(e)}function f(t){return Wr(e,t),d(void 0)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return rt(i),vt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,u,s,r,o),e._readable=sr(i,c,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Or(e,!0),e._transformStreamController=void 0}(this,c((e=>{b=e})),s,u,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o=e=>{try{return jr(r,e),d(void 0)}catch(e){return f(e)}},n=()=>d(void 0);void 0!==t.transform&&(o=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!qr(this))throw Dr("readable");return this._readable}get writable(){if(!qr(this))throw Dr("writable");return this._writable}}function qr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function Er(e,t){Xt(e._readable._readableStreamController,t),Wr(e,t)}function Wr(e,t){kr(e._transformStreamController),Ct(e._writable._writableStreamController,t),e._backpressure&&Or(e,!1)}function Or(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStream.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Br(this))throw zr("desiredSize");return Jt(this._controlledTransformStream._readable._readableStreamController)}enqueue(e){if(!Br(this))throw zr("enqueue");jr(this,e)}error(e){if(!Br(this))throw zr("error");var t;t=e,Er(this._controlledTransformStream,t)}terminate(){if(!Br(this))throw zr("terminate");!function(e){const t=e._controlledTransformStream;Ut(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Wr(t,r)}(this)}}function Br(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function kr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function jr(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!Kt(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{Gt(o,t)}catch(e){throw Wr(r,e),r._readable._storedError}(function(e){return!Ht(e)})(o)!==r._backpressure&&Or(r,!0)}function Ar(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw Er(e._controlledTransformStream,t),t}))}function zr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Dr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const Ir={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==o)for(const e in Ir)Object.prototype.hasOwnProperty.call(Ir,e)&&Object.defineProperty(o,e,{value:Ir[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter,Object.defineProperty(e,"__esModule",{value:!0})}));
2 +//# sourceMappingURL=polyfill.es6.min.js.map
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
1 +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol("+e+")"};function t(){}var o="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function n(e){return"object"==typeof e&&null!==e||"function"==typeof e}var a=t,i=Promise,l=Promise.prototype.then,u=Promise.resolve.bind(i),s=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return u(e)}function f(e){return s(e)}function b(e,r,t){return l.call(e,r,t)}function p(e,r,t){b(b(e,r,t),void 0,a)}function _(e,r){p(e,r)}function h(e,r){p(e,void 0,r)}function m(e,r,t){return b(e,r,t)}function y(e){b(e,void 0,a)}var v=function(){var e=o&&o.queueMicrotask;if("function"==typeof e)return e;var r=d(void 0);return function(e){return b(r,e)}}();function g(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}function S(e,r,t){try{return d(g(e,r,t))}catch(e){return f(e)}}var w=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.push=function(e){var r=this._back,t=r;16383===r._elements.length&&(t={_elements:[],_next:void 0}),r._elements.push(e),t!==r&&(this._back=t,r._next=t),++this._size},e.prototype.shift=function(){var e=this._front,r=e,t=this._cursor,o=t+1,n=e._elements,a=n[t];return 16384===o&&(r=e._next,o=0),--this._size,this._cursor=o,e!==r&&(this._front=r),n[t]=void 0,a},e.prototype.forEach=function(e){for(var r=this._cursor,t=this._front,o=t._elements;!(r===o.length&&void 0===t._next||r===o.length&&(r=0,0===(o=(t=t._next)._elements).length));)e(o[r]),++r},e.prototype.peek=function(){var e=this._front,r=this._cursor;return e._elements[r]},e}();function R(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?q(e):"closed"===r._state?function(e){q(e),W(e)}(e):O(e,r._storedError)}function T(e,r){return Tt(e._ownerReadableStream,r)}function C(e){"readable"===e._ownerReadableStream._state?E(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,r){O(e,r)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function P(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function q(e){e._closedPromise=c((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t}))}function O(e,r){q(e),E(e,r)}function E(e,r){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function W(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var j=r("[[AbortSteps]]"),B=r("[[ErrorSteps]]"),k=r("[[CancelSteps]]"),A=r("[[PullSteps]]"),z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function I(e,r){if(void 0!==e&&("object"!=typeof(t=e)&&"function"!=typeof t))throw new TypeError(r+" is not an object.");var t}function F(e,r){if("function"!=typeof e)throw new TypeError(r+" is not a function.")}function L(e,r){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(r+" is not an object.")}function M(e,r,t){if(void 0===e)throw new TypeError("Parameter "+r+" is required in '"+t+"'.")}function Q(e,r,t){if(void 0===e)throw new TypeError(r+" is required in '"+t+"'.")}function Y(e){return Number(e)}function x(e){return 0===e?0:e}function N(e,r){var t=Number.MAX_SAFE_INTEGER,o=Number(e);if(o=x(o),!z(o))throw new TypeError(r+" is not a finite number");if((o=function(e){return x(D(e))}(o))<0||o>t)throw new TypeError(r+" is outside the accepted range of 0 to "+t+", inclusive");return z(o)&&0!==o?o:0}function H(e,r){if(!wt(e))throw new TypeError(r+" is not a ReadableStream.")}function V(e){return new $(e)}function U(e,r){e._reader._readRequests.push(r)}function G(e,r,t){var o=e._reader._readRequests.shift();t?o._closeSteps():o._chunkSteps(r)}function X(e){return e._reader._readRequests.length}function J(e){var r=e._reader;return void 0!==r&&!!ee(r)}var K,Z,$=function(){function ReadableStreamDefaultReader(e){if(M(e,1,"ReadableStreamDefaultReader"),H(e,"First parameter"),Rt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");R(this,e),this._readRequests=new w}return Object.defineProperty(ReadableStreamDefaultReader.prototype,"closed",{get:function(){return ee(this)?this._closedPromise:f(te("closed"))},enumerable:!1,configurable:!0}),ReadableStreamDefaultReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),ee(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(te("cancel"))},ReadableStreamDefaultReader.prototype.read=function(){if(!ee(this))return f(te("read"));if(void 0===this._ownerReadableStream)return f(P("read from"));var e,r,t=c((function(t,o){e=t,r=o}));return re(this,{_chunkSteps:function(r){return e({value:r,done:!1})},_closeSteps:function(){return e({value:void 0,done:!0})},_errorSteps:function(e){return r(e)}}),t},ReadableStreamDefaultReader.prototype.releaseLock=function(){if(!ee(this))throw te("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}},ReadableStreamDefaultReader}();function ee(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof $)}function re(e,r){var t=e._ownerReadableStream;t._disturbed=!0,"closed"===t._state?r._closeSteps():"errored"===t._state?r._errorSteps(t._storedError):t._readableStreamController[A](r)}function te(e){return new TypeError("ReadableStreamDefaultReader.prototype."+e+" can only be used on a ReadableStreamDefaultReader")}Object.defineProperties($.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty($.prototype,r.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof r.asyncIterator&&((K={})[r.asyncIterator]=function(){return this},Z=K,Object.defineProperty(Z,r.asyncIterator,{enumerable:!1}));var oe=function(){function e(e,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=r}return e.prototype.next=function(){var e=this,r=function(){return e._nextSteps()};return this._ongoingPromise=this._ongoingPromise?m(this._ongoingPromise,r,r):r(),this._ongoingPromise},e.prototype.return=function(e){var r=this,t=function(){return r._returnSteps(e)};return this._ongoingPromise?m(this._ongoingPromise,t,t):t()},e.prototype._nextSteps=function(){var e=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var r,t,o=this._reader;if(void 0===o._ownerReadableStream)return f(P("iterate"));var n=c((function(e,o){r=e,t=o}));return re(o,{_chunkSteps:function(t){e._ongoingPromise=void 0,v((function(){return r({value:t,done:!1})}))},_closeSteps:function(){e._ongoingPromise=void 0,e._isFinished=!0,C(o),r({value:void 0,done:!0})},_errorSteps:function(r){e._ongoingPromise=void 0,e._isFinished=!0,C(o),t(r)}}),n},e.prototype._returnSteps=function(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;var r=this._reader;if(void 0===r._ownerReadableStream)return f(P("finish iterating"));if(!this._preventCancel){var t=T(r,e);return C(r),m(t,(function(){return{value:e,done:!0}}))}return C(r),d({value:e,done:!0})},e}(),ne={next:function(){return ae(this)?this._asyncIteratorImpl.next():f(ie("next"))},return:function(e){return ae(this)?this._asyncIteratorImpl.return(e):f(ie("return"))}};function ae(e){if(!n(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof oe}catch(e){return!1}}function ie(e){return new TypeError("ReadableStreamAsyncIterator."+e+" can only be used on a ReadableSteamAsyncIterator")}void 0!==Z&&Object.setPrototypeOf(ne,Z);var le=Number.isNaN||function(e){return e!=e};function ue(e){return e.slice()}function se(e,r,t,o,n){new Uint8Array(e).set(new Uint8Array(t,o,n),r)}function ce(e,r,t){if(e.slice)return e.slice(r,t);var o=t-r,n=new ArrayBuffer(o);return se(n,0,e,r,o),n}function de(e){var r=ce(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(r)}function fe(e){var r=e._queue.shift();return e._queueTotalSize-=r.size,e._queueTotalSize<0&&(e._queueTotalSize=0),r.value}function be(e,r,t){if("number"!=typeof(o=t)||le(o)||o<0||t===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:r,size:t}),e._queueTotalSize+=t}function pe(e){e._queue=new w,e._queueTotalSize=0}var _e=function(){function ReadableStreamBYOBRequest(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamBYOBRequest.prototype,"view",{get:function(){if(!ye(this))throw Me("view");return this._view},enumerable:!1,configurable:!0}),ReadableStreamBYOBRequest.prototype.respond=function(e){if(!ye(this))throw Me("respond");if(M(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,Ie(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest.prototype.respondWithNewView=function(e){if(!ye(this))throw Me("respondWithNewView");if(M(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,Fe(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest}();Object.defineProperties(_e.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(_e.prototype,r.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var he=function(){function ReadableByteStreamController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableByteStreamController.prototype,"byobRequest",{get:function(){if(!me(this))throw Qe("byobRequest");return ze(this)},enumerable:!1,configurable:!0}),Object.defineProperty(ReadableByteStreamController.prototype,"desiredSize",{get:function(){if(!me(this))throw Qe("desiredSize");return De(this)},enumerable:!1,configurable:!0}),ReadableByteStreamController.prototype.close=function(){if(!me(this))throw Qe("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");Be(this)},ReadableByteStreamController.prototype.enqueue=function(e){if(!me(this))throw Qe("enqueue");if(M(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableByteStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");ke(this,e)},ReadableByteStreamController.prototype.error=function(e){if(void 0===e&&(e=void 0),!me(this))throw Qe("error");Ae(this,e)},ReadableByteStreamController.prototype[k]=function(e){ge(this),pe(this);var r=this._cancelAlgorithm(e);return je(this),r},ReadableByteStreamController.prototype[A]=function(e){var r=this._controlledReadableByteStream;if(this._queueTotalSize>0){var t=this._queue.shift();this._queueTotalSize-=t.byteLength,Pe(this);var o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);e._chunkSteps(o)}else{var n=this._autoAllocateChunkSize;if(void 0!==n){var a=void 0;try{a=new ArrayBuffer(n)}catch(r){return void e._errorSteps(r)}var i={buffer:a,bufferByteLength:n,byteOffset:0,byteLength:n,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(i)}U(r,e),ve(this)}},ReadableByteStreamController}();function me(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof he)}function ye(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof _e)}function ve(e){(function(e){var r=e._controlledReadableByteStream;if("readable"!==r._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(J(r)&&X(r)>0)return!0;if(He(r)&&Ne(r)>0)return!0;if(De(e)>0)return!0;return!1})(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,p(e._pullAlgorithm(),(function(){e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,ve(e))}),(function(r){Ae(e,r)}))))}function ge(e){qe(e),e._pendingPullIntos=new w}function Se(e,r){var t=!1;"closed"===e._state&&(t=!0);var o=we(r);"default"===r.readerType?G(e,o,t):function(e,r,t){var o=e._reader._readIntoRequests.shift();t?o._closeSteps(r):o._chunkSteps(r)}(e,o,t)}function we(e){var r=e.bytesFilled,t=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,r/t)}function Re(e,r,t,o){e._queue.push({buffer:r,byteOffset:t,byteLength:o}),e._queueTotalSize+=o}function Te(e,r){var t=r.elementSize,o=r.bytesFilled-r.bytesFilled%t,n=Math.min(e._queueTotalSize,r.byteLength-r.bytesFilled),a=r.bytesFilled+n,i=a-a%t,l=n,u=!1;i>o&&(l=i-r.bytesFilled,u=!0);for(var s=e._queue;l>0;){var c=s.peek(),d=Math.min(l,c.byteLength),f=r.byteOffset+r.bytesFilled;se(r.buffer,f,c.buffer,c.byteOffset,d),c.byteLength===d?s.shift():(c.byteOffset+=d,c.byteLength-=d),e._queueTotalSize-=d,Ce(e,d,r),l-=d}return u}function Ce(e,r,t){t.bytesFilled+=r}function Pe(e){0===e._queueTotalSize&&e._closeRequested?(je(e),Ct(e._controlledReadableByteStream)):ve(e)}function qe(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Oe(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var r=e._pendingPullIntos.peek();Te(e,r)&&(We(e),Se(e._controlledReadableByteStream,r))}}function Ee(e,r){var t=e._pendingPullIntos.peek();qe(e),"closed"===e._controlledReadableByteStream._state?function(e,r){var t=e._controlledReadableByteStream;if(He(t))for(;Ne(t)>0;)Se(t,We(e))}(e):function(e,r,t){if(Ce(0,r,t),!(t.bytesFilled<t.elementSize)){We(e);var o=t.bytesFilled%t.elementSize;if(o>0){var n=t.byteOffset+t.bytesFilled,a=ce(t.buffer,n-o,n);Re(e,a,0,a.byteLength)}t.bytesFilled-=o,Se(e._controlledReadableByteStream,t),Oe(e)}}(e,r,t),ve(e)}function We(e){return e._pendingPullIntos.shift()}function je(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Be(e){var r=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===r._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0)if(e._pendingPullIntos.peek().bytesFilled>0){var t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ae(e,t),t}je(e),Ct(r)}}function ke(e,r){var t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state){var o=r.buffer,n=r.byteOffset,a=r.byteLength,i=o;if(e._pendingPullIntos.length>0){var l=e._pendingPullIntos.peek();l.buffer,0,l.buffer=l.buffer}if(qe(e),J(t))if(0===X(t))Re(e,i,n,a);else e._pendingPullIntos.length>0&&We(e),G(t,new Uint8Array(i,n,a),!1);else He(t)?(Re(e,i,n,a),Oe(e)):Re(e,i,n,a);ve(e)}}function Ae(e,r){var t=e._controlledReadableByteStream;"readable"===t._state&&(ge(e),pe(e),je(e),Pt(t,r))}function ze(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){var r=e._pendingPullIntos.peek(),t=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),o=Object.create(_e.prototype);!function(e,r,t){e._associatedReadableByteStreamController=r,e._view=t}(o,e,t),e._byobRequest=o}return e._byobRequest}function De(e){var r=e._controlledReadableByteStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Ie(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===r)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range")}t.buffer=t.buffer,Ee(e,r)}function Fe(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===r.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.bufferByteLength!==r.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(t.bytesFilled+r.byteLength>t.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var o=r.byteLength;t.buffer=r.buffer,Ee(e,o)}function Le(e,r,t,o,n,a,i){r._controlledReadableByteStream=e,r._pullAgain=!1,r._pulling=!1,r._byobRequest=null,r._queue=r._queueTotalSize=void 0,pe(r),r._closeRequested=!1,r._started=!1,r._strategyHWM=a,r._pullAlgorithm=o,r._cancelAlgorithm=n,r._autoAllocateChunkSize=i,r._pendingPullIntos=new w,e._readableStreamController=r,p(d(t()),(function(){r._started=!0,ve(r)}),(function(e){Ae(r,e)}))}function Me(e){return new TypeError("ReadableStreamBYOBRequest.prototype."+e+" can only be used on a ReadableStreamBYOBRequest")}function Qe(e){return new TypeError("ReadableByteStreamController.prototype."+e+" can only be used on a ReadableByteStreamController")}function Ye(e){return new Ve(e)}function xe(e,r){e._reader._readIntoRequests.push(r)}function Ne(e){return e._reader._readIntoRequests.length}function He(e){var r=e._reader;return void 0!==r&&!!Ue(r)}Object.defineProperties(he.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(he.prototype,r.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var Ve=function(){function ReadableStreamBYOBReader(e){if(M(e,1,"ReadableStreamBYOBReader"),H(e,"First parameter"),Rt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!me(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");R(this,e),this._readIntoRequests=new w}return Object.defineProperty(ReadableStreamBYOBReader.prototype,"closed",{get:function(){return Ue(this)?this._closedPromise:f(Xe("closed"))},enumerable:!1,configurable:!0}),ReadableStreamBYOBReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),Ue(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(Xe("cancel"))},ReadableStreamBYOBReader.prototype.read=function(e){if(!Ue(this))return f(Xe("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(P("read from"));var r,t,o=c((function(e,o){r=e,t=o}));return Ge(this,e,{_chunkSteps:function(e){return r({value:e,done:!1})},_closeSteps:function(e){return r({value:e,done:!0})},_errorSteps:function(e){return t(e)}}),o},ReadableStreamBYOBReader.prototype.releaseLock=function(){if(!Ue(this))throw Xe("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}},ReadableStreamBYOBReader}();function Ue(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof Ve)}function Ge(e,r,t){var o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?t._errorSteps(o._storedError):function(e,r,t){var o=e._controlledReadableByteStream,n=1;r.constructor!==DataView&&(n=r.constructor.BYTES_PER_ELEMENT);var a=r.constructor,i=r.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:r.byteOffset,byteLength:r.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void xe(o,t);if("closed"!==o._state){if(e._queueTotalSize>0){if(Te(e,l)){var u=we(l);return Pe(e),void t._chunkSteps(u)}if(e._closeRequested){var s=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ae(e,s),void t._errorSteps(s)}}e._pendingPullIntos.push(l),xe(o,t),ve(e)}else{var c=new a(l.buffer,l.byteOffset,0);t._closeSteps(c)}}(o._readableStreamController,r,t)}function Xe(e){return new TypeError("ReadableStreamBYOBReader.prototype."+e+" can only be used on a ReadableStreamBYOBReader")}function Je(e,r){var t=e.highWaterMark;if(void 0===t)return r;if(le(t)||t<0)throw new RangeError("Invalid highWaterMark");return t}function Ke(e){var r=e.size;return r||function(){return 1}}function Ze(e,r){I(e,r);var t=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===t?void 0:Y(t),size:void 0===o?void 0:$e(o,r+" has member 'size' that")}}function $e(e,r){return F(e,r),function(r){return Y(e(r))}}function er(e,r,t){return F(e,t),function(t){return S(e,r,[t])}}function rr(e,r,t){return F(e,t),function(){return S(e,r,[])}}function tr(e,r,t){return F(e,t),function(t){return g(e,r,[t])}}function or(e,r,t){return F(e,t),function(t,o){return S(e,r,[t,o])}}function nr(e,r){if(!sr(e))throw new TypeError(r+" is not a WritableStream.")}Object.defineProperties(Ve.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Ve.prototype,r.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var ar="function"==typeof AbortController;var ir=function(){function WritableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:L(e,"First parameter");var t=Ze(r,"Second parameter"),o=function(e,r){I(e,r);var t=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===t?void 0:er(t,e,r+" has member 'abort' that"),close:void 0===o?void 0:rr(o,e,r+" has member 'close' that"),start:void 0===n?void 0:tr(n,e,r+" has member 'start' that"),write:void 0===i?void 0:or(i,e,r+" has member 'write' that"),type:a}}(e,"First parameter");if(ur(this),void 0!==o.type)throw new RangeError("Invalid type is specified");var n=Ke(t);!function(e,r,t,o){var n=Object.create(qr.prototype),a=function(){},i=function(){return d(void 0)},l=function(){return d(void 0)},u=function(){return d(void 0)};void 0!==r.start&&(a=function(){return r.start(n)});void 0!==r.write&&(i=function(e){return r.write(e,n)});void 0!==r.close&&(l=function(){return r.close()});void 0!==r.abort&&(u=function(e){return r.abort(e)});Er(e,n,a,i,l,u,t,o)}(this,o,Je(t,1),n)}return Object.defineProperty(WritableStream.prototype,"locked",{get:function(){if(!sr(this))throw Dr("locked");return cr(this)},enumerable:!1,configurable:!0}),WritableStream.prototype.abort=function(e){return void 0===e&&(e=void 0),sr(this)?cr(this)?f(new TypeError("Cannot abort a stream that already has a writer")):dr(this,e):f(Dr("abort"))},WritableStream.prototype.close=function(){return sr(this)?cr(this)?f(new TypeError("Cannot close a stream that already has a writer")):hr(this)?f(new TypeError("Cannot close an already-closing stream")):fr(this):f(Dr("close"))},WritableStream.prototype.getWriter=function(){if(!sr(this))throw Dr("getWriter");return lr(this)},WritableStream}();function lr(e){return new vr(e)}function ur(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new w,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function sr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof ir)}function cr(e){return void 0!==e._writer}function dr(e,r){var t;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=r,null===(t=e._writableStreamController._abortController)||void 0===t||t.abort();var o=e._state;if("closed"===o||"errored"===o)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var n=!1;"erroring"===o&&(n=!0,r=void 0);var a=c((function(t,o){e._pendingAbortRequest={_promise:void 0,_resolve:t,_reject:o,_reason:r,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||pr(e,r),a}function fr(e){var r=e._state;if("closed"===r||"errored"===r)return f(new TypeError("The stream (in "+r+" state) is not in the writable state and cannot be closed"));var t,o=c((function(r,t){var o={_resolve:r,_reject:t};e._closeRequest=o})),n=e._writer;return void 0!==n&&e._backpressure&&"writable"===r&&Gr(n),be(t=e._writableStreamController,Pr,0),Br(t),o}function br(e,r){"writable"!==e._state?_r(e):pr(e,r)}function pr(e,r){var t=e._writableStreamController;e._state="erroring",e._storedError=r;var o=e._writer;void 0!==o&&Rr(o,r),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&t._started&&_r(e)}function _r(e){e._state="errored",e._writableStreamController[B]();var r=e._storedError;if(e._writeRequests.forEach((function(e){e._reject(r)})),e._writeRequests=new w,void 0!==e._pendingAbortRequest){var t=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,t._wasAlreadyErroring)return t._reject(r),void mr(e);p(e._writableStreamController[j](t._reason),(function(){t._resolve(),mr(e)}),(function(r){t._reject(r),mr(e)}))}else mr(e)}function hr(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function mr(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var r=e._writer;void 0!==r&&Yr(r,e._storedError)}function yr(e,r){var t=e._writer;void 0!==t&&r!==e._backpressure&&(r?function(e){Nr(e)}(t):Gr(t)),e._backpressure=r}Object.defineProperties(ir.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(ir.prototype,r.toStringTag,{value:"WritableStream",configurable:!0});var vr=function(){function WritableStreamDefaultWriter(e){if(M(e,1,"WritableStreamDefaultWriter"),nr(e,"First parameter"),cr(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r,t=e._state;if("writable"===t)!hr(e)&&e._backpressure?Nr(this):Vr(this),Mr(this);else if("erroring"===t)Hr(this,e._storedError),Mr(this);else if("closed"===t)Vr(this),Mr(r=this),xr(r);else{var o=e._storedError;Hr(this,o),Qr(this,o)}}return Object.defineProperty(WritableStreamDefaultWriter.prototype,"closed",{get:function(){return gr(this)?this._closedPromise:f(Fr("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"desiredSize",{get:function(){if(!gr(this))throw Fr("desiredSize");if(void 0===this._ownerWritableStream)throw Lr("desiredSize");return function(e){var r=e._ownerWritableStream,t=r._state;if("errored"===t||"erroring"===t)return null;if("closed"===t)return 0;return jr(r._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"ready",{get:function(){return gr(this)?this._readyPromise:f(Fr("ready"))},enumerable:!1,configurable:!0}),WritableStreamDefaultWriter.prototype.abort=function(e){return void 0===e&&(e=void 0),gr(this)?void 0===this._ownerWritableStream?f(Lr("abort")):function(e,r){return dr(e._ownerWritableStream,r)}(this,e):f(Fr("abort"))},WritableStreamDefaultWriter.prototype.close=function(){if(!gr(this))return f(Fr("close"));var e=this._ownerWritableStream;return void 0===e?f(Lr("close")):hr(e)?f(new TypeError("Cannot close an already-closing stream")):Sr(this)},WritableStreamDefaultWriter.prototype.releaseLock=function(){if(!gr(this))throw Fr("releaseLock");void 0!==this._ownerWritableStream&&Tr(this)},WritableStreamDefaultWriter.prototype.write=function(e){return void 0===e&&(e=void 0),gr(this)?void 0===this._ownerWritableStream?f(Lr("write to")):Cr(this,e):f(Fr("write"))},WritableStreamDefaultWriter}();function gr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof vr)}function Sr(e){return fr(e._ownerWritableStream)}function wr(e,r){"pending"===e._closedPromiseState?Yr(e,r):function(e,r){Qr(e,r)}(e,r)}function Rr(e,r){"pending"===e._readyPromiseState?Ur(e,r):function(e,r){Hr(e,r)}(e,r)}function Tr(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Rr(e,t),wr(e,t),r._writer=void 0,e._ownerWritableStream=void 0}function Cr(e,r){var t=e._ownerWritableStream,o=t._writableStreamController,n=function(e,r){try{return e._strategySizeAlgorithm(r)}catch(r){return kr(e,r),1}}(o,r);if(t!==e._ownerWritableStream)return f(Lr("write to"));var a=t._state;if("errored"===a)return f(t._storedError);if(hr(t)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(t._storedError);var i=function(e){return c((function(r,t){var o={_resolve:r,_reject:t};e._writeRequests.push(o)}))}(t);return function(e,r,t){try{be(e,r,t)}catch(r){return void kr(e,r)}var o=e._controlledWritableStream;if(!hr(o)&&"writable"===o._state){yr(o,Ar(e))}Br(e)}(o,r,n),i}Object.defineProperties(vr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(vr.prototype,r.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var Pr={},qr=function(){function WritableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(WritableStreamDefaultController.prototype,"abortReason",{get:function(){if(!Or(this))throw Ir("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultController.prototype,"signal",{get:function(){if(!Or(this))throw Ir("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),WritableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Or(this))throw Ir("error");"writable"===this._controlledWritableStream._state&&zr(this,e)},WritableStreamDefaultController.prototype[j]=function(e){var r=this._abortAlgorithm(e);return Wr(this),r},WritableStreamDefaultController.prototype[B]=function(){pe(this)},WritableStreamDefaultController}();function Or(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof qr)}function Er(e,r,t,o,n,a,i,l){r._controlledWritableStream=e,e._writableStreamController=r,r._queue=void 0,r._queueTotalSize=void 0,pe(r),r._abortReason=void 0,r._abortController=function(){if(ar)return new AbortController}(),r._started=!1,r._strategySizeAlgorithm=l,r._strategyHWM=i,r._writeAlgorithm=o,r._closeAlgorithm=n,r._abortAlgorithm=a;var u=Ar(r);yr(e,u),p(d(t()),(function(){r._started=!0,Br(r)}),(function(t){r._started=!0,br(e,t)}))}function Wr(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function jr(e){return e._strategyHWM-e._queueTotalSize}function Br(e){var r=e._controlledWritableStream;if(e._started&&void 0===r._inFlightWriteRequest)if("erroring"!==r._state){if(0!==e._queue.length){var t=e._queue.peek().value;t===Pr?function(e){var r=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(r),fe(e);var t=e._closeAlgorithm();Wr(e),p(t,(function(){!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var r=e._writer;void 0!==r&&xr(r)}(r)}),(function(e){!function(e,r){e._inFlightCloseRequest._reject(r),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(r),e._pendingAbortRequest=void 0),br(e,r)}(r,e)}))}(e):function(e,r){var t=e._controlledWritableStream;(function(e){e._inFlightWriteRequest=e._writeRequests.shift()})(t),p(e._writeAlgorithm(r),(function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(t);var r=t._state;if(fe(e),!hr(t)&&"writable"===r){var o=Ar(e);yr(t,o)}Br(e)}),(function(r){"writable"===t._state&&Wr(e),function(e,r){e._inFlightWriteRequest._reject(r),e._inFlightWriteRequest=void 0,br(e,r)}(t,r)}))}(e,t)}}else _r(r)}function kr(e,r){"writable"===e._controlledWritableStream._state&&zr(e,r)}function Ar(e){return jr(e)<=0}function zr(e,r){var t=e._controlledWritableStream;Wr(e),pr(t,r)}function Dr(e){return new TypeError("WritableStream.prototype."+e+" can only be used on a WritableStream")}function Ir(e){return new TypeError("WritableStreamDefaultController.prototype."+e+" can only be used on a WritableStreamDefaultController")}function Fr(e){return new TypeError("WritableStreamDefaultWriter.prototype."+e+" can only be used on a WritableStreamDefaultWriter")}function Lr(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Mr(e){e._closedPromise=c((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t,e._closedPromiseState="pending"}))}function Qr(e,r){Mr(e),Yr(e,r)}function Yr(e,r){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function xr(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Nr(e){e._readyPromise=c((function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})),e._readyPromiseState="pending"}function Hr(e,r){Nr(e),Ur(e,r)}function Vr(e){Nr(e),Gr(e)}function Ur(e,r){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Gr(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(qr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(qr.prototype,r.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var Xr="undefined"!=typeof DOMException?DOMException:void 0;var Jr,Kr=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Xr)?Xr:((Jr=function(e,r){this.message=e||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}).prototype=Object.create(Error.prototype),Object.defineProperty(Jr.prototype,"constructor",{value:Jr,writable:!0,configurable:!0}),Jr);function Zr(e,r,o,n,a,i){var l=V(e),u=lr(r);e._disturbed=!0;var s=!1,m=d(void 0);return c((function(v,g){var S,w,R,T;if(void 0!==i){if(S=function(){var t=new Kr("Aborted","AbortError"),o=[];n||o.push((function(){return"writable"===r._state?dr(r,t):d(void 0)})),a||o.push((function(){return"readable"===e._state?Tt(e,t):d(void 0)})),E((function(){return Promise.all(o.map((function(e){return e()})))}),!0,t)},i.aborted)return void S();i.addEventListener("abort",S)}if(O(e,l._closedPromise,(function(e){n?W(!0,e):E((function(){return dr(r,e)}),!0,e)})),O(r,u._closedPromise,(function(r){a?W(!0,r):E((function(){return Tt(e,r)}),!0,r)})),w=e,R=l._closedPromise,T=function(){o?W():E((function(){return function(e){var r=e._ownerWritableStream,t=r._state;return hr(r)||"closed"===t?d(void 0):"errored"===t?f(r._storedError):Sr(e)}(u)}))},"closed"===w._state?T():_(R,T),hr(r)||"closed"===r._state){var P=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,P):E((function(){return Tt(e,P)}),!0,P)}function q(){var e=m;return b(m,(function(){return e!==m?q():void 0}))}function O(e,r,t){"errored"===e._state?t(e._storedError):h(r,t)}function E(e,t,o){function n(){p(e(),(function(){return j(t,o)}),(function(e){return j(!0,e)}))}s||(s=!0,"writable"!==r._state||hr(r)?n():_(q(),n))}function W(e,t){s||(s=!0,"writable"!==r._state||hr(r)?j(e,t):_(q(),(function(){return j(e,t)})))}function j(e,r){Tr(u),C(l),void 0!==i&&i.removeEventListener("abort",S),e?g(r):v(void 0)}y(c((function(e,r){!function o(n){n?e():b(s?d(!0):b(u._readyPromise,(function(){return c((function(e,r){re(l,{_chunkSteps:function(r){m=b(Cr(u,r),void 0,t),e(!1)},_closeSteps:function(){return e(!0)},_errorSteps:r})}))})),o,r)}(!1)})))}))}var $r=function(){function ReadableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamDefaultController.prototype,"desiredSize",{get:function(){if(!et(this))throw ct("desiredSize");return lt(this)},enumerable:!1,configurable:!0}),ReadableStreamDefaultController.prototype.close=function(){if(!et(this))throw ct("close");if(!ut(this))throw new TypeError("The stream is not in a state that permits close");nt(this)},ReadableStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!et(this))throw ct("enqueue");if(!ut(this))throw new TypeError("The stream is not in a state that permits enqueue");return at(this,e)},ReadableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!et(this))throw ct("error");it(this,e)},ReadableStreamDefaultController.prototype[k]=function(e){pe(this);var r=this._cancelAlgorithm(e);return ot(this),r},ReadableStreamDefaultController.prototype[A]=function(e){var r=this._controlledReadableStream;if(this._queue.length>0){var t=fe(this);this._closeRequested&&0===this._queue.length?(ot(this),Ct(r)):rt(this),e._chunkSteps(t)}else U(r,e),rt(this)},ReadableStreamDefaultController}();function et(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof $r)}function rt(e){tt(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,p(e._pullAlgorithm(),(function(){e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,rt(e))}),(function(r){it(e,r)}))))}function tt(e){var r=e._controlledReadableStream;return!!ut(e)&&(!!e._started&&(!!(Rt(r)&&X(r)>0)||lt(e)>0))}function ot(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function nt(e){if(ut(e)){var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(ot(e),Ct(r))}}function at(e,r){if(ut(e)){var t=e._controlledReadableStream;if(Rt(t)&&X(t)>0)G(t,r,!1);else{var o=void 0;try{o=e._strategySizeAlgorithm(r)}catch(r){throw it(e,r),r}try{be(e,r,o)}catch(r){throw it(e,r),r}}rt(e)}}function it(e,r){var t=e._controlledReadableStream;"readable"===t._state&&(pe(e),ot(e),Pt(t,r))}function lt(e){var r=e._controlledReadableStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function ut(e){var r=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===r}function st(e,r,t,o,n,a,i){r._controlledReadableStream=e,r._queue=void 0,r._queueTotalSize=void 0,pe(r),r._started=!1,r._closeRequested=!1,r._pullAgain=!1,r._pulling=!1,r._strategySizeAlgorithm=i,r._strategyHWM=a,r._pullAlgorithm=o,r._cancelAlgorithm=n,e._readableStreamController=r,p(d(t()),(function(){r._started=!0,rt(r)}),(function(e){it(r,e)}))}function ct(e){return new TypeError("ReadableStreamDefaultController.prototype."+e+" can only be used on a ReadableStreamDefaultController")}function dt(e,r){return me(e._readableStreamController)?function(e){var r,t,o,n,a,i=V(e),l=!1,u=!1,s=!1,f=!1,b=!1,p=c((function(e){a=e}));function _(e){h(e._closedPromise,(function(r){e===i&&(Ae(o._readableStreamController,r),Ae(n._readableStreamController,r),f&&b||a(void 0))}))}function m(){Ue(i)&&(C(i),_(i=V(e))),re(i,{_chunkSteps:function(r){v((function(){u=!1,s=!1;var t=r,i=r;if(!f&&!b)try{i=de(r)}catch(r){return Ae(o._readableStreamController,r),Ae(n._readableStreamController,r),void a(Tt(e,r))}f||ke(o._readableStreamController,t),b||ke(n._readableStreamController,i),l=!1,u?g():s&&S()}))},_closeSteps:function(){l=!1,f||Be(o._readableStreamController),b||Be(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&Ie(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&Ie(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:function(){l=!1}})}function y(r,t){ee(i)&&(C(i),_(i=Ye(e)));var c=t?n:o,d=t?o:n;Ge(i,r,{_chunkSteps:function(r){v((function(){u=!1,s=!1;var o=t?b:f;if(t?f:b)o||Fe(c._readableStreamController,r);else{var n=void 0;try{n=de(r)}catch(r){return Ae(c._readableStreamController,r),Ae(d._readableStreamController,r),void a(Tt(e,r))}o||Fe(c._readableStreamController,r),ke(d._readableStreamController,n)}l=!1,u?g():s&&S()}))},_closeSteps:function(e){l=!1;var r=t?b:f,o=t?f:b;r||Be(c._readableStreamController),o||Be(d._readableStreamController),void 0!==e&&(r||Fe(c._readableStreamController,e),!o&&d._readableStreamController._pendingPullIntos.length>0&&Ie(d._readableStreamController,0)),r&&o||a(void 0)},_errorSteps:function(){l=!1}})}function g(){if(l)return u=!0,d(void 0);l=!0;var e=ze(o._readableStreamController);return null===e?m():y(e._view,!1),d(void 0)}function S(){if(l)return s=!0,d(void 0);l=!0;var e=ze(n._readableStreamController);return null===e?m():y(e._view,!0),d(void 0)}function w(o){if(f=!0,r=o,b){var n=ue([r,t]),i=Tt(e,n);a(i)}return p}function R(o){if(b=!0,t=o,f){var n=ue([r,t]),i=Tt(e,n);a(i)}return p}function T(){}return o=gt(T,g,w),n=gt(T,S,R),_(i),[o,n]}(e):function(e,r){var t,o,n,a,i,l=V(e),u=!1,s=!1,f=!1,b=!1,p=c((function(e){i=e}));function _(){return u?(s=!0,d(void 0)):(u=!0,re(l,{_chunkSteps:function(e){v((function(){s=!1;var r=e,t=e;f||at(n._readableStreamController,r),b||at(a._readableStreamController,t),u=!1,s&&_()}))},_closeSteps:function(){u=!1,f||nt(n._readableStreamController),b||nt(a._readableStreamController),f&&b||i(void 0)},_errorSteps:function(){u=!1}}),d(void 0))}function m(r){if(f=!0,t=r,b){var n=ue([t,o]),a=Tt(e,n);i(a)}return p}function y(r){if(b=!0,o=r,f){var n=ue([t,o]),a=Tt(e,n);i(a)}return p}function g(){}return n=vt(g,_,m),a=vt(g,_,y),h(l._closedPromise,(function(e){it(n._readableStreamController,e),it(a._readableStreamController,e),f&&b||i(void 0)})),[n,a]}(e)}function ft(e,r,t){return F(e,t),function(t){return S(e,r,[t])}}function bt(e,r,t){return F(e,t),function(t){return S(e,r,[t])}}function pt(e,r,t){return F(e,t),function(t){return g(e,r,[t])}}function _t(e,r){if("bytes"!==(e=""+e))throw new TypeError(r+" '"+e+"' is not a valid enumeration value for ReadableStreamType");return e}function ht(e,r){if("byob"!==(e=""+e))throw new TypeError(r+" '"+e+"' is not a valid enumeration value for ReadableStreamReaderMode");return e}function mt(e,r){I(e,r);var t=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,r){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(r+" is not an AbortSignal.")}(a,r+" has member 'signal' that"),{preventAbort:Boolean(t),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties($r.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty($r.prototype,r.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var yt=function(){function ReadableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:L(e,"First parameter");var t=Ze(r,"Second parameter"),o=function(e,r){I(e,r);var t=e,o=null==t?void 0:t.autoAllocateChunkSize,n=null==t?void 0:t.cancel,a=null==t?void 0:t.pull,i=null==t?void 0:t.start,l=null==t?void 0:t.type;return{autoAllocateChunkSize:void 0===o?void 0:N(o,r+" has member 'autoAllocateChunkSize' that"),cancel:void 0===n?void 0:ft(n,t,r+" has member 'cancel' that"),pull:void 0===a?void 0:bt(a,t,r+" has member 'pull' that"),start:void 0===i?void 0:pt(i,t,r+" has member 'start' that"),type:void 0===l?void 0:_t(l,r+" has member 'type' that")}}(e,"First parameter");if(St(this),"bytes"===o.type){if(void 0!==t.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,r,t){var o=Object.create(he.prototype),n=function(){},a=function(){return d(void 0)},i=function(){return d(void 0)};void 0!==r.start&&(n=function(){return r.start(o)}),void 0!==r.pull&&(a=function(){return r.pull(o)}),void 0!==r.cancel&&(i=function(e){return r.cancel(e)});var l=r.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");Le(e,o,n,a,i,t,l)}(this,o,Je(t,0))}else{var n=Ke(t);!function(e,r,t,o){var n=Object.create($r.prototype),a=function(){},i=function(){return d(void 0)},l=function(){return d(void 0)};void 0!==r.start&&(a=function(){return r.start(n)}),void 0!==r.pull&&(i=function(){return r.pull(n)}),void 0!==r.cancel&&(l=function(e){return r.cancel(e)}),st(e,n,a,i,l,t,o)}(this,o,Je(t,1),n)}}return Object.defineProperty(ReadableStream.prototype,"locked",{get:function(){if(!wt(this))throw qt("locked");return Rt(this)},enumerable:!1,configurable:!0}),ReadableStream.prototype.cancel=function(e){return void 0===e&&(e=void 0),wt(this)?Rt(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Tt(this,e):f(qt("cancel"))},ReadableStream.prototype.getReader=function(e){if(void 0===e&&(e=void 0),!wt(this))throw qt("getReader");return void 0===function(e,r){I(e,r);var t=null==e?void 0:e.mode;return{mode:void 0===t?void 0:ht(t,r+" has member 'mode' that")}}(e,"First parameter").mode?V(this):Ye(this)},ReadableStream.prototype.pipeThrough=function(e,r){if(void 0===r&&(r={}),!wt(this))throw qt("pipeThrough");M(e,1,"pipeThrough");var t=function(e,r){I(e,r);var t=null==e?void 0:e.readable;Q(t,"readable","ReadableWritablePair"),H(t,r+" has member 'readable' that");var o=null==e?void 0:e.writable;return Q(o,"writable","ReadableWritablePair"),nr(o,r+" has member 'writable' that"),{readable:t,writable:o}}(e,"First parameter"),o=mt(r,"Second parameter");if(Rt(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(cr(t.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(Zr(this,t.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),t.readable},ReadableStream.prototype.pipeTo=function(e,r){if(void 0===r&&(r={}),!wt(this))return f(qt("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!sr(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var t;try{t=mt(r,"Second parameter")}catch(e){return f(e)}return Rt(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):cr(e)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Zr(this,e,t.preventClose,t.preventAbort,t.preventCancel,t.signal)},ReadableStream.prototype.tee=function(){if(!wt(this))throw qt("tee");return ue(dt(this))},ReadableStream.prototype.values=function(e){if(void 0===e&&(e=void 0),!wt(this))throw qt("values");var r,t,o,n,a,i=function(e,r){I(e,r);var t=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(t)}}(e,"First parameter");return r=this,t=i.preventCancel,o=V(r),n=new oe(o,t),(a=Object.create(ne))._asyncIteratorImpl=n,a},ReadableStream}();function vt(e,r,t,o,n){void 0===o&&(o=1),void 0===n&&(n=function(){return 1});var a=Object.create(yt.prototype);return St(a),st(a,Object.create($r.prototype),e,r,t,o,n),a}function gt(e,r,t){var o=Object.create(yt.prototype);return St(o),Le(o,Object.create(he.prototype),e,r,t,0,void 0),o}function St(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function wt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof yt)}function Rt(e){return void 0!==e._reader}function Tt(e,r){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);Ct(e);var o=e._reader;return void 0!==o&&Ue(o)&&(o._readIntoRequests.forEach((function(e){e._closeSteps(void 0)})),o._readIntoRequests=new w),m(e._readableStreamController[k](r),t)}function Ct(e){e._state="closed";var r=e._reader;void 0!==r&&(W(r),ee(r)&&(r._readRequests.forEach((function(e){e._closeSteps()})),r._readRequests=new w))}function Pt(e,r){e._state="errored",e._storedError=r;var t=e._reader;void 0!==t&&(E(t,r),ee(t)?(t._readRequests.forEach((function(e){e._errorSteps(r)})),t._readRequests=new w):(t._readIntoRequests.forEach((function(e){e._errorSteps(r)})),t._readIntoRequests=new w))}function qt(e){return new TypeError("ReadableStream.prototype."+e+" can only be used on a ReadableStream")}function Ot(e,r){I(e,r);var t=null==e?void 0:e.highWaterMark;return Q(t,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(t)}}Object.defineProperties(yt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(yt.prototype,r.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof r.asyncIterator&&Object.defineProperty(yt.prototype,r.asyncIterator,{value:yt.prototype.values,writable:!0,configurable:!0});var Et=function(e){return e.byteLength};try{Object.defineProperty(Et,"name",{value:"size",configurable:!0})}catch(K){}var Wt=function(){function ByteLengthQueuingStrategy(e){M(e,1,"ByteLengthQueuingStrategy"),e=Ot(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(ByteLengthQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!Bt(this))throw jt("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(ByteLengthQueuingStrategy.prototype,"size",{get:function(){if(!Bt(this))throw jt("size");return Et},enumerable:!1,configurable:!0}),ByteLengthQueuingStrategy}();function jt(e){return new TypeError("ByteLengthQueuingStrategy.prototype."+e+" can only be used on a ByteLengthQueuingStrategy")}function Bt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof Wt)}Object.defineProperties(Wt.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Wt.prototype,r.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var kt=function(){return 1};try{Object.defineProperty(kt,"name",{value:"size",configurable:!0})}catch(K){}var At=function(){function CountQueuingStrategy(e){M(e,1,"CountQueuingStrategy"),e=Ot(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(CountQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!Dt(this))throw zt("highWaterMark");return this._countQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(CountQueuingStrategy.prototype,"size",{get:function(){if(!Dt(this))throw zt("size");return kt},enumerable:!1,configurable:!0}),CountQueuingStrategy}();function zt(e){return new TypeError("CountQueuingStrategy.prototype."+e+" can only be used on a CountQueuingStrategy")}function Dt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof At)}function It(e,r,t){return F(e,t),function(t){return S(e,r,[t])}}function Ft(e,r,t){return F(e,t),function(t){return g(e,r,[t])}}function Lt(e,r,t){return F(e,t),function(t,o){return S(e,r,[t,o])}}Object.defineProperties(At.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(At.prototype,r.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var Mt=function(){function TransformStream(e,r,t){void 0===e&&(e={}),void 0===r&&(r={}),void 0===t&&(t={}),void 0===e&&(e=null);var o=Ze(r,"Second parameter"),n=Ze(t,"Third parameter"),a=function(e,r){I(e,r);var t=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===t?void 0:It(t,e,r+" has member 'flush' that"),readableType:o,start:void 0===n?void 0:Ft(n,e,r+" has member 'start' that"),transform:void 0===a?void 0:Lt(a,e,r+" has member 'transform' that"),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");var i,l=Je(n,0),u=Ke(n),s=Je(o,1),b=Ke(o);!function(e,r,t,o,n,a){function i(){return r}function l(r){return function(e,r){var t=e._transformStreamController;if(e._backpressure){return m(e._backpressureChangePromise,(function(){var o=e._writable;if("erroring"===o._state)throw o._storedError;return Xt(t,r)}))}return Xt(t,r)}(e,r)}function u(r){return function(e,r){return Yt(e,r),d(void 0)}(e,r)}function s(){return function(e){var r=e._readable,t=e._transformStreamController,o=t._flushAlgorithm();return Ut(t),m(o,(function(){if("errored"===r._state)throw r._storedError;nt(r._readableStreamController)}),(function(t){throw Yt(e,t),r._storedError}))}(e)}function c(){return function(e){return Nt(e,!1),e._backpressureChangePromise}(e)}function f(r){return xt(e,r),d(void 0)}e._writable=function(e,r,t,o,n,a){void 0===n&&(n=1),void 0===a&&(a=function(){return 1});var i=Object.create(ir.prototype);return ur(i),Er(i,Object.create(qr.prototype),e,r,t,o,n,a),i}(i,l,s,u,t,o),e._readable=vt(i,c,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Nt(e,!0),e._transformStreamController=void 0}(this,c((function(e){i=e})),s,b,l,u),function(e,r){var t=Object.create(Ht.prototype),o=function(e){try{return Gt(t,e),d(void 0)}catch(e){return f(e)}},n=function(){return d(void 0)};void 0!==r.transform&&(o=function(e){return r.transform(e,t)});void 0!==r.flush&&(n=function(){return r.flush(t)});!function(e,r,t,o){r._controlledTransformStream=e,e._transformStreamController=r,r._transformAlgorithm=t,r._flushAlgorithm=o}(e,t,o,n)}(this,a),void 0!==a.start?i(a.start(this._transformStreamController)):i(void 0)}return Object.defineProperty(TransformStream.prototype,"readable",{get:function(){if(!Qt(this))throw Kt("readable");return this._readable},enumerable:!1,configurable:!0}),Object.defineProperty(TransformStream.prototype,"writable",{get:function(){if(!Qt(this))throw Kt("writable");return this._writable},enumerable:!1,configurable:!0}),TransformStream}();function Qt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof Mt)}function Yt(e,r){it(e._readable._readableStreamController,r),xt(e,r)}function xt(e,r){Ut(e._transformStreamController),kr(e._writable._writableStreamController,r),e._backpressure&&Nt(e,!1)}function Nt(e,r){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((function(r){e._backpressureChangePromise_resolve=r})),e._backpressure=r}Object.defineProperties(Mt.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Mt.prototype,r.toStringTag,{value:"TransformStream",configurable:!0});var Ht=function(){function TransformStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(TransformStreamDefaultController.prototype,"desiredSize",{get:function(){if(!Vt(this))throw Jt("desiredSize");return lt(this._controlledTransformStream._readable._readableStreamController)},enumerable:!1,configurable:!0}),TransformStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!Vt(this))throw Jt("enqueue");Gt(this,e)},TransformStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Vt(this))throw Jt("error");var r;r=e,Yt(this._controlledTransformStream,r)},TransformStreamDefaultController.prototype.terminate=function(){if(!Vt(this))throw Jt("terminate");!function(e){var r=e._controlledTransformStream;nt(r._readable._readableStreamController);var t=new TypeError("TransformStream terminated");xt(r,t)}(this)},TransformStreamDefaultController}();function Vt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof Ht)}function Ut(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Gt(e,r){var t=e._controlledTransformStream,o=t._readable._readableStreamController;if(!ut(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{at(o,r)}catch(e){throw xt(t,e),t._readable._storedError}(function(e){return!tt(e)})(o)!==t._backpressure&&Nt(t,!0)}function Xt(e,r){return m(e._transformAlgorithm(r),void 0,(function(r){throw Yt(e._controlledTransformStream,r),r}))}function Jt(e){return new TypeError("TransformStreamDefaultController.prototype."+e+" can only be used on a TransformStreamDefaultController")}function Kt(e){return new TypeError("TransformStream.prototype."+e+" can only be used on a TransformStream")}Object.defineProperties(Ht.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Ht.prototype,r.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var Zt={ReadableStream:yt,ReadableStreamDefaultController:$r,ReadableByteStreamController:he,ReadableStreamBYOBRequest:_e,ReadableStreamDefaultReader:$,ReadableStreamBYOBReader:Ve,WritableStream:ir,WritableStreamDefaultController:qr,WritableStreamDefaultWriter:vr,ByteLengthQueuingStrategy:Wt,CountQueuingStrategy:At,TransformStream:Mt,TransformStreamDefaultController:Ht};if(void 0!==o)for(var $t in Zt)Object.prototype.hasOwnProperty.call(Zt,$t)&&Object.defineProperty(o,$t,{value:Zt[$t],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=Wt,e.CountQueuingStrategy=At,e.ReadableByteStreamController=he,e.ReadableStream=yt,e.ReadableStreamBYOBReader=Ve,e.ReadableStreamBYOBRequest=_e,e.ReadableStreamDefaultController=$r,e.ReadableStreamDefaultReader=$,e.TransformStream=Mt,e.TransformStreamDefaultController=Ht,e.WritableStream=ir,e.WritableStreamDefaultController=qr,e.WritableStreamDefaultWriter=vr,Object.defineProperty(e,"__esModule",{value:!0})}));
2 +//# sourceMappingURL=polyfill.min.js.map
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
1 +/// <reference lib="esnext.asynciterable" />
2 +
3 +/**
4 + * A signal object that allows you to communicate with a request and abort it if required
5 + * via its associated `AbortController` object.
6 + *
7 + * @remarks
8 + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.
9 + * It is redefined here, so it can be polyfilled without a DOM, for example with
10 + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.
11 + *
12 + * @public
13 + */
14 +export declare interface AbortSignal {
15 + /**
16 + * Whether the request is aborted.
17 + */
18 + readonly aborted: boolean;
19 + /**
20 + * Add an event listener to be triggered when this signal becomes aborted.
21 + */
22 + addEventListener(type: 'abort', listener: () => void): void;
23 + /**
24 + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.
25 + */
26 + removeEventListener(type: 'abort', listener: () => void): void;
27 +}
28 +
29 +/**
30 + * A queuing strategy that counts the number of bytes in each chunk.
31 + *
32 + * @public
33 + */
34 +export declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {
35 + constructor(options: QueuingStrategyInit);
36 + /**
37 + * Returns the high water mark provided to the constructor.
38 + */
39 + readonly highWaterMark: number;
40 + /**
41 + * Measures the size of `chunk` by returning the value of its `byteLength` property.
42 + */
43 + readonly size: (chunk: ArrayBufferView) => number;
44 +}
45 +
46 +/**
47 + * A queuing strategy that counts the number of chunks.
48 + *
49 + * @public
50 + */
51 +export declare class CountQueuingStrategy implements QueuingStrategy<any> {
52 + constructor(options: QueuingStrategyInit);
53 + /**
54 + * Returns the high water mark provided to the constructor.
55 + */
56 + readonly highWaterMark: number;
57 + /**
58 + * Measures the size of `chunk` by always returning 1.
59 + * This ensures that the total queue size is a count of the number of chunks in the queue.
60 + */
61 + readonly size: (chunk: any) => 1;
62 +}
63 +
64 +/**
65 + * A queuing strategy.
66 + *
67 + * @public
68 + */
69 +export declare interface QueuingStrategy<T = any> {
70 + /**
71 + * A non-negative number indicating the high water mark of the stream using this queuing strategy.
72 + */
73 + highWaterMark?: number;
74 + /**
75 + * A function that computes and returns the finite non-negative size of the given chunk value.
76 + */
77 + size?: QueuingStrategySizeCallback<T>;
78 +}
79 +
80 +/**
81 + * @public
82 + */
83 +export declare interface QueuingStrategyInit {
84 + /**
85 + * {@inheritDoc QueuingStrategy.highWaterMark}
86 + */
87 + highWaterMark: number;
88 +}
89 +
90 +declare type QueuingStrategySizeCallback<T = any> = (chunk: T) => number;
91 +
92 +declare type ReadableByteStream = ReadableStream<Uint8Array> & {
93 + _readableStreamController: ReadableByteStreamController;
94 +};
95 +
96 +/**
97 + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
98 + *
99 + * @public
100 + */
101 +export declare class ReadableByteStreamController {
102 + private constructor();
103 + /**
104 + * Returns the current BYOB pull request, or `null` if there isn't one.
105 + */
106 + readonly byobRequest: ReadableStreamBYOBRequest | null;
107 + /**
108 + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
109 + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
110 + */
111 + readonly desiredSize: number | null;
112 + /**
113 + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
114 + * the stream, but once those are read, the stream will become closed.
115 + */
116 + close(): void;
117 + /**
118 + * Enqueues the given chunk chunk in the controlled readable stream.
119 + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.
120 + */
121 + enqueue(chunk: ArrayBufferView): void;
122 + /**
123 + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
124 + */
125 + error(e?: any): void;
126 +}
127 +
128 +/**
129 + * A readable stream represents a source of data, from which you can read.
130 + *
131 + * @public
132 + */
133 +export declare class ReadableStream<R = any> {
134 + constructor(underlyingSource: UnderlyingByteSource, strategy?: {
135 + highWaterMark?: number;
136 + size?: undefined;
137 + });
138 + constructor(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>);
139 + /**
140 + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
141 + */
142 + readonly locked: boolean;
143 + /**
144 + * Cancels the stream, signaling a loss of interest in the stream by a consumer.
145 + *
146 + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
147 + * method, which might or might not use it.
148 + */
149 + cancel(reason?: any): Promise<void>;
150 + /**
151 + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.
152 + *
153 + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,
154 + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading.
155 + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its
156 + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise
157 + * control over allocation.
158 + */
159 + getReader({ mode }: {
160 + mode: 'byob';
161 + }): ReadableStreamBYOBReader;
162 + /**
163 + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.
164 + * While the stream is locked, no other reader can be acquired until this one is released.
165 + *
166 + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream
167 + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours
168 + * or cancel the stream, which would interfere with your abstraction.
169 + */
170 + getReader(): ReadableStreamDefaultReader<R>;
171 + /**
172 + * Provides a convenient, chainable way of piping this readable stream through a transform stream
173 + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream
174 + * into the writable side of the supplied pair, and returns the readable side for further use.
175 + *
176 + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
177 + */
178 + pipeThrough<RS extends ReadableStream>(transform: {
179 + readable: RS;
180 + writable: WritableStream<R>;
181 + }, options?: StreamPipeOptions): RS;
182 + /**
183 + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under
184 + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills
185 + * when the piping process completes successfully, or rejects if any errors were encountered.
186 + *
187 + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
188 + */
189 + pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
190 + /**
191 + * Tees this readable stream, returning a two-element array containing the two resulting branches as
192 + * new {@link ReadableStream} instances.
193 + *
194 + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
195 + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
196 + * propagated to the stream's underlying source.
197 + *
198 + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
199 + * this could allow interference between the two branches.
200 + */
201 + tee(): [ReadableStream<R>, ReadableStream<R>];
202 + /**
203 + * Asynchronously iterates over the chunks in the stream's internal queue.
204 + *
205 + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.
206 + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method
207 + * is called, e.g. by breaking out of the loop.
208 + *
209 + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also
210 + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing
211 + * `true` for the `preventCancel` option.
212 + */
213 + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
214 + /**
215 + * {@inheritDoc ReadableStream.values}
216 + */
217 + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator<R>;
218 +}
219 +
220 +/**
221 + * An async iterator returned by {@link ReadableStream.values}.
222 + *
223 + * @public
224 + */
225 +export declare interface ReadableStreamAsyncIterator<R> extends AsyncIterator<R> {
226 + next(): Promise<IteratorResult<R, undefined>>;
227 + return(value?: any): Promise<IteratorResult<any>>;
228 +}
229 +
230 +/**
231 + * A BYOB reader vended by a {@link ReadableStream}.
232 + *
233 + * @public
234 + */
235 +export declare class ReadableStreamBYOBReader {
236 + constructor(stream: ReadableByteStream);
237 + /**
238 + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
239 + * the reader's lock is released before the stream finishes closing.
240 + */
241 + readonly closed: Promise<undefined>;
242 + /**
243 + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
244 + */
245 + cancel(reason?: any): Promise<void>;
246 + /**
247 + * Attempts to reads bytes into view, and returns a promise resolved with the result.
248 + *
249 + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
250 + */
251 + read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamBYOBReadResult<T>>;
252 + /**
253 + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
254 + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
255 + * from now on; otherwise, the reader will appear closed.
256 + *
257 + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
258 + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
259 + * do so will throw a `TypeError` and leave the reader locked to the stream.
260 + */
261 + releaseLock(): void;
262 +}
263 +
264 +/**
265 + * A result returned by {@link ReadableStreamBYOBReader.read}.
266 + *
267 + * @public
268 + */
269 +export declare type ReadableStreamBYOBReadResult<T extends ArrayBufferView> = {
270 + done: false;
271 + value: T;
272 +} | {
273 + done: true;
274 + value: T | undefined;
275 +};
276 +
277 +/**
278 + * A pull-into request in a {@link ReadableByteStreamController}.
279 + *
280 + * @public
281 + */
282 +export declare class ReadableStreamBYOBRequest {
283 + private constructor();
284 + /**
285 + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
286 + */
287 + readonly view: ArrayBufferView | null;
288 + /**
289 + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into
290 + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.
291 + *
292 + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer
293 + * modifiable.
294 + */
295 + respond(bytesWritten: number): void;
296 + /**
297 + * Indicates to the associated readable byte stream that instead of writing into
298 + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,
299 + * which will be given to the consumer of the readable byte stream.
300 + *
301 + * After this method is called, `view` will be transferred and no longer modifiable.
302 + */
303 + respondWithNewView(view: ArrayBufferView): void;
304 +}
305 +
306 +/**
307 + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
308 + *
309 + * @public
310 + */
311 +export declare class ReadableStreamDefaultController<R> {
312 + private constructor();
313 + /**
314 + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
315 + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
316 + */
317 + readonly desiredSize: number | null;
318 + /**
319 + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
320 + * the stream, but once those are read, the stream will become closed.
321 + */
322 + close(): void;
323 + /**
324 + * Enqueues the given chunk `chunk` in the controlled readable stream.
325 + */
326 + enqueue(chunk: R): void;
327 + /**
328 + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
329 + */
330 + error(e?: any): void;
331 +}
332 +
333 +/**
334 + * A default reader vended by a {@link ReadableStream}.
335 + *
336 + * @public
337 + */
338 +export declare class ReadableStreamDefaultReader<R = any> {
339 + constructor(stream: ReadableStream<R>);
340 + /**
341 + * Returns a promise that will be fulfilled when the stream becomes closed,
342 + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
343 + */
344 + readonly closed: Promise<undefined>;
345 + /**
346 + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
347 + */
348 + cancel(reason?: any): Promise<void>;
349 + /**
350 + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
351 + *
352 + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
353 + */
354 + read(): Promise<ReadableStreamDefaultReadResult<R>>;
355 + /**
356 + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
357 + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
358 + * from now on; otherwise, the reader will appear closed.
359 + *
360 + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
361 + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
362 + * do so will throw a `TypeError` and leave the reader locked to the stream.
363 + */
364 + releaseLock(): void;
365 +}
366 +
367 +/**
368 + * A result returned by {@link ReadableStreamDefaultReader.read}.
369 + *
370 + * @public
371 + */
372 +export declare type ReadableStreamDefaultReadResult<T> = {
373 + done: false;
374 + value: T;
375 +} | {
376 + done: true;
377 + value?: undefined;
378 +};
379 +
380 +/**
381 + * Options for {@link ReadableStream.values | async iterating} a stream.
382 + *
383 + * @public
384 + */
385 +export declare interface ReadableStreamIteratorOptions {
386 + preventCancel?: boolean;
387 +}
388 +
389 +/**
390 + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed
391 + * to {@link ReadableStream.pipeThrough}.
392 + *
393 + * @public
394 + */
395 +export declare interface ReadableWritablePair<R, W> {
396 + readable: ReadableStream<R>;
397 + writable: WritableStream<W>;
398 +}
399 +
400 +/**
401 + * Options for {@link ReadableStream.pipeTo | piping} a stream.
402 + *
403 + * @public
404 + */
405 +export declare interface StreamPipeOptions {
406 + /**
407 + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors.
408 + */
409 + preventAbort?: boolean;
410 + /**
411 + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes
412 + * or errors.
413 + */
414 + preventCancel?: boolean;
415 + /**
416 + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes.
417 + */
418 + preventClose?: boolean;
419 + /**
420 + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding
421 + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream
422 + * aborted, unless the respective options `preventCancel` or `preventAbort` are set.
423 + */
424 + signal?: AbortSignal;
425 +}
426 +
427 +/**
428 + * A transformer for constructing a {@link TransformStream}.
429 + *
430 + * @public
431 + */
432 +export declare interface Transformer<I = any, O = any> {
433 + /**
434 + * A function that is called immediately during creation of the {@link TransformStream}.
435 + */
436 + start?: TransformerStartCallback<O>;
437 + /**
438 + * A function called when a new chunk originally written to the writable side is ready to be transformed.
439 + */
440 + transform?: TransformerTransformCallback<I, O>;
441 + /**
442 + * A function called after all chunks written to the writable side have been transformed by successfully passing
443 + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed.
444 + */
445 + flush?: TransformerFlushCallback<O>;
446 + readableType?: undefined;
447 + writableType?: undefined;
448 +}
449 +
450 +/** @public */
451 +export declare type TransformerFlushCallback<O> = (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
452 +
453 +/** @public */
454 +export declare type TransformerStartCallback<O> = (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
455 +
456 +/** @public */
457 +export declare type TransformerTransformCallback<I, O> = (chunk: I, controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
458 +
459 +/**
460 + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
461 + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
462 + * In a manner specific to the transform stream in question, writes to the writable side result in new data being
463 + * made available for reading from the readable side.
464 + *
465 + * @public
466 + */
467 +export declare class TransformStream<I = any, O = any> {
468 + constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
469 + /**
470 + * The readable side of the transform stream.
471 + */
472 + readonly readable: ReadableStream<O>;
473 + /**
474 + * The writable side of the transform stream.
475 + */
476 + readonly writable: WritableStream<I>;
477 +}
478 +
479 +/**
480 + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
481 + *
482 + * @public
483 + */
484 +export declare class TransformStreamDefaultController<O> {
485 + private constructor();
486 + /**
487 + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
488 + */
489 + readonly desiredSize: number | null;
490 + /**
491 + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.
492 + */
493 + enqueue(chunk: O): void;
494 + /**
495 + * Errors both the readable side and the writable side of the controlled transform stream, making all future
496 + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
497 + */
498 + error(reason?: any): void;
499 + /**
500 + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
501 + * transformer only needs to consume a portion of the chunks written to the writable side.
502 + */
503 + terminate(): void;
504 +}
505 +
506 +/**
507 + * An underlying byte source for constructing a {@link ReadableStream}.
508 + *
509 + * @public
510 + */
511 +export declare interface UnderlyingByteSource {
512 + /**
513 + * {@inheritDoc UnderlyingSource.start}
514 + */
515 + start?: UnderlyingByteSourceStartCallback;
516 + /**
517 + * {@inheritDoc UnderlyingSource.pull}
518 + */
519 + pull?: UnderlyingByteSourcePullCallback;
520 + /**
521 + * {@inheritDoc UnderlyingSource.cancel}
522 + */
523 + cancel?: UnderlyingSourceCancelCallback;
524 + /**
525 + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream.
526 + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its
527 + * {@link ReadableStream.(getReader:1) | getReader()} method.
528 + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()}
529 + * and {@link UnderlyingByteSource.pull | pull()} methods.
530 + */
531 + type: 'bytes';
532 + /**
533 + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the
534 + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream
535 + * implementation will automatically allocate an ArrayBuffer of the given size, so that
536 + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present,
537 + * as if the consumer was using a BYOB reader.
538 + */
539 + autoAllocateChunkSize?: number;
540 +}
541 +
542 +/** @public */
543 +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike<void>;
544 +
545 +/** @public */
546 +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike<void>;
547 +
548 +/**
549 + * An underlying sink for constructing a {@link WritableStream}.
550 + *
551 + * @public
552 + */
553 +export declare interface UnderlyingSink<W = any> {
554 + /**
555 + * A function that is called immediately during creation of the {@link WritableStream}.
556 + */
557 + start?: UnderlyingSinkStartCallback;
558 + /**
559 + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream
560 + * implementation guarantees that this function will be called only after previous writes have succeeded, and never
561 + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or
562 + * {@link UnderlyingSink.abort | abort()} have been called.
563 + *
564 + * This function is used to actually send the data to the resource presented by the underlying sink, for example by
565 + * calling a lower-level API.
566 + */
567 + write?: UnderlyingSinkWriteCallback<W>;
568 + /**
569 + * A function that is called after the producer signals, via
570 + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and
571 + * subsequently all queued-up writes have successfully completed.
572 + *
573 + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release
574 + * access to any held resources.
575 + */
576 + close?: UnderlyingSinkCloseCallback;
577 + /**
578 + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or
579 + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its
580 + * argument the same value as was passed to those methods by the producer.
581 + *
582 + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the
583 + * {@link ReadableStream.pipeTo | pipeTo()} method for more details.
584 + *
585 + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with
586 + * some custom handling.
587 + */
588 + abort?: UnderlyingSinkAbortCallback;
589 + type?: undefined;
590 +}
591 +
592 +/** @public */
593 +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike<void>;
594 +
595 +/** @public */
596 +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike<void>;
597 +
598 +/** @public */
599 +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike<void>;
600 +
601 +/** @public */
602 +export declare type UnderlyingSinkWriteCallback<W> = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike<void>;
603 +
604 +/**
605 + * An underlying source for constructing a {@link ReadableStream}.
606 + *
607 + * @public
608 + */
609 +export declare interface UnderlyingSource<R = any> {
610 + /**
611 + * A function that is called immediately during creation of the {@link ReadableStream}.
612 + */
613 + start?: UnderlyingSourceStartCallback<R>;
614 + /**
615 + * A function that is called whenever the stream’s internal queue of chunks becomes not full,
616 + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly
617 + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive).
618 + */
619 + pull?: UnderlyingSourcePullCallback<R>;
620 + /**
621 + * A function that is called whenever the consumer cancels the stream, via
622 + * {@link ReadableStream.cancel | stream.cancel()},
623 + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or
624 + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}.
625 + * It takes as its argument the same value as was passed to those methods by the consumer.
626 + */
627 + cancel?: UnderlyingSourceCancelCallback;
628 + type?: undefined;
629 +}
630 +
631 +/** @public */
632 +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike<void>;
633 +
634 +/** @public */
635 +export declare type UnderlyingSourcePullCallback<R> = (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
636 +
637 +/** @public */
638 +export declare type UnderlyingSourceStartCallback<R> = (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
639 +
640 +/**
641 + * A writable stream represents a destination for data, into which you can write.
642 + *
643 + * @public
644 + */
645 +export declare class WritableStream<W = any> {
646 + constructor(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>);
647 + /**
648 + * Returns whether or not the writable stream is locked to a writer.
649 + */
650 + readonly locked: boolean;
651 + /**
652 + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
653 + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
654 + * mechanism of the underlying sink.
655 + *
656 + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
657 + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
658 + * the stream) if the stream is currently locked.
659 + */
660 + abort(reason?: any): Promise<void>;
661 + /**
662 + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
663 + * close behavior. During this time any further attempts to write will fail (without erroring the stream).
664 + *
665 + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
666 + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
667 + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
668 + */
669 + close(): Promise<undefined>;
670 + /**
671 + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
672 + * is locked, no other writer can be acquired until this one is released.
673 + *
674 + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
675 + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
676 + * the same time, which would cause the resulting written data to be unpredictable and probably useless.
677 + */
678 + getWriter(): WritableStreamDefaultWriter<W>;
679 +}
680 +
681 +/**
682 + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
683 + *
684 + * @public
685 + */
686 +export declare class WritableStreamDefaultController<W = any> {
687 + private constructor();
688 + /**
689 + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
690 + *
691 + * @deprecated
692 + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
693 + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
694 + */
695 + readonly abortReason: any;
696 + /**
697 + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
698 + */
699 + readonly signal: AbortSignal;
700 + /**
701 + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
702 + *
703 + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
704 + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
705 + * normal lifecycle of interactions with the underlying sink.
706 + */
707 + error(e?: any): void;
708 +}
709 +
710 +/**
711 + * A default writer vended by a {@link WritableStream}.
712 + *
713 + * @public
714 + */
715 +export declare class WritableStreamDefaultWriter<W = any> {
716 + constructor(stream: WritableStream<W>);
717 + /**
718 + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
719 + * the writer’s lock is released before the stream finishes closing.
720 + */
721 + readonly closed: Promise<undefined>;
722 + /**
723 + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
724 + * A producer can use this information to determine the right amount of data to write.
725 + *
726 + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
727 + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
728 + * the writer’s lock is released.
729 + */
730 + readonly desiredSize: number | null;
731 + /**
732 + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
733 + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
734 + * back to zero or below, the getter will return a new promise that stays pending until the next transition.
735 + *
736 + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
737 + * rejected.
738 + */
739 + readonly ready: Promise<undefined>;
740 + /**
741 + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
742 + */
743 + abort(reason?: any): Promise<void>;
744 + /**
745 + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
746 + */
747 + close(): Promise<void>;
748 + /**
749 + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
750 + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
751 + * now on; otherwise, the writer will appear closed.
752 + *
753 + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
754 + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
755 + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
756 + * other producers from writing in an interleaved manner.
757 + */
758 + releaseLock(): void;
759 + /**
760 + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,
761 + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return
762 + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes
763 + * errored before the writing process is initiated.
764 + *
765 + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been
766 + * accepted, and not necessarily that it is safely saved to its ultimate destination.
767 + */
768 + write(chunk: W): Promise<void>;
769 +}
770 +
771 +export { }
1 +/// <reference lib="es2018.asynciterable" />
2 +
3 +/**
4 + * A signal object that allows you to communicate with a request and abort it if required
5 + * via its associated `AbortController` object.
6 + *
7 + * @remarks
8 + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.
9 + * It is redefined here, so it can be polyfilled without a DOM, for example with
10 + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.
11 + *
12 + * @public
13 + */
14 +export declare interface AbortSignal {
15 + /**
16 + * Whether the request is aborted.
17 + */
18 + readonly aborted: boolean;
19 + /**
20 + * Add an event listener to be triggered when this signal becomes aborted.
21 + */
22 + addEventListener(type: 'abort', listener: () => void): void;
23 + /**
24 + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.
25 + */
26 + removeEventListener(type: 'abort', listener: () => void): void;
27 +}
28 +
29 +/**
30 + * A queuing strategy that counts the number of bytes in each chunk.
31 + *
32 + * @public
33 + */
34 +export declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {
35 + constructor(options: QueuingStrategyInit);
36 + /**
37 + * Returns the high water mark provided to the constructor.
38 + */
39 + get highWaterMark(): number;
40 + /**
41 + * Measures the size of `chunk` by returning the value of its `byteLength` property.
42 + */
43 + get size(): (chunk: ArrayBufferView) => number;
44 +}
45 +
46 +/**
47 + * A queuing strategy that counts the number of chunks.
48 + *
49 + * @public
50 + */
51 +export declare class CountQueuingStrategy implements QueuingStrategy<any> {
52 + constructor(options: QueuingStrategyInit);
53 + /**
54 + * Returns the high water mark provided to the constructor.
55 + */
56 + get highWaterMark(): number;
57 + /**
58 + * Measures the size of `chunk` by always returning 1.
59 + * This ensures that the total queue size is a count of the number of chunks in the queue.
60 + */
61 + get size(): (chunk: any) => 1;
62 +}
63 +
64 +/**
65 + * A queuing strategy.
66 + *
67 + * @public
68 + */
69 +export declare interface QueuingStrategy<T = any> {
70 + /**
71 + * A non-negative number indicating the high water mark of the stream using this queuing strategy.
72 + */
73 + highWaterMark?: number;
74 + /**
75 + * A function that computes and returns the finite non-negative size of the given chunk value.
76 + */
77 + size?: QueuingStrategySizeCallback<T>;
78 +}
79 +
80 +/**
81 + * @public
82 + */
83 +export declare interface QueuingStrategyInit {
84 + /**
85 + * {@inheritDoc QueuingStrategy.highWaterMark}
86 + */
87 + highWaterMark: number;
88 +}
89 +
90 +declare type QueuingStrategySizeCallback<T = any> = (chunk: T) => number;
91 +
92 +declare type ReadableByteStream = ReadableStream<Uint8Array> & {
93 + _readableStreamController: ReadableByteStreamController;
94 +};
95 +
96 +/**
97 + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
98 + *
99 + * @public
100 + */
101 +export declare class ReadableByteStreamController {
102 + private constructor();
103 + /**
104 + * Returns the current BYOB pull request, or `null` if there isn't one.
105 + */
106 + get byobRequest(): ReadableStreamBYOBRequest | null;
107 + /**
108 + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
109 + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
110 + */
111 + get desiredSize(): number | null;
112 + /**
113 + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
114 + * the stream, but once those are read, the stream will become closed.
115 + */
116 + close(): void;
117 + /**
118 + * Enqueues the given chunk chunk in the controlled readable stream.
119 + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.
120 + */
121 + enqueue(chunk: ArrayBufferView): void;
122 + /**
123 + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
124 + */
125 + error(e?: any): void;
126 +}
127 +
128 +/**
129 + * A readable stream represents a source of data, from which you can read.
130 + *
131 + * @public
132 + */
133 +export declare class ReadableStream<R = any> {
134 + constructor(underlyingSource: UnderlyingByteSource, strategy?: {
135 + highWaterMark?: number;
136 + size?: undefined;
137 + });
138 + constructor(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>);
139 + /**
140 + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
141 + */
142 + get locked(): boolean;
143 + /**
144 + * Cancels the stream, signaling a loss of interest in the stream by a consumer.
145 + *
146 + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
147 + * method, which might or might not use it.
148 + */
149 + cancel(reason?: any): Promise<void>;
150 + /**
151 + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.
152 + *
153 + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,
154 + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading.
155 + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its
156 + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise
157 + * control over allocation.
158 + */
159 + getReader({ mode }: {
160 + mode: 'byob';
161 + }): ReadableStreamBYOBReader;
162 + /**
163 + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.
164 + * While the stream is locked, no other reader can be acquired until this one is released.
165 + *
166 + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream
167 + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours
168 + * or cancel the stream, which would interfere with your abstraction.
169 + */
170 + getReader(): ReadableStreamDefaultReader<R>;
171 + /**
172 + * Provides a convenient, chainable way of piping this readable stream through a transform stream
173 + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream
174 + * into the writable side of the supplied pair, and returns the readable side for further use.
175 + *
176 + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
177 + */
178 + pipeThrough<RS extends ReadableStream>(transform: {
179 + readable: RS;
180 + writable: WritableStream<R>;
181 + }, options?: StreamPipeOptions): RS;
182 + /**
183 + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under
184 + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills
185 + * when the piping process completes successfully, or rejects if any errors were encountered.
186 + *
187 + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
188 + */
189 + pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
190 + /**
191 + * Tees this readable stream, returning a two-element array containing the two resulting branches as
192 + * new {@link ReadableStream} instances.
193 + *
194 + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
195 + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
196 + * propagated to the stream's underlying source.
197 + *
198 + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
199 + * this could allow interference between the two branches.
200 + */
201 + tee(): [ReadableStream<R>, ReadableStream<R>];
202 + /**
203 + * Asynchronously iterates over the chunks in the stream's internal queue.
204 + *
205 + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.
206 + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method
207 + * is called, e.g. by breaking out of the loop.
208 + *
209 + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also
210 + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing
211 + * `true` for the `preventCancel` option.
212 + */
213 + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
214 + /**
215 + * {@inheritDoc ReadableStream.values}
216 + */
217 + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator<R>;
218 +}
219 +
220 +/**
221 + * An async iterator returned by {@link ReadableStream.values}.
222 + *
223 + * @public
224 + */
225 +export declare interface ReadableStreamAsyncIterator<R> extends AsyncIterator<R> {
226 + next(): Promise<IteratorResult<R, undefined>>;
227 + return(value?: any): Promise<IteratorResult<any>>;
228 +}
229 +
230 +/**
231 + * A BYOB reader vended by a {@link ReadableStream}.
232 + *
233 + * @public
234 + */
235 +export declare class ReadableStreamBYOBReader {
236 + constructor(stream: ReadableByteStream);
237 + /**
238 + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
239 + * the reader's lock is released before the stream finishes closing.
240 + */
241 + get closed(): Promise<undefined>;
242 + /**
243 + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
244 + */
245 + cancel(reason?: any): Promise<void>;
246 + /**
247 + * Attempts to reads bytes into view, and returns a promise resolved with the result.
248 + *
249 + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
250 + */
251 + read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamBYOBReadResult<T>>;
252 + /**
253 + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
254 + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
255 + * from now on; otherwise, the reader will appear closed.
256 + *
257 + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
258 + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
259 + * do so will throw a `TypeError` and leave the reader locked to the stream.
260 + */
261 + releaseLock(): void;
262 +}
263 +
264 +/**
265 + * A result returned by {@link ReadableStreamBYOBReader.read}.
266 + *
267 + * @public
268 + */
269 +export declare type ReadableStreamBYOBReadResult<T extends ArrayBufferView> = {
270 + done: false;
271 + value: T;
272 +} | {
273 + done: true;
274 + value: T | undefined;
275 +};
276 +
277 +/**
278 + * A pull-into request in a {@link ReadableByteStreamController}.
279 + *
280 + * @public
281 + */
282 +export declare class ReadableStreamBYOBRequest {
283 + private constructor();
284 + /**
285 + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
286 + */
287 + get view(): ArrayBufferView | null;
288 + /**
289 + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into
290 + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.
291 + *
292 + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer
293 + * modifiable.
294 + */
295 + respond(bytesWritten: number): void;
296 + /**
297 + * Indicates to the associated readable byte stream that instead of writing into
298 + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,
299 + * which will be given to the consumer of the readable byte stream.
300 + *
301 + * After this method is called, `view` will be transferred and no longer modifiable.
302 + */
303 + respondWithNewView(view: ArrayBufferView): void;
304 +}
305 +
306 +/**
307 + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
308 + *
309 + * @public
310 + */
311 +export declare class ReadableStreamDefaultController<R> {
312 + private constructor();
313 + /**
314 + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
315 + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
316 + */
317 + get desiredSize(): number | null;
318 + /**
319 + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
320 + * the stream, but once those are read, the stream will become closed.
321 + */
322 + close(): void;
323 + /**
324 + * Enqueues the given chunk `chunk` in the controlled readable stream.
325 + */
326 + enqueue(chunk: R): void;
327 + /**
328 + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
329 + */
330 + error(e?: any): void;
331 +}
332 +
333 +/**
334 + * A default reader vended by a {@link ReadableStream}.
335 + *
336 + * @public
337 + */
338 +export declare class ReadableStreamDefaultReader<R = any> {
339 + constructor(stream: ReadableStream<R>);
340 + /**
341 + * Returns a promise that will be fulfilled when the stream becomes closed,
342 + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
343 + */
344 + get closed(): Promise<undefined>;
345 + /**
346 + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
347 + */
348 + cancel(reason?: any): Promise<void>;
349 + /**
350 + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
351 + *
352 + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
353 + */
354 + read(): Promise<ReadableStreamDefaultReadResult<R>>;
355 + /**
356 + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
357 + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
358 + * from now on; otherwise, the reader will appear closed.
359 + *
360 + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
361 + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
362 + * do so will throw a `TypeError` and leave the reader locked to the stream.
363 + */
364 + releaseLock(): void;
365 +}
366 +
367 +/**
368 + * A result returned by {@link ReadableStreamDefaultReader.read}.
369 + *
370 + * @public
371 + */
372 +export declare type ReadableStreamDefaultReadResult<T> = {
373 + done: false;
374 + value: T;
375 +} | {
376 + done: true;
377 + value?: undefined;
378 +};
379 +
380 +/**
381 + * Options for {@link ReadableStream.values | async iterating} a stream.
382 + *
383 + * @public
384 + */
385 +export declare interface ReadableStreamIteratorOptions {
386 + preventCancel?: boolean;
387 +}
388 +
389 +/**
390 + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed
391 + * to {@link ReadableStream.pipeThrough}.
392 + *
393 + * @public
394 + */
395 +export declare interface ReadableWritablePair<R, W> {
396 + readable: ReadableStream<R>;
397 + writable: WritableStream<W>;
398 +}
399 +
400 +/**
401 + * Options for {@link ReadableStream.pipeTo | piping} a stream.
402 + *
403 + * @public
404 + */
405 +export declare interface StreamPipeOptions {
406 + /**
407 + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors.
408 + */
409 + preventAbort?: boolean;
410 + /**
411 + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes
412 + * or errors.
413 + */
414 + preventCancel?: boolean;
415 + /**
416 + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes.
417 + */
418 + preventClose?: boolean;
419 + /**
420 + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding
421 + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream
422 + * aborted, unless the respective options `preventCancel` or `preventAbort` are set.
423 + */
424 + signal?: AbortSignal;
425 +}
426 +
427 +/**
428 + * A transformer for constructing a {@link TransformStream}.
429 + *
430 + * @public
431 + */
432 +export declare interface Transformer<I = any, O = any> {
433 + /**
434 + * A function that is called immediately during creation of the {@link TransformStream}.
435 + */
436 + start?: TransformerStartCallback<O>;
437 + /**
438 + * A function called when a new chunk originally written to the writable side is ready to be transformed.
439 + */
440 + transform?: TransformerTransformCallback<I, O>;
441 + /**
442 + * A function called after all chunks written to the writable side have been transformed by successfully passing
443 + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed.
444 + */
445 + flush?: TransformerFlushCallback<O>;
446 + readableType?: undefined;
447 + writableType?: undefined;
448 +}
449 +
450 +/** @public */
451 +export declare type TransformerFlushCallback<O> = (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
452 +
453 +/** @public */
454 +export declare type TransformerStartCallback<O> = (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
455 +
456 +/** @public */
457 +export declare type TransformerTransformCallback<I, O> = (chunk: I, controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
458 +
459 +/**
460 + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
461 + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
462 + * In a manner specific to the transform stream in question, writes to the writable side result in new data being
463 + * made available for reading from the readable side.
464 + *
465 + * @public
466 + */
467 +export declare class TransformStream<I = any, O = any> {
468 + constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
469 + /**
470 + * The readable side of the transform stream.
471 + */
472 + get readable(): ReadableStream<O>;
473 + /**
474 + * The writable side of the transform stream.
475 + */
476 + get writable(): WritableStream<I>;
477 +}
478 +
479 +/**
480 + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
481 + *
482 + * @public
483 + */
484 +export declare class TransformStreamDefaultController<O> {
485 + private constructor();
486 + /**
487 + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
488 + */
489 + get desiredSize(): number | null;
490 + /**
491 + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.
492 + */
493 + enqueue(chunk: O): void;
494 + /**
495 + * Errors both the readable side and the writable side of the controlled transform stream, making all future
496 + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
497 + */
498 + error(reason?: any): void;
499 + /**
500 + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
501 + * transformer only needs to consume a portion of the chunks written to the writable side.
502 + */
503 + terminate(): void;
504 +}
505 +
506 +/**
507 + * An underlying byte source for constructing a {@link ReadableStream}.
508 + *
509 + * @public
510 + */
511 +export declare interface UnderlyingByteSource {
512 + /**
513 + * {@inheritDoc UnderlyingSource.start}
514 + */
515 + start?: UnderlyingByteSourceStartCallback;
516 + /**
517 + * {@inheritDoc UnderlyingSource.pull}
518 + */
519 + pull?: UnderlyingByteSourcePullCallback;
520 + /**
521 + * {@inheritDoc UnderlyingSource.cancel}
522 + */
523 + cancel?: UnderlyingSourceCancelCallback;
524 + /**
525 + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream.
526 + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its
527 + * {@link ReadableStream.(getReader:1) | getReader()} method.
528 + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()}
529 + * and {@link UnderlyingByteSource.pull | pull()} methods.
530 + */
531 + type: 'bytes';
532 + /**
533 + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the
534 + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream
535 + * implementation will automatically allocate an ArrayBuffer of the given size, so that
536 + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present,
537 + * as if the consumer was using a BYOB reader.
538 + */
539 + autoAllocateChunkSize?: number;
540 +}
541 +
542 +/** @public */
543 +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike<void>;
544 +
545 +/** @public */
546 +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike<void>;
547 +
548 +/**
549 + * An underlying sink for constructing a {@link WritableStream}.
550 + *
551 + * @public
552 + */
553 +export declare interface UnderlyingSink<W = any> {
554 + /**
555 + * A function that is called immediately during creation of the {@link WritableStream}.
556 + */
557 + start?: UnderlyingSinkStartCallback;
558 + /**
559 + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream
560 + * implementation guarantees that this function will be called only after previous writes have succeeded, and never
561 + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or
562 + * {@link UnderlyingSink.abort | abort()} have been called.
563 + *
564 + * This function is used to actually send the data to the resource presented by the underlying sink, for example by
565 + * calling a lower-level API.
566 + */
567 + write?: UnderlyingSinkWriteCallback<W>;
568 + /**
569 + * A function that is called after the producer signals, via
570 + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and
571 + * subsequently all queued-up writes have successfully completed.
572 + *
573 + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release
574 + * access to any held resources.
575 + */
576 + close?: UnderlyingSinkCloseCallback;
577 + /**
578 + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or
579 + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its
580 + * argument the same value as was passed to those methods by the producer.
581 + *
582 + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the
583 + * {@link ReadableStream.pipeTo | pipeTo()} method for more details.
584 + *
585 + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with
586 + * some custom handling.
587 + */
588 + abort?: UnderlyingSinkAbortCallback;
589 + type?: undefined;
590 +}
591 +
592 +/** @public */
593 +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike<void>;
594 +
595 +/** @public */
596 +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike<void>;
597 +
598 +/** @public */
599 +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike<void>;
600 +
601 +/** @public */
602 +export declare type UnderlyingSinkWriteCallback<W> = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike<void>;
603 +
604 +/**
605 + * An underlying source for constructing a {@link ReadableStream}.
606 + *
607 + * @public
608 + */
609 +export declare interface UnderlyingSource<R = any> {
610 + /**
611 + * A function that is called immediately during creation of the {@link ReadableStream}.
612 + */
613 + start?: UnderlyingSourceStartCallback<R>;
614 + /**
615 + * A function that is called whenever the stream’s internal queue of chunks becomes not full,
616 + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly
617 + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive).
618 + */
619 + pull?: UnderlyingSourcePullCallback<R>;
620 + /**
621 + * A function that is called whenever the consumer cancels the stream, via
622 + * {@link ReadableStream.cancel | stream.cancel()},
623 + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or
624 + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}.
625 + * It takes as its argument the same value as was passed to those methods by the consumer.
626 + */
627 + cancel?: UnderlyingSourceCancelCallback;
628 + type?: undefined;
629 +}
630 +
631 +/** @public */
632 +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike<void>;
633 +
634 +/** @public */
635 +export declare type UnderlyingSourcePullCallback<R> = (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
636 +
637 +/** @public */
638 +export declare type UnderlyingSourceStartCallback<R> = (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
639 +
640 +/**
641 + * A writable stream represents a destination for data, into which you can write.
642 + *
643 + * @public
644 + */
645 +export declare class WritableStream<W = any> {
646 + constructor(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>);
647 + /**
648 + * Returns whether or not the writable stream is locked to a writer.
649 + */
650 + get locked(): boolean;
651 + /**
652 + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
653 + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
654 + * mechanism of the underlying sink.
655 + *
656 + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
657 + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
658 + * the stream) if the stream is currently locked.
659 + */
660 + abort(reason?: any): Promise<void>;
661 + /**
662 + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
663 + * close behavior. During this time any further attempts to write will fail (without erroring the stream).
664 + *
665 + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
666 + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
667 + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
668 + */
669 + close(): Promise<undefined>;
670 + /**
671 + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
672 + * is locked, no other writer can be acquired until this one is released.
673 + *
674 + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
675 + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
676 + * the same time, which would cause the resulting written data to be unpredictable and probably useless.
677 + */
678 + getWriter(): WritableStreamDefaultWriter<W>;
679 +}
680 +
681 +/**
682 + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
683 + *
684 + * @public
685 + */
686 +export declare class WritableStreamDefaultController<W = any> {
687 + private constructor();
688 + /**
689 + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
690 + *
691 + * @deprecated
692 + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
693 + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
694 + */
695 + get abortReason(): any;
696 + /**
697 + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
698 + */
699 + get signal(): AbortSignal;
700 + /**
701 + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
702 + *
703 + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
704 + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
705 + * normal lifecycle of interactions with the underlying sink.
706 + */
707 + error(e?: any): void;
708 +}
709 +
710 +/**
711 + * A default writer vended by a {@link WritableStream}.
712 + *
713 + * @public
714 + */
715 +export declare class WritableStreamDefaultWriter<W = any> {
716 + constructor(stream: WritableStream<W>);
717 + /**
718 + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
719 + * the writer’s lock is released before the stream finishes closing.
720 + */
721 + get closed(): Promise<undefined>;
722 + /**
723 + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
724 + * A producer can use this information to determine the right amount of data to write.
725 + *
726 + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
727 + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
728 + * the writer’s lock is released.
729 + */
730 + get desiredSize(): number | null;
731 + /**
732 + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
733 + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
734 + * back to zero or below, the getter will return a new promise that stays pending until the next transition.
735 + *
736 + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
737 + * rejected.
738 + */
739 + get ready(): Promise<undefined>;
740 + /**
741 + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
742 + */
743 + abort(reason?: any): Promise<void>;
744 + /**
745 + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
746 + */
747 + close(): Promise<void>;
748 + /**
749 + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
750 + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
751 + * now on; otherwise, the writer will appear closed.
752 + *
753 + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
754 + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
755 + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
756 + * other producers from writing in an interleaved manner.
757 + */
758 + releaseLock(): void;
759 + /**
760 + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,
761 + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return
762 + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes
763 + * errored before the writing process is initiated.
764 + *
765 + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been
766 + * accepted, and not necessarily that it is safely saved to its ultimate destination.
767 + */
768 + write(chunk: W): Promise<void>;
769 +}
770 +
771 +export { }
1 +// This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2 +// It should be published with your NPM package. It should not be tracked by Git.
3 +{
4 + "tsdocVersion": "0.12",
5 + "toolPackages": [
6 + {
7 + "packageName": "@microsoft/api-extractor",
8 + "packageVersion": "7.13.4"
9 + }
10 + ]
11 +}
1 +{
2 + "name": "web-streams-polyfill-es2018",
3 + "main": "../dist/polyfill.es2018",
4 + "browser": "../dist/polyfill.es2018.min.js",
5 + "module": "../dist/polyfill.es2018.mjs",
6 + "types": "../dist/types/polyfill.d.ts"
7 +}
1 +{
2 + "name": "web-streams-polyfill-es6",
3 + "main": "../dist/polyfill.es6",
4 + "browser": "../dist/polyfill.es6.min.js",
5 + "module": "../dist/polyfill.es6.mjs",
6 + "types": "../dist/types/polyfill.d.ts"
7 +}
1 +{
2 + "name": "web-streams-polyfill",
3 + "version": "3.2.1",
4 + "description": "Web Streams, based on the WHATWG spec reference implementation",
5 + "main": "dist/polyfill",
6 + "browser": "dist/polyfill.min.js",
7 + "module": "dist/polyfill.mjs",
8 + "types": "dist/types/polyfill.d.ts",
9 + "typesVersions": {
10 + ">=3.6": {
11 + "dist/types/*": [
12 + "dist/types/ts3.6/*"
13 + ]
14 + }
15 + },
16 + "scripts": {
17 + "test": "npm run test:types && npm run test:unit && npm run test:wpt",
18 + "test:wpt": "node --expose_gc ./test/run-web-platform-tests.js",
19 + "pretest:wpt": "git submodule update --init --recursive",
20 + "test:types": "tsc -p ./test/types/tsconfig.json",
21 + "test:unit": "jasmine --config=test/unit/jasmine.json",
22 + "lint": "eslint \"src/**/*.ts\"",
23 + "build": "npm run build:bundle && npm run build:types",
24 + "build:bundle": "rollup -c",
25 + "build:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run && node ./build/downlevel-dts.js",
26 + "accept:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run --local && node ./build/downlevel-dts.js",
27 + "prepare": "npm run build"
28 + },
29 + "files": [
30 + "dist",
31 + "es6",
32 + "es2018",
33 + "ponyfill"
34 + ],
35 + "engines": {
36 + "node": ">= 8"
37 + },
38 + "repository": {
39 + "type": "git",
40 + "url": "git+https://github.com/MattiasBuelens/web-streams-polyfill.git"
41 + },
42 + "keywords": [
43 + "streams",
44 + "whatwg",
45 + "polyfill"
46 + ],
47 + "author": "Mattias Buelens <mattias@buelens.com>",
48 + "contributors": [
49 + "Diwank Singh <diwank.singh@gmail.com>"
50 + ],
51 + "license": "MIT",
52 + "bugs": {
53 + "url": "https://github.com/MattiasBuelens/web-streams-polyfill/issues"
54 + },
55 + "homepage": "https://github.com/MattiasBuelens/web-streams-polyfill#readme",
56 + "devDependencies": {
57 + "@microsoft/api-extractor": "^7.13.4",
58 + "@rollup/plugin-inject": "^4.0.2",
59 + "@rollup/plugin-replace": "^2.4.2",
60 + "@rollup/plugin-strip": "^2.0.0",
61 + "@rollup/plugin-typescript": "^8.2.1",
62 + "@types/node": "^14.14.37",
63 + "@typescript-eslint/eslint-plugin": "^4.21.0",
64 + "@typescript-eslint/parser": "^4.21.0",
65 + "@ungap/promise-all-settled": "^1.1.2",
66 + "eslint": "^7.23.0",
67 + "jasmine": "^3.7.0",
68 + "micromatch": "^4.0.2",
69 + "rollup": "^2.44.0",
70 + "rollup-plugin-terser": "^7.0.2",
71 + "ts-morph": "^10.0.2",
72 + "tslib": "^2.2.0",
73 + "typescript": "^4.2.4",
74 + "wpt-runner": "^3.2.1"
75 + }
76 +}
1 +{
2 + "name": "web-streams-ponyfill-es2018",
3 + "main": "../../dist/ponyfill.es2018",
4 + "module": "../../dist/ponyfill.es2018.mjs",
5 + "types": "../../dist/types/polyfill.d.ts"
6 +}
1 +{
2 + "name": "web-streams-ponyfill-es6",
3 + "main": "../../dist/ponyfill.es6",
4 + "module": "../../dist/ponyfill.es6.mjs",
5 + "types": "../../dist/types/polyfill.d.ts"
6 +}
1 +{
2 + "name": "web-streams-ponyfill",
3 + "main": "../dist/ponyfill",
4 + "module": "../dist/ponyfill.mjs",
5 + "types": "../dist/types/polyfill.d.ts"
6 +}
...@@ -9,8 +9,8 @@ ...@@ -9,8 +9,8 @@
9 "version": "1.0.0", 9 "version": "1.0.0",
10 "license": "ISC", 10 "license": "ISC",
11 "dependencies": { 11 "dependencies": {
12 - "axios": "^0.27.2", 12 + "discord.js": "^12.5.3",
13 - "discord.js": "^12.5.3" 13 + "node-fetch": "^3.2.4"
14 } 14 }
15 }, 15 },
16 "node_modules/@discordjs/collection": { 16 "node_modules/@discordjs/collection": {
...@@ -47,15 +47,6 @@ ...@@ -47,15 +47,6 @@
47 "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", 47 "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
48 "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" 48 "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
49 }, 49 },
50 - "node_modules/axios": {
51 - "version": "0.27.2",
52 - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz",
53 - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==",
54 - "dependencies": {
55 - "follow-redirects": "^1.14.9",
56 - "form-data": "^4.0.0"
57 - }
58 - },
59 "node_modules/combined-stream": { 50 "node_modules/combined-stream": {
60 "version": "1.0.8", 51 "version": "1.0.8",
61 "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", 52 "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
...@@ -67,6 +58,14 @@ ...@@ -67,6 +58,14 @@
67 "node": ">= 0.8" 58 "node": ">= 0.8"
68 } 59 }
69 }, 60 },
61 + "node_modules/data-uri-to-buffer": {
62 + "version": "4.0.0",
63 + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.0.tgz",
64 + "integrity": "sha512-Vr3mLBA8qWmcuschSLAOogKgQ/Jwxulv3RNE4FXnYWRGujzrRWQI4m12fQqRkwX06C0KanhLr4hK+GydchZsaA==",
65 + "engines": {
66 + "node": ">= 12"
67 + }
68 + },
70 "node_modules/delayed-stream": { 69 "node_modules/delayed-stream": {
71 "version": "1.0.0", 70 "version": "1.0.0",
72 "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", 71 "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
...@@ -94,6 +93,25 @@ ...@@ -94,6 +93,25 @@
94 "node": ">=12.0.0" 93 "node": ">=12.0.0"
95 } 94 }
96 }, 95 },
96 + "node_modules/discord.js/node_modules/node-fetch": {
97 + "version": "2.6.7",
98 + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
99 + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
100 + "dependencies": {
101 + "whatwg-url": "^5.0.0"
102 + },
103 + "engines": {
104 + "node": "4.x || >=6.0.0"
105 + },
106 + "peerDependencies": {
107 + "encoding": "^0.1.0"
108 + },
109 + "peerDependenciesMeta": {
110 + "encoding": {
111 + "optional": true
112 + }
113 + }
114 + },
97 "node_modules/event-target-shim": { 115 "node_modules/event-target-shim": {
98 "version": "5.0.1", 116 "version": "5.0.1",
99 "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", 117 "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
...@@ -102,36 +120,37 @@ ...@@ -102,36 +120,37 @@
102 "node": ">=6" 120 "node": ">=6"
103 } 121 }
104 }, 122 },
105 - "node_modules/follow-redirects": { 123 + "node_modules/fetch-blob": {
106 - "version": "1.15.1", 124 + "version": "3.1.5",
107 - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz", 125 + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.1.5.tgz",
108 - "integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==", 126 + "integrity": "sha512-N64ZpKqoLejlrwkIAnb9iLSA3Vx/kjgzpcDhygcqJ2KKjky8nCgUQ+dzXtbrLaWZGZNmNfQTsiQ0weZ1svglHg==",
109 "funding": [ 127 "funding": [
110 { 128 {
111 - "type": "individual", 129 + "type": "github",
112 - "url": "https://github.com/sponsors/RubenVerborgh" 130 + "url": "https://github.com/sponsors/jimmywarting"
131 + },
132 + {
133 + "type": "paypal",
134 + "url": "https://paypal.me/jimmywarting"
113 } 135 }
114 ], 136 ],
115 - "engines": { 137 + "dependencies": {
116 - "node": ">=4.0" 138 + "node-domexception": "^1.0.0",
139 + "web-streams-polyfill": "^3.0.3"
117 }, 140 },
118 - "peerDependenciesMeta": { 141 + "engines": {
119 - "debug": { 142 + "node": "^12.20 || >= 14.13"
120 - "optional": true
121 - }
122 } 143 }
123 }, 144 },
124 - "node_modules/form-data": { 145 + "node_modules/formdata-polyfill": {
125 - "version": "4.0.0", 146 + "version": "4.0.10",
126 - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", 147 + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
127 - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", 148 + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
128 "dependencies": { 149 "dependencies": {
129 - "asynckit": "^0.4.0", 150 + "fetch-blob": "^3.1.2"
130 - "combined-stream": "^1.0.8",
131 - "mime-types": "^2.1.12"
132 }, 151 },
133 "engines": { 152 "engines": {
134 - "node": ">= 6" 153 + "node": ">=12.20.0"
135 } 154 }
136 }, 155 },
137 "node_modules/mime-db": { 156 "node_modules/mime-db": {
...@@ -153,23 +172,39 @@ ...@@ -153,23 +172,39 @@
153 "node": ">= 0.6" 172 "node": ">= 0.6"
154 } 173 }
155 }, 174 },
175 + "node_modules/node-domexception": {
176 + "version": "1.0.0",
177 + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
178 + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
179 + "funding": [
180 + {
181 + "type": "github",
182 + "url": "https://github.com/sponsors/jimmywarting"
183 + },
184 + {
185 + "type": "github",
186 + "url": "https://paypal.me/jimmywarting"
187 + }
188 + ],
189 + "engines": {
190 + "node": ">=10.5.0"
191 + }
192 + },
156 "node_modules/node-fetch": { 193 "node_modules/node-fetch": {
157 - "version": "2.6.7", 194 + "version": "3.2.4",
158 - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", 195 + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.2.4.tgz",
159 - "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", 196 + "integrity": "sha512-WvYJRN7mMyOLurFR2YpysQGuwYrJN+qrrpHjJDuKMcSPdfFccRUla/kng2mz6HWSBxJcqPbvatS6Gb4RhOzCJw==",
160 "dependencies": { 197 "dependencies": {
161 - "whatwg-url": "^5.0.0" 198 + "data-uri-to-buffer": "^4.0.0",
199 + "fetch-blob": "^3.1.4",
200 + "formdata-polyfill": "^4.0.10"
162 }, 201 },
163 "engines": { 202 "engines": {
164 - "node": "4.x || >=6.0.0" 203 + "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
165 }, 204 },
166 - "peerDependencies": { 205 + "funding": {
167 - "encoding": "^0.1.0" 206 + "type": "opencollective",
168 - }, 207 + "url": "https://opencollective.com/node-fetch"
169 - "peerDependenciesMeta": {
170 - "encoding": {
171 - "optional": true
172 - }
173 } 208 }
174 }, 209 },
175 "node_modules/prism-media": { 210 "node_modules/prism-media": {
...@@ -212,6 +247,14 @@ ...@@ -212,6 +247,14 @@
212 "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", 247 "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
213 "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" 248 "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw=="
214 }, 249 },
250 + "node_modules/web-streams-polyfill": {
251 + "version": "3.2.1",
252 + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz",
253 + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==",
254 + "engines": {
255 + "node": ">= 8"
256 + }
257 + },
215 "node_modules/webidl-conversions": { 258 "node_modules/webidl-conversions": {
216 "version": "3.0.1", 259 "version": "3.0.1",
217 "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", 260 "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
...@@ -276,15 +319,6 @@ ...@@ -276,15 +319,6 @@
276 "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", 319 "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
277 "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" 320 "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
278 }, 321 },
279 - "axios": {
280 - "version": "0.27.2",
281 - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz",
282 - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==",
283 - "requires": {
284 - "follow-redirects": "^1.14.9",
285 - "form-data": "^4.0.0"
286 - }
287 - },
288 "combined-stream": { 322 "combined-stream": {
289 "version": "1.0.8", 323 "version": "1.0.8",
290 "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", 324 "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
...@@ -293,6 +327,11 @@ ...@@ -293,6 +327,11 @@
293 "delayed-stream": "~1.0.0" 327 "delayed-stream": "~1.0.0"
294 } 328 }
295 }, 329 },
330 + "data-uri-to-buffer": {
331 + "version": "4.0.0",
332 + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.0.tgz",
333 + "integrity": "sha512-Vr3mLBA8qWmcuschSLAOogKgQ/Jwxulv3RNE4FXnYWRGujzrRWQI4m12fQqRkwX06C0KanhLr4hK+GydchZsaA=="
334 + },
296 "delayed-stream": { 335 "delayed-stream": {
297 "version": "1.0.0", 336 "version": "1.0.0",
298 "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", 337 "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
...@@ -311,6 +350,16 @@ ...@@ -311,6 +350,16 @@
311 "setimmediate": "^1.0.5", 350 "setimmediate": "^1.0.5",
312 "tweetnacl": "^1.0.3", 351 "tweetnacl": "^1.0.3",
313 "ws": "^7.4.4" 352 "ws": "^7.4.4"
353 + },
354 + "dependencies": {
355 + "node-fetch": {
356 + "version": "2.6.7",
357 + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
358 + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
359 + "requires": {
360 + "whatwg-url": "^5.0.0"
361 + }
362 + }
314 } 363 }
315 }, 364 },
316 "event-target-shim": { 365 "event-target-shim": {
...@@ -318,19 +367,21 @@ ...@@ -318,19 +367,21 @@
318 "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", 367 "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
319 "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==" 368 "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="
320 }, 369 },
321 - "follow-redirects": { 370 + "fetch-blob": {
322 - "version": "1.15.1", 371 + "version": "3.1.5",
323 - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz", 372 + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.1.5.tgz",
324 - "integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==" 373 + "integrity": "sha512-N64ZpKqoLejlrwkIAnb9iLSA3Vx/kjgzpcDhygcqJ2KKjky8nCgUQ+dzXtbrLaWZGZNmNfQTsiQ0weZ1svglHg==",
374 + "requires": {
375 + "node-domexception": "^1.0.0",
376 + "web-streams-polyfill": "^3.0.3"
377 + }
325 }, 378 },
326 - "form-data": { 379 + "formdata-polyfill": {
327 - "version": "4.0.0", 380 + "version": "4.0.10",
328 - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", 381 + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
329 - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", 382 + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
330 "requires": { 383 "requires": {
331 - "asynckit": "^0.4.0", 384 + "fetch-blob": "^3.1.2"
332 - "combined-stream": "^1.0.8",
333 - "mime-types": "^2.1.12"
334 } 385 }
335 }, 386 },
336 "mime-db": { 387 "mime-db": {
...@@ -346,12 +397,19 @@ ...@@ -346,12 +397,19 @@
346 "mime-db": "1.52.0" 397 "mime-db": "1.52.0"
347 } 398 }
348 }, 399 },
400 + "node-domexception": {
401 + "version": "1.0.0",
402 + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
403 + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="
404 + },
349 "node-fetch": { 405 "node-fetch": {
350 - "version": "2.6.7", 406 + "version": "3.2.4",
351 - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", 407 + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.2.4.tgz",
352 - "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", 408 + "integrity": "sha512-WvYJRN7mMyOLurFR2YpysQGuwYrJN+qrrpHjJDuKMcSPdfFccRUla/kng2mz6HWSBxJcqPbvatS6Gb4RhOzCJw==",
353 "requires": { 409 "requires": {
354 - "whatwg-url": "^5.0.0" 410 + "data-uri-to-buffer": "^4.0.0",
411 + "fetch-blob": "^3.1.4",
412 + "formdata-polyfill": "^4.0.10"
355 } 413 }
356 }, 414 },
357 "prism-media": { 415 "prism-media": {
...@@ -375,6 +433,11 @@ ...@@ -375,6 +433,11 @@
375 "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", 433 "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
376 "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" 434 "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw=="
377 }, 435 },
436 + "web-streams-polyfill": {
437 + "version": "3.2.1",
438 + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz",
439 + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q=="
440 + },
378 "webidl-conversions": { 441 "webidl-conversions": {
379 "version": "3.0.1", 442 "version": "3.0.1",
380 "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", 443 "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
......
...@@ -3,13 +3,14 @@ ...@@ -3,13 +3,14 @@
3 "version": "1.0.0", 3 "version": "1.0.0",
4 "description": "Anxiety Manager discord bot", 4 "description": "Anxiety Manager discord bot",
5 "main": "main.js", 5 "main": "main.js",
6 + "type": "module",
6 "scripts": { 7 "scripts": {
7 "test": "echo \"Error: no test specified\" && exit 1" 8 "test": "echo \"Error: no test specified\" && exit 1"
8 }, 9 },
9 "author": "sab", 10 "author": "sab",
10 "license": "ISC", 11 "license": "ISC",
11 "dependencies": { 12 "dependencies": {
12 - "axios": "^0.27.2", 13 + "discord.js": "^12.5.3",
13 - "discord.js": "^12.5.3" 14 + "node-fetch": "^3.2.4"
14 } 15 }
15 } 16 }
......