b4756f32 by RSA

node_modules rm

1 parent 22599c8e
Showing 581 changed files with 1 additions and 4801 deletions
1 node_modules
...\ No newline at end of file ...\ No newline at end of file
1 #!/bin/sh
2 basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3
4 case `uname` in
5 *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
6 esac
7
8 if [ -x "$basedir/node" ]; then
9 "$basedir/node" "$basedir/../mime/cli.js" "$@"
10 ret=$?
11 else
12 node "$basedir/../mime/cli.js" "$@"
13 ret=$?
14 fi
15 exit $ret
1 @ECHO off
2 SETLOCAL
3 CALL :find_dp0
4
5 IF EXIST "%dp0%\node.exe" (
6 SET "_prog=%dp0%\node.exe"
7 ) ELSE (
8 SET "_prog=node"
9 SET PATHEXT=%PATHEXT:;.JS;=;%
10 )
11
12 "%_prog%" "%dp0%\..\mime\cli.js" %*
13 ENDLOCAL
14 EXIT /b %errorlevel%
15 :find_dp0
16 SET dp0=%~dp0
17 EXIT /b
1 #!/usr/bin/env pwsh
2 $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
3
4 $exe=""
5 if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
6 # Fix case when both the Windows and Linux builds of Node
7 # are installed in the same directory
8 $exe=".exe"
9 }
10 $ret=0
11 if (Test-Path "$basedir/node$exe") {
12 & "$basedir/node$exe" "$basedir/../mime/cli.js" $args
13 $ret=$LASTEXITCODE
14 } else {
15 & "node$exe" "$basedir/../mime/cli.js" $args
16 $ret=$LASTEXITCODE
17 }
18 exit $ret
1 1.3.8 / 2022-02-02
2 ==================
3
4 * deps: mime-types@~2.1.34
5 - deps: mime-db@~1.51.0
6 * deps: negotiator@0.6.3
7
8 1.3.7 / 2019-04-29
9 ==================
10
11 * deps: negotiator@0.6.2
12 - Fix sorting charset, encoding, and language with extra parameters
13
14 1.3.6 / 2019-04-28
15 ==================
16
17 * deps: mime-types@~2.1.24
18 - deps: mime-db@~1.40.0
19
20 1.3.5 / 2018-02-28
21 ==================
22
23 * deps: mime-types@~2.1.18
24 - deps: mime-db@~1.33.0
25
26 1.3.4 / 2017-08-22
27 ==================
28
29 * deps: mime-types@~2.1.16
30 - deps: mime-db@~1.29.0
31
32 1.3.3 / 2016-05-02
33 ==================
34
35 * deps: mime-types@~2.1.11
36 - deps: mime-db@~1.23.0
37 * deps: negotiator@0.6.1
38 - perf: improve `Accept` parsing speed
39 - perf: improve `Accept-Charset` parsing speed
40 - perf: improve `Accept-Encoding` parsing speed
41 - perf: improve `Accept-Language` parsing speed
42
43 1.3.2 / 2016-03-08
44 ==================
45
46 * deps: mime-types@~2.1.10
47 - Fix extension of `application/dash+xml`
48 - Update primary extension for `audio/mp4`
49 - deps: mime-db@~1.22.0
50
51 1.3.1 / 2016-01-19
52 ==================
53
54 * deps: mime-types@~2.1.9
55 - deps: mime-db@~1.21.0
56
57 1.3.0 / 2015-09-29
58 ==================
59
60 * deps: mime-types@~2.1.7
61 - deps: mime-db@~1.19.0
62 * deps: negotiator@0.6.0
63 - Fix including type extensions in parameters in `Accept` parsing
64 - Fix parsing `Accept` parameters with quoted equals
65 - Fix parsing `Accept` parameters with quoted semicolons
66 - Lazy-load modules from main entry point
67 - perf: delay type concatenation until needed
68 - perf: enable strict mode
69 - perf: hoist regular expressions
70 - perf: remove closures getting spec properties
71 - perf: remove a closure from media type parsing
72 - perf: remove property delete from media type parsing
73
74 1.2.13 / 2015-09-06
75 ===================
76
77 * deps: mime-types@~2.1.6
78 - deps: mime-db@~1.18.0
79
80 1.2.12 / 2015-07-30
81 ===================
82
83 * deps: mime-types@~2.1.4
84 - deps: mime-db@~1.16.0
85
86 1.2.11 / 2015-07-16
87 ===================
88
89 * deps: mime-types@~2.1.3
90 - deps: mime-db@~1.15.0
91
92 1.2.10 / 2015-07-01
93 ===================
94
95 * deps: mime-types@~2.1.2
96 - deps: mime-db@~1.14.0
97
98 1.2.9 / 2015-06-08
99 ==================
100
101 * deps: mime-types@~2.1.1
102 - perf: fix deopt during mapping
103
104 1.2.8 / 2015-06-07
105 ==================
106
107 * deps: mime-types@~2.1.0
108 - deps: mime-db@~1.13.0
109 * perf: avoid argument reassignment & argument slice
110 * perf: avoid negotiator recursive construction
111 * perf: enable strict mode
112 * perf: remove unnecessary bitwise operator
113
114 1.2.7 / 2015-05-10
115 ==================
116
117 * deps: negotiator@0.5.3
118 - Fix media type parameter matching to be case-insensitive
119
120 1.2.6 / 2015-05-07
121 ==================
122
123 * deps: mime-types@~2.0.11
124 - deps: mime-db@~1.9.1
125 * deps: negotiator@0.5.2
126 - Fix comparing media types with quoted values
127 - Fix splitting media types with quoted commas
128
129 1.2.5 / 2015-03-13
130 ==================
131
132 * deps: mime-types@~2.0.10
133 - deps: mime-db@~1.8.0
134
135 1.2.4 / 2015-02-14
136 ==================
137
138 * Support Node.js 0.6
139 * deps: mime-types@~2.0.9
140 - deps: mime-db@~1.7.0
141 * deps: negotiator@0.5.1
142 - Fix preference sorting to be stable for long acceptable lists
143
144 1.2.3 / 2015-01-31
145 ==================
146
147 * deps: mime-types@~2.0.8
148 - deps: mime-db@~1.6.0
149
150 1.2.2 / 2014-12-30
151 ==================
152
153 * deps: mime-types@~2.0.7
154 - deps: mime-db@~1.5.0
155
156 1.2.1 / 2014-12-30
157 ==================
158
159 * deps: mime-types@~2.0.5
160 - deps: mime-db@~1.3.1
161
162 1.2.0 / 2014-12-19
163 ==================
164
165 * deps: negotiator@0.5.0
166 - Fix list return order when large accepted list
167 - Fix missing identity encoding when q=0 exists
168 - Remove dynamic building of Negotiator class
169
170 1.1.4 / 2014-12-10
171 ==================
172
173 * deps: mime-types@~2.0.4
174 - deps: mime-db@~1.3.0
175
176 1.1.3 / 2014-11-09
177 ==================
178
179 * deps: mime-types@~2.0.3
180 - deps: mime-db@~1.2.0
181
182 1.1.2 / 2014-10-14
183 ==================
184
185 * deps: negotiator@0.4.9
186 - Fix error when media type has invalid parameter
187
188 1.1.1 / 2014-09-28
189 ==================
190
191 * deps: mime-types@~2.0.2
192 - deps: mime-db@~1.1.0
193 * deps: negotiator@0.4.8
194 - Fix all negotiations to be case-insensitive
195 - Stable sort preferences of same quality according to client order
196
197 1.1.0 / 2014-09-02
198 ==================
199
200 * update `mime-types`
201
202 1.0.7 / 2014-07-04
203 ==================
204
205 * Fix wrong type returned from `type` when match after unknown extension
206
207 1.0.6 / 2014-06-24
208 ==================
209
210 * deps: negotiator@0.4.7
211
212 1.0.5 / 2014-06-20
213 ==================
214
215 * fix crash when unknown extension given
216
217 1.0.4 / 2014-06-19
218 ==================
219
220 * use `mime-types`
221
222 1.0.3 / 2014-06-11
223 ==================
224
225 * deps: negotiator@0.4.6
226 - Order by specificity when quality is the same
227
228 1.0.2 / 2014-05-29
229 ==================
230
231 * Fix interpretation when header not in request
232 * deps: pin negotiator@0.4.5
233
234 1.0.1 / 2014-01-18
235 ==================
236
237 * Identity encoding isn't always acceptable
238 * deps: negotiator@~0.4.0
239
240 1.0.0 / 2013-12-27
241 ==================
242
243 * Genesis
1 (The MIT License)
2
3 Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
4 Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
5
6 Permission is hereby granted, free of charge, to any person obtaining
7 a copy of this software and associated documentation files (the
8 'Software'), to deal in the Software without restriction, including
9 without limitation the rights to use, copy, modify, merge, publish,
10 distribute, sublicense, and/or sell copies of the Software, and to
11 permit persons to whom the Software is furnished to do so, subject to
12 the following conditions:
13
14 The above copyright notice and this permission notice shall be
15 included in all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
18 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 # accepts
2
3 [![NPM Version][npm-version-image]][npm-url]
4 [![NPM Downloads][npm-downloads-image]][npm-url]
5 [![Node.js Version][node-version-image]][node-version-url]
6 [![Build Status][github-actions-ci-image]][github-actions-ci-url]
7 [![Test Coverage][coveralls-image]][coveralls-url]
8
9 Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
10 Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
11
12 In addition to negotiator, it allows:
13
14 - Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
15 as well as `('text/html', 'application/json')`.
16 - Allows type shorthands such as `json`.
17 - Returns `false` when no types match
18 - Treats non-existent headers as `*`
19
20 ## Installation
21
22 This is a [Node.js](https://nodejs.org/en/) module available through the
23 [npm registry](https://www.npmjs.com/). Installation is done using the
24 [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
25
26 ```sh
27 $ npm install accepts
28 ```
29
30 ## API
31
32 ```js
33 var accepts = require('accepts')
34 ```
35
36 ### accepts(req)
37
38 Create a new `Accepts` object for the given `req`.
39
40 #### .charset(charsets)
41
42 Return the first accepted charset. If nothing in `charsets` is accepted,
43 then `false` is returned.
44
45 #### .charsets()
46
47 Return the charsets that the request accepts, in the order of the client's
48 preference (most preferred first).
49
50 #### .encoding(encodings)
51
52 Return the first accepted encoding. If nothing in `encodings` is accepted,
53 then `false` is returned.
54
55 #### .encodings()
56
57 Return the encodings that the request accepts, in the order of the client's
58 preference (most preferred first).
59
60 #### .language(languages)
61
62 Return the first accepted language. If nothing in `languages` is accepted,
63 then `false` is returned.
64
65 #### .languages()
66
67 Return the languages that the request accepts, in the order of the client's
68 preference (most preferred first).
69
70 #### .type(types)
71
72 Return the first accepted type (and it is returned as the same text as what
73 appears in the `types` array). If nothing in `types` is accepted, then `false`
74 is returned.
75
76 The `types` array can contain full MIME types or file extensions. Any value
77 that is not a full MIME types is passed to `require('mime-types').lookup`.
78
79 #### .types()
80
81 Return the types that the request accepts, in the order of the client's
82 preference (most preferred first).
83
84 ## Examples
85
86 ### Simple type negotiation
87
88 This simple example shows how to use `accepts` to return a different typed
89 respond body based on what the client wants to accept. The server lists it's
90 preferences in order and will get back the best match between the client and
91 server.
92
93 ```js
94 var accepts = require('accepts')
95 var http = require('http')
96
97 function app (req, res) {
98 var accept = accepts(req)
99
100 // the order of this list is significant; should be server preferred order
101 switch (accept.type(['json', 'html'])) {
102 case 'json':
103 res.setHeader('Content-Type', 'application/json')
104 res.write('{"hello":"world!"}')
105 break
106 case 'html':
107 res.setHeader('Content-Type', 'text/html')
108 res.write('<b>hello, world!</b>')
109 break
110 default:
111 // the fallback is text/plain, so no need to specify it above
112 res.setHeader('Content-Type', 'text/plain')
113 res.write('hello, world!')
114 break
115 }
116
117 res.end()
118 }
119
120 http.createServer(app).listen(3000)
121 ```
122
123 You can test this out with the cURL program:
124 ```sh
125 curl -I -H'Accept: text/html' http://localhost:3000/
126 ```
127
128 ## License
129
130 [MIT](LICENSE)
131
132 [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
133 [coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
134 [github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
135 [github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
136 [node-version-image]: https://badgen.net/npm/node/accepts
137 [node-version-url]: https://nodejs.org/en/download
138 [npm-downloads-image]: https://badgen.net/npm/dm/accepts
139 [npm-url]: https://npmjs.org/package/accepts
140 [npm-version-image]: https://badgen.net/npm/v/accepts
1 /*!
2 * accepts
3 * Copyright(c) 2014 Jonathan Ong
4 * Copyright(c) 2015 Douglas Christopher Wilson
5 * MIT Licensed
6 */
7
8 'use strict'
9
10 /**
11 * Module dependencies.
12 * @private
13 */
14
15 var Negotiator = require('negotiator')
16 var mime = require('mime-types')
17
18 /**
19 * Module exports.
20 * @public
21 */
22
23 module.exports = Accepts
24
25 /**
26 * Create a new Accepts object for the given req.
27 *
28 * @param {object} req
29 * @public
30 */
31
32 function Accepts (req) {
33 if (!(this instanceof Accepts)) {
34 return new Accepts(req)
35 }
36
37 this.headers = req.headers
38 this.negotiator = new Negotiator(req)
39 }
40
41 /**
42 * Check if the given `type(s)` is acceptable, returning
43 * the best match when true, otherwise `undefined`, in which
44 * case you should respond with 406 "Not Acceptable".
45 *
46 * The `type` value may be a single mime type string
47 * such as "application/json", the extension name
48 * such as "json" or an array `["json", "html", "text/plain"]`. When a list
49 * or array is given the _best_ match, if any is returned.
50 *
51 * Examples:
52 *
53 * // Accept: text/html
54 * this.types('html');
55 * // => "html"
56 *
57 * // Accept: text/*, application/json
58 * this.types('html');
59 * // => "html"
60 * this.types('text/html');
61 * // => "text/html"
62 * this.types('json', 'text');
63 * // => "json"
64 * this.types('application/json');
65 * // => "application/json"
66 *
67 * // Accept: text/*, application/json
68 * this.types('image/png');
69 * this.types('png');
70 * // => undefined
71 *
72 * // Accept: text/*;q=.5, application/json
73 * this.types(['html', 'json']);
74 * this.types('html', 'json');
75 * // => "json"
76 *
77 * @param {String|Array} types...
78 * @return {String|Array|Boolean}
79 * @public
80 */
81
82 Accepts.prototype.type =
83 Accepts.prototype.types = function (types_) {
84 var types = types_
85
86 // support flattened arguments
87 if (types && !Array.isArray(types)) {
88 types = new Array(arguments.length)
89 for (var i = 0; i < types.length; i++) {
90 types[i] = arguments[i]
91 }
92 }
93
94 // no types, return all requested types
95 if (!types || types.length === 0) {
96 return this.negotiator.mediaTypes()
97 }
98
99 // no accept header, return first given type
100 if (!this.headers.accept) {
101 return types[0]
102 }
103
104 var mimes = types.map(extToMime)
105 var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
106 var first = accepts[0]
107
108 return first
109 ? types[mimes.indexOf(first)]
110 : false
111 }
112
113 /**
114 * Return accepted encodings or best fit based on `encodings`.
115 *
116 * Given `Accept-Encoding: gzip, deflate`
117 * an array sorted by quality is returned:
118 *
119 * ['gzip', 'deflate']
120 *
121 * @param {String|Array} encodings...
122 * @return {String|Array}
123 * @public
124 */
125
126 Accepts.prototype.encoding =
127 Accepts.prototype.encodings = function (encodings_) {
128 var encodings = encodings_
129
130 // support flattened arguments
131 if (encodings && !Array.isArray(encodings)) {
132 encodings = new Array(arguments.length)
133 for (var i = 0; i < encodings.length; i++) {
134 encodings[i] = arguments[i]
135 }
136 }
137
138 // no encodings, return all requested encodings
139 if (!encodings || encodings.length === 0) {
140 return this.negotiator.encodings()
141 }
142
143 return this.negotiator.encodings(encodings)[0] || false
144 }
145
146 /**
147 * Return accepted charsets or best fit based on `charsets`.
148 *
149 * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
150 * an array sorted by quality is returned:
151 *
152 * ['utf-8', 'utf-7', 'iso-8859-1']
153 *
154 * @param {String|Array} charsets...
155 * @return {String|Array}
156 * @public
157 */
158
159 Accepts.prototype.charset =
160 Accepts.prototype.charsets = function (charsets_) {
161 var charsets = charsets_
162
163 // support flattened arguments
164 if (charsets && !Array.isArray(charsets)) {
165 charsets = new Array(arguments.length)
166 for (var i = 0; i < charsets.length; i++) {
167 charsets[i] = arguments[i]
168 }
169 }
170
171 // no charsets, return all requested charsets
172 if (!charsets || charsets.length === 0) {
173 return this.negotiator.charsets()
174 }
175
176 return this.negotiator.charsets(charsets)[0] || false
177 }
178
179 /**
180 * Return accepted languages or best fit based on `langs`.
181 *
182 * Given `Accept-Language: en;q=0.8, es, pt`
183 * an array sorted by quality is returned:
184 *
185 * ['es', 'pt', 'en']
186 *
187 * @param {String|Array} langs...
188 * @return {Array|String}
189 * @public
190 */
191
192 Accepts.prototype.lang =
193 Accepts.prototype.langs =
194 Accepts.prototype.language =
195 Accepts.prototype.languages = function (languages_) {
196 var languages = languages_
197
198 // support flattened arguments
199 if (languages && !Array.isArray(languages)) {
200 languages = new Array(arguments.length)
201 for (var i = 0; i < languages.length; i++) {
202 languages[i] = arguments[i]
203 }
204 }
205
206 // no languages, return all requested languages
207 if (!languages || languages.length === 0) {
208 return this.negotiator.languages()
209 }
210
211 return this.negotiator.languages(languages)[0] || false
212 }
213
214 /**
215 * Convert extnames to mime.
216 *
217 * @param {String} type
218 * @return {String}
219 * @private
220 */
221
222 function extToMime (type) {
223 return type.indexOf('/') === -1
224 ? mime.lookup(type)
225 : type
226 }
227
228 /**
229 * Check if mime is valid.
230 *
231 * @param {String} type
232 * @return {String}
233 * @private
234 */
235
236 function validMime (type) {
237 return typeof type === 'string'
238 }
1 {
2 "_from": "accepts@~1.3.8",
3 "_id": "accepts@1.3.8",
4 "_inBundle": false,
5 "_integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
6 "_location": "/accepts",
7 "_phantomChildren": {},
8 "_requested": {
9 "type": "range",
10 "registry": true,
11 "raw": "accepts@~1.3.8",
12 "name": "accepts",
13 "escapedName": "accepts",
14 "rawSpec": "~1.3.8",
15 "saveSpec": null,
16 "fetchSpec": "~1.3.8"
17 },
18 "_requiredBy": [
19 "/express"
20 ],
21 "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
22 "_shasum": "0bf0be125b67014adcb0b0921e62db7bffe16b2e",
23 "_spec": "accepts@~1.3.8",
24 "_where": "C:\\xampp\\htdocs\\chatgpt.ai-pro.org\\node_modules\\express",
25 "bugs": {
26 "url": "https://github.com/jshttp/accepts/issues"
27 },
28 "bundleDependencies": false,
29 "contributors": [
30 {
31 "name": "Douglas Christopher Wilson",
32 "email": "doug@somethingdoug.com"
33 },
34 {
35 "name": "Jonathan Ong",
36 "email": "me@jongleberry.com",
37 "url": "http://jongleberry.com"
38 }
39 ],
40 "dependencies": {
41 "mime-types": "~2.1.34",
42 "negotiator": "0.6.3"
43 },
44 "deprecated": false,
45 "description": "Higher-level content negotiation",
46 "devDependencies": {
47 "deep-equal": "1.0.1",
48 "eslint": "7.32.0",
49 "eslint-config-standard": "14.1.1",
50 "eslint-plugin-import": "2.25.4",
51 "eslint-plugin-markdown": "2.2.1",
52 "eslint-plugin-node": "11.1.0",
53 "eslint-plugin-promise": "4.3.1",
54 "eslint-plugin-standard": "4.1.0",
55 "mocha": "9.2.0",
56 "nyc": "15.1.0"
57 },
58 "engines": {
59 "node": ">= 0.6"
60 },
61 "files": [
62 "LICENSE",
63 "HISTORY.md",
64 "index.js"
65 ],
66 "homepage": "https://github.com/jshttp/accepts#readme",
67 "keywords": [
68 "content",
69 "negotiation",
70 "accept",
71 "accepts"
72 ],
73 "license": "MIT",
74 "name": "accepts",
75 "repository": {
76 "type": "git",
77 "url": "git+https://github.com/jshttp/accepts.git"
78 },
79 "scripts": {
80 "lint": "eslint .",
81 "test": "mocha --reporter spec --check-leaks --bail test/",
82 "test-ci": "nyc --reporter=lcov --reporter=text npm test",
83 "test-cov": "nyc --reporter=html --reporter=text npm test"
84 },
85 "version": "1.3.8"
86 }
1 The MIT License (MIT)
2
3 Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com)
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
13 all 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
21 THE SOFTWARE.
1 # Array Flatten
2
3 [![NPM version][npm-image]][npm-url]
4 [![NPM downloads][downloads-image]][downloads-url]
5 [![Build status][travis-image]][travis-url]
6 [![Test coverage][coveralls-image]][coveralls-url]
7
8 > Flatten an array of nested arrays into a single flat array. Accepts an optional depth.
9
10 ## Installation
11
12 ```
13 npm install array-flatten --save
14 ```
15
16 ## Usage
17
18 ```javascript
19 var flatten = require('array-flatten')
20
21 flatten([1, [2, [3, [4, [5], 6], 7], 8], 9])
22 //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
23
24 flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2)
25 //=> [1, 2, 3, [4, [5], 6], 7, 8, 9]
26
27 (function () {
28 flatten(arguments) //=> [1, 2, 3]
29 })(1, [2, 3])
30 ```
31
32 ## License
33
34 MIT
35
36 [npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat
37 [npm-url]: https://npmjs.org/package/array-flatten
38 [downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat
39 [downloads-url]: https://npmjs.org/package/array-flatten
40 [travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat
41 [travis-url]: https://travis-ci.org/blakeembrey/array-flatten
42 [coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat
43 [coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master
1 'use strict'
2
3 /**
4 * Expose `arrayFlatten`.
5 */
6 module.exports = arrayFlatten
7
8 /**
9 * Recursive flatten function with depth.
10 *
11 * @param {Array} array
12 * @param {Array} result
13 * @param {Number} depth
14 * @return {Array}
15 */
16 function flattenWithDepth (array, result, depth) {
17 for (var i = 0; i < array.length; i++) {
18 var value = array[i]
19
20 if (depth > 0 && Array.isArray(value)) {
21 flattenWithDepth(value, result, depth - 1)
22 } else {
23 result.push(value)
24 }
25 }
26
27 return result
28 }
29
30 /**
31 * Recursive flatten function. Omitting depth is slightly faster.
32 *
33 * @param {Array} array
34 * @param {Array} result
35 * @return {Array}
36 */
37 function flattenForever (array, result) {
38 for (var i = 0; i < array.length; i++) {
39 var value = array[i]
40
41 if (Array.isArray(value)) {
42 flattenForever(value, result)
43 } else {
44 result.push(value)
45 }
46 }
47
48 return result
49 }
50
51 /**
52 * Flatten an array, with the ability to define a depth.
53 *
54 * @param {Array} array
55 * @param {Number} depth
56 * @return {Array}
57 */
58 function arrayFlatten (array, depth) {
59 if (depth == null) {
60 return flattenForever(array, [])
61 }
62
63 return flattenWithDepth(array, [], depth)
64 }
1 {
2 "_from": "array-flatten@1.1.1",
3 "_id": "array-flatten@1.1.1",
4 "_inBundle": false,
5 "_integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
6 "_location": "/array-flatten",
7 "_phantomChildren": {},
8 "_requested": {
9 "type": "version",
10 "registry": true,
11 "raw": "array-flatten@1.1.1",
12 "name": "array-flatten",
13 "escapedName": "array-flatten",
14 "rawSpec": "1.1.1",
15 "saveSpec": null,
16 "fetchSpec": "1.1.1"
17 },
18 "_requiredBy": [
19 "/express"
20 ],
21 "_resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
22 "_shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2",
23 "_spec": "array-flatten@1.1.1",
24 "_where": "C:\\xampp\\htdocs\\chatgpt.ai-pro.org\\node_modules\\express",
25 "author": {
26 "name": "Blake Embrey",
27 "email": "hello@blakeembrey.com",
28 "url": "http://blakeembrey.me"
29 },
30 "bugs": {
31 "url": "https://github.com/blakeembrey/array-flatten/issues"
32 },
33 "bundleDependencies": false,
34 "deprecated": false,
35 "description": "Flatten an array of nested arrays into a single flat array",
36 "devDependencies": {
37 "istanbul": "^0.3.13",
38 "mocha": "^2.2.4",
39 "pre-commit": "^1.0.7",
40 "standard": "^3.7.3"
41 },
42 "files": [
43 "array-flatten.js",
44 "LICENSE"
45 ],
46 "homepage": "https://github.com/blakeembrey/array-flatten",
47 "keywords": [
48 "array",
49 "flatten",
50 "arguments",
51 "depth"
52 ],
53 "license": "MIT",
54 "main": "array-flatten.js",
55 "name": "array-flatten",
56 "repository": {
57 "type": "git",
58 "url": "git://github.com/blakeembrey/array-flatten.git"
59 },
60 "scripts": {
61 "test": "istanbul cover _mocha -- -R spec"
62 },
63 "version": "1.1.1"
64 }
1 The MIT License (MIT)
2
3 Copyright (c) 2016 Alex Indigo
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 # asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit)
2
3 Minimal async jobs utility library, with streams support.
4
5 [![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit)
6 [![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit)
7 [![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit)
8
9 [![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master)
10 [![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit)
11 [![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit)
12
13 <!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) -->
14
15 AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects.
16 Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method.
17
18 It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators.
19
20 | compression | size |
21 | :----------------- | -------: |
22 | asynckit.js | 12.34 kB |
23 | asynckit.min.js | 4.11 kB |
24 | asynckit.min.js.gz | 1.47 kB |
25
26
27 ## Install
28
29 ```sh
30 $ npm install --save asynckit
31 ```
32
33 ## Examples
34
35 ### Parallel Jobs
36
37 Runs iterator over provided array in parallel. Stores output in the `result` array,
38 on the matching positions. In unlikely event of an error from one of the jobs,
39 will terminate rest of the active jobs (if abort function is provided)
40 and return error along with salvaged data to the main callback function.
41
42 #### Input Array
43
44 ```javascript
45 var parallel = require('asynckit').parallel
46 , assert = require('assert')
47 ;
48
49 var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
50 , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
51 , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
52 , target = []
53 ;
54
55 parallel(source, asyncJob, function(err, result)
56 {
57 assert.deepEqual(result, expectedResult);
58 assert.deepEqual(target, expectedTarget);
59 });
60
61 // async job accepts one element from the array
62 // and a callback function
63 function asyncJob(item, cb)
64 {
65 // different delays (in ms) per item
66 var delay = item * 25;
67
68 // pretend different jobs take different time to finish
69 // and not in consequential order
70 var timeoutId = setTimeout(function() {
71 target.push(item);
72 cb(null, item * 2);
73 }, delay);
74
75 // allow to cancel "leftover" jobs upon error
76 // return function, invoking of which will abort this job
77 return clearTimeout.bind(null, timeoutId);
78 }
79 ```
80
81 More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js).
82
83 #### Input Object
84
85 Also it supports named jobs, listed via object.
86
87 ```javascript
88 var parallel = require('asynckit/parallel')
89 , assert = require('assert')
90 ;
91
92 var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
93 , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
94 , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
95 , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ]
96 , target = []
97 , keys = []
98 ;
99
100 parallel(source, asyncJob, function(err, result)
101 {
102 assert.deepEqual(result, expectedResult);
103 assert.deepEqual(target, expectedTarget);
104 assert.deepEqual(keys, expectedKeys);
105 });
106
107 // supports full value, key, callback (shortcut) interface
108 function asyncJob(item, key, cb)
109 {
110 // different delays (in ms) per item
111 var delay = item * 25;
112
113 // pretend different jobs take different time to finish
114 // and not in consequential order
115 var timeoutId = setTimeout(function() {
116 keys.push(key);
117 target.push(item);
118 cb(null, item * 2);
119 }, delay);
120
121 // allow to cancel "leftover" jobs upon error
122 // return function, invoking of which will abort this job
123 return clearTimeout.bind(null, timeoutId);
124 }
125 ```
126
127 More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js).
128
129 ### Serial Jobs
130
131 Runs iterator over provided array sequentially. Stores output in the `result` array,
132 on the matching positions. In unlikely event of an error from one of the jobs,
133 will not proceed to the rest of the items in the list
134 and return error along with salvaged data to the main callback function.
135
136 #### Input Array
137
138 ```javascript
139 var serial = require('asynckit/serial')
140 , assert = require('assert')
141 ;
142
143 var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
144 , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
145 , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
146 , target = []
147 ;
148
149 serial(source, asyncJob, function(err, result)
150 {
151 assert.deepEqual(result, expectedResult);
152 assert.deepEqual(target, expectedTarget);
153 });
154
155 // extended interface (item, key, callback)
156 // also supported for arrays
157 function asyncJob(item, key, cb)
158 {
159 target.push(key);
160
161 // it will be automatically made async
162 // even it iterator "returns" in the same event loop
163 cb(null, item * 2);
164 }
165 ```
166
167 More examples could be found in [test/test-serial-array.js](test/test-serial-array.js).
168
169 #### Input Object
170
171 Also it supports named jobs, listed via object.
172
173 ```javascript
174 var serial = require('asynckit').serial
175 , assert = require('assert')
176 ;
177
178 var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
179 , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
180 , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
181 , target = []
182 ;
183
184 var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
185 , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
186 , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
187 , target = []
188 ;
189
190
191 serial(source, asyncJob, function(err, result)
192 {
193 assert.deepEqual(result, expectedResult);
194 assert.deepEqual(target, expectedTarget);
195 });
196
197 // shortcut interface (item, callback)
198 // works for object as well as for the arrays
199 function asyncJob(item, cb)
200 {
201 target.push(item);
202
203 // it will be automatically made async
204 // even it iterator "returns" in the same event loop
205 cb(null, item * 2);
206 }
207 ```
208
209 More examples could be found in [test/test-serial-object.js](test/test-serial-object.js).
210
211 _Note: Since _object_ is an _unordered_ collection of properties,
212 it may produce unexpected results with sequential iterations.
213 Whenever order of the jobs' execution is important please use `serialOrdered` method._
214
215 ### Ordered Serial Iterations
216
217 TBD
218
219 For example [compare-property](compare-property) package.
220
221 ### Streaming interface
222
223 TBD
224
225 ## Want to Know More?
226
227 More examples can be found in [test folder](test/).
228
229 Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions.
230
231 ## License
232
233 AsyncKit is licensed under the MIT license.
1 /* eslint no-console: "off" */
2
3 var asynckit = require('./')
4 , async = require('async')
5 , assert = require('assert')
6 , expected = 0
7 ;
8
9 var Benchmark = require('benchmark');
10 var suite = new Benchmark.Suite;
11
12 var source = [];
13 for (var z = 1; z < 100; z++)
14 {
15 source.push(z);
16 expected += z;
17 }
18
19 suite
20 // add tests
21
22 .add('async.map', function(deferred)
23 {
24 var total = 0;
25
26 async.map(source,
27 function(i, cb)
28 {
29 setImmediate(function()
30 {
31 total += i;
32 cb(null, total);
33 });
34 },
35 function(err, result)
36 {
37 assert.ifError(err);
38 assert.equal(result[result.length - 1], expected);
39 deferred.resolve();
40 });
41 }, {'defer': true})
42
43
44 .add('asynckit.parallel', function(deferred)
45 {
46 var total = 0;
47
48 asynckit.parallel(source,
49 function(i, cb)
50 {
51 setImmediate(function()
52 {
53 total += i;
54 cb(null, total);
55 });
56 },
57 function(err, result)
58 {
59 assert.ifError(err);
60 assert.equal(result[result.length - 1], expected);
61 deferred.resolve();
62 });
63 }, {'defer': true})
64
65
66 // add listeners
67 .on('cycle', function(ev)
68 {
69 console.log(String(ev.target));
70 })
71 .on('complete', function()
72 {
73 console.log('Fastest is ' + this.filter('fastest').map('name'));
74 })
75 // run async
76 .run({ 'async': true });
1 module.exports =
2 {
3 parallel : require('./parallel.js'),
4 serial : require('./serial.js'),
5 serialOrdered : require('./serialOrdered.js')
6 };
1 // API
2 module.exports = abort;
3
4 /**
5 * Aborts leftover active jobs
6 *
7 * @param {object} state - current state object
8 */
9 function abort(state)
10 {
11 Object.keys(state.jobs).forEach(clean.bind(state));
12
13 // reset leftover jobs
14 state.jobs = {};
15 }
16
17 /**
18 * Cleans up leftover job by invoking abort function for the provided job id
19 *
20 * @this state
21 * @param {string|number} key - job id to abort
22 */
23 function clean(key)
24 {
25 if (typeof this.jobs[key] == 'function')
26 {
27 this.jobs[key]();
28 }
29 }
1 var defer = require('./defer.js');
2
3 // API
4 module.exports = async;
5
6 /**
7 * Runs provided callback asynchronously
8 * even if callback itself is not
9 *
10 * @param {function} callback - callback to invoke
11 * @returns {function} - augmented callback
12 */
13 function async(callback)
14 {
15 var isAsync = false;
16
17 // check if async happened
18 defer(function() { isAsync = true; });
19
20 return function async_callback(err, result)
21 {
22 if (isAsync)
23 {
24 callback(err, result);
25 }
26 else
27 {
28 defer(function nextTick_callback()
29 {
30 callback(err, result);
31 });
32 }
33 };
34 }
1 module.exports = defer;
2
3 /**
4 * Runs provided function on next iteration of the event loop
5 *
6 * @param {function} fn - function to run
7 */
8 function defer(fn)
9 {
10 var nextTick = typeof setImmediate == 'function'
11 ? setImmediate
12 : (
13 typeof process == 'object' && typeof process.nextTick == 'function'
14 ? process.nextTick
15 : null
16 );
17
18 if (nextTick)
19 {
20 nextTick(fn);
21 }
22 else
23 {
24 setTimeout(fn, 0);
25 }
26 }
1 var async = require('./async.js')
2 , abort = require('./abort.js')
3 ;
4
5 // API
6 module.exports = iterate;
7
8 /**
9 * Iterates over each job object
10 *
11 * @param {array|object} list - array or object (named list) to iterate over
12 * @param {function} iterator - iterator to run
13 * @param {object} state - current job status
14 * @param {function} callback - invoked when all elements processed
15 */
16 function iterate(list, iterator, state, callback)
17 {
18 // store current index
19 var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
20
21 state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
22 {
23 // don't repeat yourself
24 // skip secondary callbacks
25 if (!(key in state.jobs))
26 {
27 return;
28 }
29
30 // clean up jobs
31 delete state.jobs[key];
32
33 if (error)
34 {
35 // don't process rest of the results
36 // stop still active jobs
37 // and reset the list
38 abort(state);
39 }
40 else
41 {
42 state.results[key] = output;
43 }
44
45 // return salvaged results
46 callback(error, state.results);
47 });
48 }
49
50 /**
51 * Runs iterator over provided job element
52 *
53 * @param {function} iterator - iterator to invoke
54 * @param {string|number} key - key/index of the element in the list of jobs
55 * @param {mixed} item - job description
56 * @param {function} callback - invoked after iterator is done with the job
57 * @returns {function|mixed} - job abort function or something else
58 */
59 function runJob(iterator, key, item, callback)
60 {
61 var aborter;
62
63 // allow shortcut if iterator expects only two arguments
64 if (iterator.length == 2)
65 {
66 aborter = iterator(item, async(callback));
67 }
68 // otherwise go with full three arguments
69 else
70 {
71 aborter = iterator(item, key, async(callback));
72 }
73
74 return aborter;
75 }
1 var streamify = require('./streamify.js')
2 , defer = require('./defer.js')
3 ;
4
5 // API
6 module.exports = ReadableAsyncKit;
7
8 /**
9 * Base constructor for all streams
10 * used to hold properties/methods
11 */
12 function ReadableAsyncKit()
13 {
14 ReadableAsyncKit.super_.apply(this, arguments);
15
16 // list of active jobs
17 this.jobs = {};
18
19 // add stream methods
20 this.destroy = destroy;
21 this._start = _start;
22 this._read = _read;
23 }
24
25 /**
26 * Destroys readable stream,
27 * by aborting outstanding jobs
28 *
29 * @returns {void}
30 */
31 function destroy()
32 {
33 if (this.destroyed)
34 {
35 return;
36 }
37
38 this.destroyed = true;
39
40 if (typeof this.terminator == 'function')
41 {
42 this.terminator();
43 }
44 }
45
46 /**
47 * Starts provided jobs in async manner
48 *
49 * @private
50 */
51 function _start()
52 {
53 // first argument – runner function
54 var runner = arguments[0]
55 // take away first argument
56 , args = Array.prototype.slice.call(arguments, 1)
57 // second argument - input data
58 , input = args[0]
59 // last argument - result callback
60 , endCb = streamify.callback.call(this, args[args.length - 1])
61 ;
62
63 args[args.length - 1] = endCb;
64 // third argument - iterator
65 args[1] = streamify.iterator.call(this, args[1]);
66
67 // allow time for proper setup
68 defer(function()
69 {
70 if (!this.destroyed)
71 {
72 this.terminator = runner.apply(null, args);
73 }
74 else
75 {
76 endCb(null, Array.isArray(input) ? [] : {});
77 }
78 }.bind(this));
79 }
80
81
82 /**
83 * Implement _read to comply with Readable streams
84 * Doesn't really make sense for flowing object mode
85 *
86 * @private
87 */
88 function _read()
89 {
90
91 }
1 var parallel = require('../parallel.js');
2
3 // API
4 module.exports = ReadableParallel;
5
6 /**
7 * Streaming wrapper to `asynckit.parallel`
8 *
9 * @param {array|object} list - array or object (named list) to iterate over
10 * @param {function} iterator - iterator to run
11 * @param {function} callback - invoked when all elements processed
12 * @returns {stream.Readable#}
13 */
14 function ReadableParallel(list, iterator, callback)
15 {
16 if (!(this instanceof ReadableParallel))
17 {
18 return new ReadableParallel(list, iterator, callback);
19 }
20
21 // turn on object mode
22 ReadableParallel.super_.call(this, {objectMode: true});
23
24 this._start(parallel, list, iterator, callback);
25 }
1 var serial = require('../serial.js');
2
3 // API
4 module.exports = ReadableSerial;
5
6 /**
7 * Streaming wrapper to `asynckit.serial`
8 *
9 * @param {array|object} list - array or object (named list) to iterate over
10 * @param {function} iterator - iterator to run
11 * @param {function} callback - invoked when all elements processed
12 * @returns {stream.Readable#}
13 */
14 function ReadableSerial(list, iterator, callback)
15 {
16 if (!(this instanceof ReadableSerial))
17 {
18 return new ReadableSerial(list, iterator, callback);
19 }
20
21 // turn on object mode
22 ReadableSerial.super_.call(this, {objectMode: true});
23
24 this._start(serial, list, iterator, callback);
25 }
1 var serialOrdered = require('../serialOrdered.js');
2
3 // API
4 module.exports = ReadableSerialOrdered;
5 // expose sort helpers
6 module.exports.ascending = serialOrdered.ascending;
7 module.exports.descending = serialOrdered.descending;
8
9 /**
10 * Streaming wrapper to `asynckit.serialOrdered`
11 *
12 * @param {array|object} list - array or object (named list) to iterate over
13 * @param {function} iterator - iterator to run
14 * @param {function} sortMethod - custom sort function
15 * @param {function} callback - invoked when all elements processed
16 * @returns {stream.Readable#}
17 */
18 function ReadableSerialOrdered(list, iterator, sortMethod, callback)
19 {
20 if (!(this instanceof ReadableSerialOrdered))
21 {
22 return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
23 }
24
25 // turn on object mode
26 ReadableSerialOrdered.super_.call(this, {objectMode: true});
27
28 this._start(serialOrdered, list, iterator, sortMethod, callback);
29 }
1 // API
2 module.exports = state;
3
4 /**
5 * Creates initial state object
6 * for iteration over list
7 *
8 * @param {array|object} list - list to iterate over
9 * @param {function|null} sortMethod - function to use for keys sort,
10 * or `null` to keep them as is
11 * @returns {object} - initial state object
12 */
13 function state(list, sortMethod)
14 {
15 var isNamedList = !Array.isArray(list)
16 , initState =
17 {
18 index : 0,
19 keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
20 jobs : {},
21 results : isNamedList ? {} : [],
22 size : isNamedList ? Object.keys(list).length : list.length
23 }
24 ;
25
26 if (sortMethod)
27 {
28 // sort array keys based on it's values
29 // sort object's keys just on own merit
30 initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
31 {
32 return sortMethod(list[a], list[b]);
33 });
34 }
35
36 return initState;
37 }
1 var async = require('./async.js');
2
3 // API
4 module.exports = {
5 iterator: wrapIterator,
6 callback: wrapCallback
7 };
8
9 /**
10 * Wraps iterators with long signature
11 *
12 * @this ReadableAsyncKit#
13 * @param {function} iterator - function to wrap
14 * @returns {function} - wrapped function
15 */
16 function wrapIterator(iterator)
17 {
18 var stream = this;
19
20 return function(item, key, cb)
21 {
22 var aborter
23 , wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
24 ;
25
26 stream.jobs[key] = wrappedCb;
27
28 // it's either shortcut (item, cb)
29 if (iterator.length == 2)
30 {
31 aborter = iterator(item, wrappedCb);
32 }
33 // or long format (item, key, cb)
34 else
35 {
36 aborter = iterator(item, key, wrappedCb);
37 }
38
39 return aborter;
40 };
41 }
42
43 /**
44 * Wraps provided callback function
45 * allowing to execute snitch function before
46 * real callback
47 *
48 * @this ReadableAsyncKit#
49 * @param {function} callback - function to wrap
50 * @returns {function} - wrapped function
51 */
52 function wrapCallback(callback)
53 {
54 var stream = this;
55
56 var wrapped = function(error, result)
57 {
58 return finisher.call(stream, error, result, callback);
59 };
60
61 return wrapped;
62 }
63
64 /**
65 * Wraps provided iterator callback function
66 * makes sure snitch only called once,
67 * but passes secondary calls to the original callback
68 *
69 * @this ReadableAsyncKit#
70 * @param {function} callback - callback to wrap
71 * @param {number|string} key - iteration key
72 * @returns {function} wrapped callback
73 */
74 function wrapIteratorCallback(callback, key)
75 {
76 var stream = this;
77
78 return function(error, output)
79 {
80 // don't repeat yourself
81 if (!(key in stream.jobs))
82 {
83 callback(error, output);
84 return;
85 }
86
87 // clean up jobs
88 delete stream.jobs[key];
89
90 return streamer.call(stream, error, {key: key, value: output}, callback);
91 };
92 }
93
94 /**
95 * Stream wrapper for iterator callback
96 *
97 * @this ReadableAsyncKit#
98 * @param {mixed} error - error response
99 * @param {mixed} output - iterator output
100 * @param {function} callback - callback that expects iterator results
101 */
102 function streamer(error, output, callback)
103 {
104 if (error && !this.error)
105 {
106 this.error = error;
107 this.pause();
108 this.emit('error', error);
109 // send back value only, as expected
110 callback(error, output && output.value);
111 return;
112 }
113
114 // stream stuff
115 this.push(output);
116
117 // back to original track
118 // send back value only, as expected
119 callback(error, output && output.value);
120 }
121
122 /**
123 * Stream wrapper for finishing callback
124 *
125 * @this ReadableAsyncKit#
126 * @param {mixed} error - error response
127 * @param {mixed} output - iterator output
128 * @param {function} callback - callback that expects final results
129 */
130 function finisher(error, output, callback)
131 {
132 // signal end of the stream
133 // only for successfully finished streams
134 if (!error)
135 {
136 this.push(null);
137 }
138
139 // back to original track
140 callback(error, output);
141 }
1 var abort = require('./abort.js')
2 , async = require('./async.js')
3 ;
4
5 // API
6 module.exports = terminator;
7
8 /**
9 * Terminates jobs in the attached state context
10 *
11 * @this AsyncKitState#
12 * @param {function} callback - final callback to invoke after termination
13 */
14 function terminator(callback)
15 {
16 if (!Object.keys(this.jobs).length)
17 {
18 return;
19 }
20
21 // fast forward iteration index
22 this.index = this.size;
23
24 // abort jobs
25 abort(this);
26
27 // send back results we have so far
28 async(callback)(null, this.results);
29 }
1 {
2 "_from": "asynckit@^0.4.0",
3 "_id": "asynckit@0.4.0",
4 "_inBundle": false,
5 "_integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
6 "_location": "/asynckit",
7 "_phantomChildren": {},
8 "_requested": {
9 "type": "range",
10 "registry": true,
11 "raw": "asynckit@^0.4.0",
12 "name": "asynckit",
13 "escapedName": "asynckit",
14 "rawSpec": "^0.4.0",
15 "saveSpec": null,
16 "fetchSpec": "^0.4.0"
17 },
18 "_requiredBy": [
19 "/form-data"
20 ],
21 "_resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
22 "_shasum": "c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79",
23 "_spec": "asynckit@^0.4.0",
24 "_where": "C:\\xampp\\htdocs\\chatgpt.ai-pro.org\\node_modules\\form-data",
25 "author": {
26 "name": "Alex Indigo",
27 "email": "iam@alexindigo.com"
28 },
29 "bugs": {
30 "url": "https://github.com/alexindigo/asynckit/issues"
31 },
32 "bundleDependencies": false,
33 "dependencies": {},
34 "deprecated": false,
35 "description": "Minimal async jobs utility library, with streams support",
36 "devDependencies": {
37 "browserify": "^13.0.0",
38 "browserify-istanbul": "^2.0.0",
39 "coveralls": "^2.11.9",
40 "eslint": "^2.9.0",
41 "istanbul": "^0.4.3",
42 "obake": "^0.1.2",
43 "phantomjs-prebuilt": "^2.1.7",
44 "pre-commit": "^1.1.3",
45 "reamde": "^1.1.0",
46 "rimraf": "^2.5.2",
47 "size-table": "^0.2.0",
48 "tap-spec": "^4.1.1",
49 "tape": "^4.5.1"
50 },
51 "homepage": "https://github.com/alexindigo/asynckit#readme",
52 "keywords": [
53 "async",
54 "jobs",
55 "parallel",
56 "serial",
57 "iterator",
58 "array",
59 "object",
60 "stream",
61 "destroy",
62 "terminate",
63 "abort"
64 ],
65 "license": "MIT",
66 "main": "index.js",
67 "name": "asynckit",
68 "pre-commit": [
69 "clean",
70 "lint",
71 "test",
72 "browser",
73 "report",
74 "size"
75 ],
76 "repository": {
77 "type": "git",
78 "url": "git+https://github.com/alexindigo/asynckit.git"
79 },
80 "scripts": {
81 "browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec",
82 "clean": "rimraf coverage",
83 "debug": "tape test/test-*.js",
84 "lint": "eslint *.js lib/*.js test/*.js",
85 "report": "istanbul report",
86 "size": "browserify index.js | size-table asynckit",
87 "test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec",
88 "win-test": "tape test/test-*.js"
89 },
90 "version": "0.4.0"
91 }
1 var iterate = require('./lib/iterate.js')
2 , initState = require('./lib/state.js')
3 , terminator = require('./lib/terminator.js')
4 ;
5
6 // Public API
7 module.exports = parallel;
8
9 /**
10 * Runs iterator over provided array elements in parallel
11 *
12 * @param {array|object} list - array or object (named list) to iterate over
13 * @param {function} iterator - iterator to run
14 * @param {function} callback - invoked when all elements processed
15 * @returns {function} - jobs terminator
16 */
17 function parallel(list, iterator, callback)
18 {
19 var state = initState(list);
20
21 while (state.index < (state['keyedList'] || list).length)
22 {
23 iterate(list, iterator, state, function(error, result)
24 {
25 if (error)
26 {
27 callback(error, result);
28 return;
29 }
30
31 // looks like it's the last one
32 if (Object.keys(state.jobs).length === 0)
33 {
34 callback(null, state.results);
35 return;
36 }
37 });
38
39 state.index++;
40 }
41
42 return terminator.bind(state, callback);
43 }
1 var serialOrdered = require('./serialOrdered.js');
2
3 // Public API
4 module.exports = serial;
5
6 /**
7 * Runs iterator over provided array elements in series
8 *
9 * @param {array|object} list - array or object (named list) to iterate over
10 * @param {function} iterator - iterator to run
11 * @param {function} callback - invoked when all elements processed
12 * @returns {function} - jobs terminator
13 */
14 function serial(list, iterator, callback)
15 {
16 return serialOrdered(list, iterator, null, callback);
17 }
1 var iterate = require('./lib/iterate.js')
2 , initState = require('./lib/state.js')
3 , terminator = require('./lib/terminator.js')
4 ;
5
6 // Public API
7 module.exports = serialOrdered;
8 // sorting helpers
9 module.exports.ascending = ascending;
10 module.exports.descending = descending;
11
12 /**
13 * Runs iterator over provided sorted array elements in series
14 *
15 * @param {array|object} list - array or object (named list) to iterate over
16 * @param {function} iterator - iterator to run
17 * @param {function} sortMethod - custom sort function
18 * @param {function} callback - invoked when all elements processed
19 * @returns {function} - jobs terminator
20 */
21 function serialOrdered(list, iterator, sortMethod, callback)
22 {
23 var state = initState(list, sortMethod);
24
25 iterate(list, iterator, state, function iteratorHandler(error, result)
26 {
27 if (error)
28 {
29 callback(error, result);
30 return;
31 }
32
33 state.index++;
34
35 // are we there yet?
36 if (state.index < (state['keyedList'] || list).length)
37 {
38 iterate(list, iterator, state, iteratorHandler);
39 return;
40 }
41
42 // done here
43 callback(null, state.results);
44 });
45
46 return terminator.bind(state, callback);
47 }
48
49 /*
50 * -- Sort methods
51 */
52
53 /**
54 * sort helper to sort array elements in ascending order
55 *
56 * @param {mixed} a - an item to compare
57 * @param {mixed} b - an item to compare
58 * @returns {number} - comparison result
59 */
60 function ascending(a, b)
61 {
62 return a < b ? -1 : a > b ? 1 : 0;
63 }
64
65 /**
66 * sort helper to sort array elements in descending order
67 *
68 * @param {mixed} a - an item to compare
69 * @param {mixed} b - an item to compare
70 * @returns {number} - comparison result
71 */
72 function descending(a, b)
73 {
74 return -1 * ascending(a, b);
75 }
1 var inherits = require('util').inherits
2 , Readable = require('stream').Readable
3 , ReadableAsyncKit = require('./lib/readable_asynckit.js')
4 , ReadableParallel = require('./lib/readable_parallel.js')
5 , ReadableSerial = require('./lib/readable_serial.js')
6 , ReadableSerialOrdered = require('./lib/readable_serial_ordered.js')
7 ;
8
9 // API
10 module.exports =
11 {
12 parallel : ReadableParallel,
13 serial : ReadableSerial,
14 serialOrdered : ReadableSerialOrdered,
15 };
16
17 inherits(ReadableAsyncKit, Readable);
18
19 inherits(ReadableParallel, ReadableAsyncKit);
20 inherits(ReadableSerial, ReadableAsyncKit);
21 inherits(ReadableSerialOrdered, ReadableAsyncKit);
1 Copyright (c) 2014-present Matt Zabriskie
2
3 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
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
10 The above copyright notice and this permission notice shall be included in
11 all 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
17 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
19 THE SOFTWARE.
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 // TypeScript Version: 3.0
2
3 export type AxiosRequestHeaders = Record<string, string | number | boolean>;
4
5 export type AxiosResponseHeaders = Record<string, string> & {
6 "set-cookie"?: string[]
7 };
8
9 export interface AxiosRequestTransformer {
10 (data: any, headers?: AxiosRequestHeaders): any;
11 }
12
13 export interface AxiosResponseTransformer {
14 (data: any, headers?: AxiosResponseHeaders): any;
15 }
16
17 export interface AxiosAdapter {
18 (config: AxiosRequestConfig): AxiosPromise;
19 }
20
21 export interface AxiosBasicCredentials {
22 username: string;
23 password: string;
24 }
25
26 export interface AxiosProxyConfig {
27 host: string;
28 port: number;
29 auth?: {
30 username: string;
31 password: string;
32 };
33 protocol?: string;
34 }
35
36 export type Method =
37 | 'get' | 'GET'
38 | 'delete' | 'DELETE'
39 | 'head' | 'HEAD'
40 | 'options' | 'OPTIONS'
41 | 'post' | 'POST'
42 | 'put' | 'PUT'
43 | 'patch' | 'PATCH'
44 | 'purge' | 'PURGE'
45 | 'link' | 'LINK'
46 | 'unlink' | 'UNLINK';
47
48 export type ResponseType =
49 | 'arraybuffer'
50 | 'blob'
51 | 'document'
52 | 'json'
53 | 'text'
54 | 'stream';
55
56 export type responseEncoding =
57 | 'ascii' | 'ASCII'
58 | 'ansi' | 'ANSI'
59 | 'binary' | 'BINARY'
60 | 'base64' | 'BASE64'
61 | 'base64url' | 'BASE64URL'
62 | 'hex' | 'HEX'
63 | 'latin1' | 'LATIN1'
64 | 'ucs-2' | 'UCS-2'
65 | 'ucs2' | 'UCS2'
66 | 'utf-8' | 'UTF-8'
67 | 'utf8' | 'UTF8'
68 | 'utf16le' | 'UTF16LE';
69
70 export interface TransitionalOptions {
71 silentJSONParsing?: boolean;
72 forcedJSONParsing?: boolean;
73 clarifyTimeoutError?: boolean;
74 }
75
76 export interface AxiosRequestConfig<D = any> {
77 url?: string;
78 method?: Method;
79 baseURL?: string;
80 transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
81 transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
82 headers?: AxiosRequestHeaders;
83 params?: any;
84 paramsSerializer?: (params: any) => string;
85 data?: D;
86 timeout?: number;
87 timeoutErrorMessage?: string;
88 withCredentials?: boolean;
89 adapter?: AxiosAdapter;
90 auth?: AxiosBasicCredentials;
91 responseType?: ResponseType;
92 responseEncoding?: responseEncoding | string;
93 xsrfCookieName?: string;
94 xsrfHeaderName?: string;
95 onUploadProgress?: (progressEvent: any) => void;
96 onDownloadProgress?: (progressEvent: any) => void;
97 maxContentLength?: number;
98 validateStatus?: ((status: number) => boolean) | null;
99 maxBodyLength?: number;
100 maxRedirects?: number;
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 }
111
112 export interface HeadersDefaults {
113 common: AxiosRequestHeaders;
114 delete: AxiosRequestHeaders;
115 get: AxiosRequestHeaders;
116 head: AxiosRequestHeaders;
117 post: AxiosRequestHeaders;
118 put: AxiosRequestHeaders;
119 patch: AxiosRequestHeaders;
120 options?: AxiosRequestHeaders;
121 purge?: AxiosRequestHeaders;
122 link?: AxiosRequestHeaders;
123 unlink?: AxiosRequestHeaders;
124 }
125
126 export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
127 headers: HeadersDefaults;
128 }
129
130 export interface AxiosResponse<T = any, D = any> {
131 data: T;
132 status: number;
133 statusText: string;
134 headers: AxiosResponseHeaders;
135 config: AxiosRequestConfig<D>;
136 request?: any;
137 }
138
139 export interface AxiosError<T = any, D = any> extends Error {
140 config: AxiosRequestConfig<D>;
141 code?: string;
142 request?: any;
143 response?: AxiosResponse<T, D>;
144 isAxiosError: boolean;
145 toJSON: () => object;
146 }
147
148 export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
149 }
150
151 export interface CancelStatic {
152 new (message?: string): Cancel;
153 }
154
155 export interface Cancel {
156 message: string | undefined;
157 }
158
159 export interface Canceler {
160 (message?: string): void;
161 }
162
163 export interface CancelTokenStatic {
164 new (executor: (cancel: Canceler) => void): CancelToken;
165 source(): CancelTokenSource;
166 }
167
168 export interface CancelToken {
169 promise: Promise<Cancel>;
170 reason?: Cancel;
171 throwIfRequested(): void;
172 }
173
174 export interface CancelTokenSource {
175 token: CancelToken;
176 cancel: Canceler;
177 }
178
179 export interface AxiosInterceptorManager<V> {
180 use<T = V>(onFulfilled?: (value: V) => T | Promise<T>, onRejected?: (error: any) => any): number;
181 eject(id: number): void;
182 }
183
184 export class Axios {
185 constructor(config?: AxiosRequestConfig);
186 defaults: AxiosDefaults;
187 interceptors: {
188 request: AxiosInterceptorManager<AxiosRequestConfig>;
189 response: AxiosInterceptorManager<AxiosResponse>;
190 };
191 getUri(config?: AxiosRequestConfig): string;
192 request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
193 get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
194 delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
195 head<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
196 options<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
197 post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
198 put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
199 patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
200 }
201
202 export interface AxiosInstance extends Axios {
203 (config: AxiosRequestConfig): AxiosPromise;
204 (url: string, config?: AxiosRequestConfig): AxiosPromise;
205 }
206
207 export interface AxiosStatic extends AxiosInstance {
208 create(config?: AxiosRequestConfig): AxiosInstance;
209 Cancel: CancelStatic;
210 CancelToken: CancelTokenStatic;
211 Axios: typeof Axios;
212 readonly VERSION: string;
213 isCancel(value: any): boolean;
214 all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
215 spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
216 isAxiosError(payload: any): payload is AxiosError;
217 }
218
219 declare const axios: AxiosStatic;
220
221 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 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 createError = require('../core/createError');
11 var transitionalDefaults = require('../defaults/transitional');
12 var Cancel = require('../cancel/Cancel');
13
14 module.exports = function xhrAdapter(config) {
15 return new Promise(function dispatchXhrRequest(resolve, reject) {
16 var requestData = config.data;
17 var requestHeaders = config.headers;
18 var responseType = config.responseType;
19 var onCanceled;
20 function done() {
21 if (config.cancelToken) {
22 config.cancelToken.unsubscribe(onCanceled);
23 }
24
25 if (config.signal) {
26 config.signal.removeEventListener('abort', onCanceled);
27 }
28 }
29
30 if (utils.isFormData(requestData)) {
31 delete requestHeaders['Content-Type']; // Let the browser set it
32 }
33
34 var request = new XMLHttpRequest();
35
36 // HTTP basic authentication
37 if (config.auth) {
38 var username = config.auth.username || '';
39 var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
40 requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
41 }
42
43 var fullPath = buildFullPath(config.baseURL, config.url);
44 request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
45
46 // Set the request timeout in MS
47 request.timeout = config.timeout;
48
49 function onloadend() {
50 if (!request) {
51 return;
52 }
53 // Prepare the response
54 var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
55 var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
56 request.responseText : request.response;
57 var response = {
58 data: responseData,
59 status: request.status,
60 statusText: request.statusText,
61 headers: responseHeaders,
62 config: config,
63 request: request
64 };
65
66 settle(function _resolve(value) {
67 resolve(value);
68 done();
69 }, function _reject(err) {
70 reject(err);
71 done();
72 }, response);
73
74 // Clean up request
75 request = null;
76 }
77
78 if ('onloadend' in request) {
79 // Use onloadend if available
80 request.onloadend = onloadend;
81 } else {
82 // Listen for ready state to emulate onloadend
83 request.onreadystatechange = function handleLoad() {
84 if (!request || request.readyState !== 4) {
85 return;
86 }
87
88 // The request errored out and we didn't get a response, this will be
89 // handled by onerror instead
90 // With one exception: request that using file: protocol, most browsers
91 // will return status as 0 even though it's a successful request
92 if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
93 return;
94 }
95 // readystate handler is calling before onerror or ontimeout handlers,
96 // so we should call onloadend on the next 'tick'
97 setTimeout(onloadend);
98 };
99 }
100
101 // Handle browser request cancellation (as opposed to a manual cancellation)
102 request.onabort = function handleAbort() {
103 if (!request) {
104 return;
105 }
106
107 reject(createError('Request aborted', config, 'ECONNABORTED', request));
108
109 // Clean up request
110 request = null;
111 };
112
113 // Handle low level network errors
114 request.onerror = function handleError() {
115 // Real errors are hidden from us by the browser
116 // onerror should only fire if it's a network error
117 reject(createError('Network Error', config, null, request));
118
119 // Clean up request
120 request = null;
121 };
122
123 // Handle timeout
124 request.ontimeout = function handleTimeout() {
125 var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
126 var transitional = config.transitional || transitionalDefaults;
127 if (config.timeoutErrorMessage) {
128 timeoutErrorMessage = config.timeoutErrorMessage;
129 }
130 reject(createError(
131 timeoutErrorMessage,
132 config,
133 transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
134 request));
135
136 // Clean up request
137 request = null;
138 };
139
140 // Add xsrf header
141 // This is only done if running in a standard browser environment.
142 // Specifically not if we're in a web worker, or react-native.
143 if (utils.isStandardBrowserEnv()) {
144 // Add xsrf header
145 var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
146 cookies.read(config.xsrfCookieName) :
147 undefined;
148
149 if (xsrfValue) {
150 requestHeaders[config.xsrfHeaderName] = xsrfValue;
151 }
152 }
153
154 // Add headers to the request
155 if ('setRequestHeader' in request) {
156 utils.forEach(requestHeaders, function setRequestHeader(val, key) {
157 if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
158 // Remove Content-Type if data is undefined
159 delete requestHeaders[key];
160 } else {
161 // Otherwise add header to the request
162 request.setRequestHeader(key, val);
163 }
164 });
165 }
166
167 // Add withCredentials to request if needed
168 if (!utils.isUndefined(config.withCredentials)) {
169 request.withCredentials = !!config.withCredentials;
170 }
171
172 // Add responseType to request if needed
173 if (responseType && responseType !== 'json') {
174 request.responseType = config.responseType;
175 }
176
177 // Handle progress if needed
178 if (typeof config.onDownloadProgress === 'function') {
179 request.addEventListener('progress', config.onDownloadProgress);
180 }
181
182 // Not all browsers support upload events
183 if (typeof config.onUploadProgress === 'function' && request.upload) {
184 request.upload.addEventListener('progress', config.onUploadProgress);
185 }
186
187 if (config.cancelToken || config.signal) {
188 // Handle cancellation
189 // eslint-disable-next-line func-names
190 onCanceled = function(cancel) {
191 if (!request) {
192 return;
193 }
194 reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);
195 request.abort();
196 request = null;
197 };
198
199 config.cancelToken && config.cancelToken.subscribe(onCanceled);
200 if (config.signal) {
201 config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
202 }
203 }
204
205 if (!requestData) {
206 requestData = null;
207 }
208
209 // Send the request
210 request.send(requestData);
211 });
212 };
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.Cancel = require('./cancel/Cancel');
41 axios.CancelToken = require('./cancel/CancelToken');
42 axios.isCancel = require('./cancel/isCancel');
43 axios.VERSION = require('./env/data').version;
44
45 // Expose all/spread
46 axios.all = function all(promises) {
47 return Promise.all(promises);
48 };
49 axios.spread = require('./helpers/spread');
50
51 // Expose isAxiosError
52 axios.isAxiosError = require('./helpers/isAxiosError');
53
54 module.exports = axios;
55
56 // Allow use of default import syntax in TypeScript
57 module.exports.default = axios;
1 'use strict';
2
3 /**
4 * A `Cancel` is an object that is thrown when an operation is canceled.
5 *
6 * @class
7 * @param {string=} message The message.
8 */
9 function Cancel(message) {
10 this.message = message;
11 }
12
13 Cancel.prototype.toString = function toString() {
14 return 'Cancel' + (this.message ? ': ' + this.message : '');
15 };
16
17 Cancel.prototype.__CANCEL__ = true;
18
19 module.exports = Cancel;
1 'use strict';
2
3 var Cancel = require('./Cancel');
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 Cancel(message);
60 resolvePromise(token.reason);
61 });
62 }
63
64 /**
65 * Throws a `Cancel` 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 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 validator = require('../helpers/validator');
9
10 var validators = validator.validators;
11 /**
12 * Create a new instance of Axios
13 *
14 * @param {Object} instanceConfig The default config for the instance
15 */
16 function Axios(instanceConfig) {
17 this.defaults = instanceConfig;
18 this.interceptors = {
19 request: new InterceptorManager(),
20 response: new InterceptorManager()
21 };
22 }
23
24 /**
25 * Dispatch a request
26 *
27 * @param {Object} config The config specific for this request (merged with this.defaults)
28 */
29 Axios.prototype.request = function request(configOrUrl, config) {
30 /*eslint no-param-reassign:0*/
31 // Allow for axios('example/url'[, config]) a la fetch API
32 if (typeof configOrUrl === 'string') {
33 config = config || {};
34 config.url = configOrUrl;
35 } else {
36 config = configOrUrl || {};
37 }
38
39 config = mergeConfig(this.defaults, config);
40
41 // Set config.method
42 if (config.method) {
43 config.method = config.method.toLowerCase();
44 } else if (this.defaults.method) {
45 config.method = this.defaults.method.toLowerCase();
46 } else {
47 config.method = 'get';
48 }
49
50 var transitional = config.transitional;
51
52 if (transitional !== undefined) {
53 validator.assertOptions(transitional, {
54 silentJSONParsing: validators.transitional(validators.boolean),
55 forcedJSONParsing: validators.transitional(validators.boolean),
56 clarifyTimeoutError: validators.transitional(validators.boolean)
57 }, false);
58 }
59
60 // filter out skipped interceptors
61 var requestInterceptorChain = [];
62 var synchronousRequestInterceptors = true;
63 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
64 if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
65 return;
66 }
67
68 synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
69
70 requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
71 });
72
73 var responseInterceptorChain = [];
74 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
75 responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
76 });
77
78 var promise;
79
80 if (!synchronousRequestInterceptors) {
81 var chain = [dispatchRequest, undefined];
82
83 Array.prototype.unshift.apply(chain, requestInterceptorChain);
84 chain = chain.concat(responseInterceptorChain);
85
86 promise = Promise.resolve(config);
87 while (chain.length) {
88 promise = promise.then(chain.shift(), chain.shift());
89 }
90
91 return promise;
92 }
93
94
95 var newConfig = config;
96 while (requestInterceptorChain.length) {
97 var onFulfilled = requestInterceptorChain.shift();
98 var onRejected = requestInterceptorChain.shift();
99 try {
100 newConfig = onFulfilled(newConfig);
101 } catch (error) {
102 onRejected(error);
103 break;
104 }
105 }
106
107 try {
108 promise = dispatchRequest(newConfig);
109 } catch (error) {
110 return Promise.reject(error);
111 }
112
113 while (responseInterceptorChain.length) {
114 promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
115 }
116
117 return promise;
118 };
119
120 Axios.prototype.getUri = function getUri(config) {
121 config = mergeConfig(this.defaults, config);
122 return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
123 };
124
125 // Provide aliases for supported request methods
126 utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
127 /*eslint func-names:0*/
128 Axios.prototype[method] = function(url, config) {
129 return this.request(mergeConfig(config || {}, {
130 method: method,
131 url: url,
132 data: (config || {}).data
133 }));
134 };
135 });
136
137 utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
138 /*eslint func-names:0*/
139 Axios.prototype[method] = function(url, data, config) {
140 return this.request(mergeConfig(config || {}, {
141 method: method,
142 url: url,
143 data: data
144 }));
145 };
146 });
147
148 module.exports = Axios;
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 enhanceError = require('./enhanceError');
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 {Object} config The config.
10 * @param {string} [code] The error code (for example, 'ECONNABORTED').
11 * @param {Object} [request] The request.
12 * @param {Object} [response] The response.
13 * @returns {Error} The created error.
14 */
15 module.exports = function createError(message, config, code, request, response) {
16 var error = new Error(message);
17 return enhanceError(error, config, code, request, response);
18 };
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 Cancel = require('../cancel/Cancel');
8
9 /**
10 * Throws a `Cancel` 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 Cancel('canceled');
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 /**
4 * Update an Error with the specified config, error code, and response.
5 *
6 * @param {Error} error The error to update.
7 * @param {Object} config The config.
8 * @param {string} [code] The error code (for example, 'ECONNABORTED').
9 * @param {Object} [request] The request.
10 * @param {Object} [response] The response.
11 * @returns {Error} The error.
12 */
13 module.exports = function enhanceError(error, config, code, request, response) {
14 error.config = config;
15 if (code) {
16 error.code = code;
17 }
18
19 error.request = request;
20 error.response = response;
21 error.isAxiosError = true;
22
23 error.toJSON = function toJSON() {
24 return {
25 // Standard
26 message: this.message,
27 name: this.name,
28 // Microsoft
29 description: this.description,
30 number: this.number,
31 // Mozilla
32 fileName: this.fileName,
33 lineNumber: this.lineNumber,
34 columnNumber: this.columnNumber,
35 stack: this.stack,
36 // Axios
37 config: this.config,
38 code: this.code,
39 status: this.response && this.response.status ? this.response.status : null
40 };
41 };
42 return error;
43 };
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 'transport': defaultToConfig2,
84 'httpAgent': defaultToConfig2,
85 'httpsAgent': defaultToConfig2,
86 'cancelToken': defaultToConfig2,
87 'socketPath': defaultToConfig2,
88 'responseEncoding': defaultToConfig2,
89 'validateStatus': mergeDirectKeys
90 };
91
92 utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
93 var merge = mergeMap[prop] || mergeDeepProperties;
94 var configValue = merge(prop);
95 (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
96 });
97
98 return config;
99 };
1 'use strict';
2
3 var createError = require('./createError');
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(createError(
18 'Request failed with status code ' + response.status,
19 response.config,
20 null,
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 'use strict';
2
3 var utils = require('../utils');
4 var normalizeHeaderName = require('../helpers/normalizeHeaderName');
5 var enhanceError = require('../core/enhanceError');
6 var transitionalDefaults = require('./transitional');
7
8 var DEFAULT_CONTENT_TYPE = {
9 'Content-Type': 'application/x-www-form-urlencoded'
10 };
11
12 function setContentTypeIfUnset(headers, value) {
13 if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
14 headers['Content-Type'] = value;
15 }
16 }
17
18 function getDefaultAdapter() {
19 var adapter;
20 if (typeof XMLHttpRequest !== 'undefined') {
21 // For browsers use XHR adapter
22 adapter = require('../adapters/xhr');
23 } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
24 // For node use HTTP adapter
25 adapter = require('../adapters/http');
26 }
27 return adapter;
28 }
29
30 function stringifySafely(rawValue, parser, encoder) {
31 if (utils.isString(rawValue)) {
32 try {
33 (parser || JSON.parse)(rawValue);
34 return utils.trim(rawValue);
35 } catch (e) {
36 if (e.name !== 'SyntaxError') {
37 throw e;
38 }
39 }
40 }
41
42 return (encoder || JSON.stringify)(rawValue);
43 }
44
45 var defaults = {
46
47 transitional: transitionalDefaults,
48
49 adapter: getDefaultAdapter(),
50
51 transformRequest: [function transformRequest(data, headers) {
52 normalizeHeaderName(headers, 'Accept');
53 normalizeHeaderName(headers, 'Content-Type');
54
55 if (utils.isFormData(data) ||
56 utils.isArrayBuffer(data) ||
57 utils.isBuffer(data) ||
58 utils.isStream(data) ||
59 utils.isFile(data) ||
60 utils.isBlob(data)
61 ) {
62 return data;
63 }
64 if (utils.isArrayBufferView(data)) {
65 return data.buffer;
66 }
67 if (utils.isURLSearchParams(data)) {
68 setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
69 return data.toString();
70 }
71 if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {
72 setContentTypeIfUnset(headers, 'application/json');
73 return stringifySafely(data);
74 }
75 return data;
76 }],
77
78 transformResponse: [function transformResponse(data) {
79 var transitional = this.transitional || defaults.transitional;
80 var silentJSONParsing = transitional && transitional.silentJSONParsing;
81 var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
82 var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
83
84 if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
85 try {
86 return JSON.parse(data);
87 } catch (e) {
88 if (strictJSONParsing) {
89 if (e.name === 'SyntaxError') {
90 throw enhanceError(e, this, 'E_JSON_PARSE');
91 }
92 throw e;
93 }
94 }
95 }
96
97 return data;
98 }],
99
100 /**
101 * A timeout in milliseconds to abort a request. If set to 0 (default) a
102 * timeout is not created.
103 */
104 timeout: 0,
105
106 xsrfCookieName: 'XSRF-TOKEN',
107 xsrfHeaderName: 'X-XSRF-TOKEN',
108
109 maxContentLength: -1,
110 maxBodyLength: -1,
111
112 validateStatus: function validateStatus(status) {
113 return status >= 200 && status < 300;
114 },
115
116 headers: {
117 common: {
118 'Accept': 'application/json, text/plain, */*'
119 }
120 }
121 };
122
123 utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
124 defaults.headers[method] = {};
125 });
126
127 utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
128 defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
129 });
130
131 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.26.1"
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 '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 /**
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 function combinedKey(parentKey, elKey) {
4 return parentKey + '.' + elKey;
5 }
6
7 function buildFormData(formData, data, parentKey) {
8 if (Array.isArray(data)) {
9 data.forEach(function buildArray(el, i) {
10 buildFormData(formData, el, combinedKey(parentKey, i));
11 });
12 } else if (
13 typeof data === 'object' &&
14 !(data instanceof File || data === null)
15 ) {
16 Object.keys(data).forEach(function buildObject(key) {
17 buildFormData(
18 formData,
19 data[key],
20 parentKey ? combinedKey(parentKey, key) : key
21 );
22 });
23 } else {
24 if (data === undefined) {
25 return;
26 }
27
28 var value =
29 typeof data === 'boolean' || typeof data === 'number'
30 ? data.toString()
31 : data;
32 formData.append(parentKey, value);
33 }
34 }
35
36 /**
37 * convert a data object to FormData
38 *
39 * type FormDataPrimitive = string | Blob | number | boolean
40 * interface FormDataNest {
41 * [x: string]: FormVal
42 * }
43 *
44 * type FormVal = FormDataNest | FormDataPrimitive
45 *
46 * @param {FormVal} data
47 */
48
49 module.exports = function getFormData(data) {
50 var formData = new FormData();
51
52 buildFormData(formData, data);
53
54 return formData;
55 };
1 'use strict';
2
3 var VERSION = require('../env/data').version;
4
5 var validators = {};
6
7 // eslint-disable-next-line func-names
8 ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
9 validators[type] = function validator(thing) {
10 return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
11 };
12 });
13
14 var deprecatedWarnings = {};
15
16 /**
17 * Transitional option validator
18 * @param {function|boolean?} validator - set to false if the transitional option has been removed
19 * @param {string?} version - deprecated version / removed since version
20 * @param {string?} message - some message with additional info
21 * @returns {function}
22 */
23 validators.transitional = function transitional(validator, version, message) {
24 function formatMessage(opt, desc) {
25 return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
26 }
27
28 // eslint-disable-next-line func-names
29 return function(value, opt, opts) {
30 if (validator === false) {
31 throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')));
32 }
33
34 if (version && !deprecatedWarnings[opt]) {
35 deprecatedWarnings[opt] = true;
36 // eslint-disable-next-line no-console
37 console.warn(
38 formatMessage(
39 opt,
40 ' has been deprecated since v' + version + ' and will be removed in the near future'
41 )
42 );
43 }
44
45 return validator ? validator(value, opt, opts) : true;
46 };
47 };
48
49 /**
50 * Assert object's properties type
51 * @param {object} options
52 * @param {object} schema
53 * @param {boolean?} allowUnknown
54 */
55
56 function assertOptions(options, schema, allowUnknown) {
57 if (typeof options !== 'object') {
58 throw new TypeError('options must be an object');
59 }
60 var keys = Object.keys(options);
61 var i = keys.length;
62 while (i-- > 0) {
63 var opt = keys[i];
64 var validator = schema[opt];
65 if (validator) {
66 var value = options[opt];
67 var result = value === undefined || validator(value, opt, options);
68 if (result !== true) {
69 throw new TypeError('option ' + opt + ' must be ' + result);
70 }
71 continue;
72 }
73 if (allowUnknown !== true) {
74 throw Error('Unknown option ' + opt);
75 }
76 }
77 }
78
79 module.exports = {
80 assertOptions: assertOptions,
81 validators: validators
82 };
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 /**
10 * Determine if a value is an Array
11 *
12 * @param {Object} val The value to test
13 * @returns {boolean} True if value is an Array, otherwise false
14 */
15 function isArray(val) {
16 return Array.isArray(val);
17 }
18
19 /**
20 * Determine if a value is undefined
21 *
22 * @param {Object} val The value to test
23 * @returns {boolean} True if the value is undefined, otherwise false
24 */
25 function isUndefined(val) {
26 return typeof val === 'undefined';
27 }
28
29 /**
30 * Determine if a value is a Buffer
31 *
32 * @param {Object} val The value to test
33 * @returns {boolean} True if value is a Buffer, otherwise false
34 */
35 function isBuffer(val) {
36 return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
37 && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
38 }
39
40 /**
41 * Determine if a value is an ArrayBuffer
42 *
43 * @param {Object} val The value to test
44 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
45 */
46 function isArrayBuffer(val) {
47 return toString.call(val) === '[object ArrayBuffer]';
48 }
49
50 /**
51 * Determine if a value is a FormData
52 *
53 * @param {Object} val The value to test
54 * @returns {boolean} True if value is an FormData, otherwise false
55 */
56 function isFormData(val) {
57 return toString.call(val) === '[object FormData]';
58 }
59
60 /**
61 * Determine if a value is a view on an ArrayBuffer
62 *
63 * @param {Object} val The value to test
64 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
65 */
66 function isArrayBufferView(val) {
67 var result;
68 if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
69 result = ArrayBuffer.isView(val);
70 } else {
71 result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
72 }
73 return result;
74 }
75
76 /**
77 * Determine if a value is a String
78 *
79 * @param {Object} val The value to test
80 * @returns {boolean} True if value is a String, otherwise false
81 */
82 function isString(val) {
83 return typeof val === 'string';
84 }
85
86 /**
87 * Determine if a value is a Number
88 *
89 * @param {Object} val The value to test
90 * @returns {boolean} True if value is a Number, otherwise false
91 */
92 function isNumber(val) {
93 return typeof val === 'number';
94 }
95
96 /**
97 * Determine if a value is an Object
98 *
99 * @param {Object} val The value to test
100 * @returns {boolean} True if value is an Object, otherwise false
101 */
102 function isObject(val) {
103 return val !== null && typeof val === 'object';
104 }
105
106 /**
107 * Determine if a value is a plain Object
108 *
109 * @param {Object} val The value to test
110 * @return {boolean} True if value is a plain Object, otherwise false
111 */
112 function isPlainObject(val) {
113 if (toString.call(val) !== '[object Object]') {
114 return false;
115 }
116
117 var prototype = Object.getPrototypeOf(val);
118 return prototype === null || prototype === Object.prototype;
119 }
120
121 /**
122 * Determine if a value is a Date
123 *
124 * @param {Object} val The value to test
125 * @returns {boolean} True if value is a Date, otherwise false
126 */
127 function isDate(val) {
128 return toString.call(val) === '[object Date]';
129 }
130
131 /**
132 * Determine if a value is a File
133 *
134 * @param {Object} val The value to test
135 * @returns {boolean} True if value is a File, otherwise false
136 */
137 function isFile(val) {
138 return toString.call(val) === '[object File]';
139 }
140
141 /**
142 * Determine if a value is a Blob
143 *
144 * @param {Object} val The value to test
145 * @returns {boolean} True if value is a Blob, otherwise false
146 */
147 function isBlob(val) {
148 return toString.call(val) === '[object Blob]';
149 }
150
151 /**
152 * Determine if a value is a Function
153 *
154 * @param {Object} val The value to test
155 * @returns {boolean} True if value is a Function, otherwise false
156 */
157 function isFunction(val) {
158 return toString.call(val) === '[object Function]';
159 }
160
161 /**
162 * Determine if a value is a Stream
163 *
164 * @param {Object} val The value to test
165 * @returns {boolean} True if value is a Stream, otherwise false
166 */
167 function isStream(val) {
168 return isObject(val) && isFunction(val.pipe);
169 }
170
171 /**
172 * Determine if a value is a URLSearchParams object
173 *
174 * @param {Object} val The value to test
175 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
176 */
177 function isURLSearchParams(val) {
178 return toString.call(val) === '[object URLSearchParams]';
179 }
180
181 /**
182 * Trim excess whitespace off the beginning and end of a string
183 *
184 * @param {String} str The String to trim
185 * @returns {String} The String freed of excess whitespace
186 */
187 function trim(str) {
188 return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
189 }
190
191 /**
192 * Determine if we're running in a standard browser environment
193 *
194 * This allows axios to run in a web worker, and react-native.
195 * Both environments support XMLHttpRequest, but not fully standard globals.
196 *
197 * web workers:
198 * typeof window -> undefined
199 * typeof document -> undefined
200 *
201 * react-native:
202 * navigator.product -> 'ReactNative'
203 * nativescript
204 * navigator.product -> 'NativeScript' or 'NS'
205 */
206 function isStandardBrowserEnv() {
207 if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
208 navigator.product === 'NativeScript' ||
209 navigator.product === 'NS')) {
210 return false;
211 }
212 return (
213 typeof window !== 'undefined' &&
214 typeof document !== 'undefined'
215 );
216 }
217
218 /**
219 * Iterate over an Array or an Object invoking a function for each item.
220 *
221 * If `obj` is an Array callback will be called passing
222 * the value, index, and complete array for each item.
223 *
224 * If 'obj' is an Object callback will be called passing
225 * the value, key, and complete object for each property.
226 *
227 * @param {Object|Array} obj The object to iterate
228 * @param {Function} fn The callback to invoke for each item
229 */
230 function forEach(obj, fn) {
231 // Don't bother if no value provided
232 if (obj === null || typeof obj === 'undefined') {
233 return;
234 }
235
236 // Force an array if not already something iterable
237 if (typeof obj !== 'object') {
238 /*eslint no-param-reassign:0*/
239 obj = [obj];
240 }
241
242 if (isArray(obj)) {
243 // Iterate over array values
244 for (var i = 0, l = obj.length; i < l; i++) {
245 fn.call(null, obj[i], i, obj);
246 }
247 } else {
248 // Iterate over object keys
249 for (var key in obj) {
250 if (Object.prototype.hasOwnProperty.call(obj, key)) {
251 fn.call(null, obj[key], key, obj);
252 }
253 }
254 }
255 }
256
257 /**
258 * Accepts varargs expecting each argument to be an object, then
259 * immutably merges the properties of each object and returns result.
260 *
261 * When multiple objects contain the same key the later object in
262 * the arguments list will take precedence.
263 *
264 * Example:
265 *
266 * ```js
267 * var result = merge({foo: 123}, {foo: 456});
268 * console.log(result.foo); // outputs 456
269 * ```
270 *
271 * @param {Object} obj1 Object to merge
272 * @returns {Object} Result of all merge properties
273 */
274 function merge(/* obj1, obj2, obj3, ... */) {
275 var result = {};
276 function assignValue(val, key) {
277 if (isPlainObject(result[key]) && isPlainObject(val)) {
278 result[key] = merge(result[key], val);
279 } else if (isPlainObject(val)) {
280 result[key] = merge({}, val);
281 } else if (isArray(val)) {
282 result[key] = val.slice();
283 } else {
284 result[key] = val;
285 }
286 }
287
288 for (var i = 0, l = arguments.length; i < l; i++) {
289 forEach(arguments[i], assignValue);
290 }
291 return result;
292 }
293
294 /**
295 * Extends object a by mutably adding to it the properties of object b.
296 *
297 * @param {Object} a The object to be extended
298 * @param {Object} b The object to copy properties from
299 * @param {Object} thisArg The object to bind function to
300 * @return {Object} The resulting value of object a
301 */
302 function extend(a, b, thisArg) {
303 forEach(b, function assignValue(val, key) {
304 if (thisArg && typeof val === 'function') {
305 a[key] = bind(val, thisArg);
306 } else {
307 a[key] = val;
308 }
309 });
310 return a;
311 }
312
313 /**
314 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
315 *
316 * @param {string} content with BOM
317 * @return {string} content value without BOM
318 */
319 function stripBOM(content) {
320 if (content.charCodeAt(0) === 0xFEFF) {
321 content = content.slice(1);
322 }
323 return content;
324 }
325
326 module.exports = {
327 isArray: isArray,
328 isArrayBuffer: isArrayBuffer,
329 isBuffer: isBuffer,
330 isFormData: isFormData,
331 isArrayBufferView: isArrayBufferView,
332 isString: isString,
333 isNumber: isNumber,
334 isObject: isObject,
335 isPlainObject: isPlainObject,
336 isUndefined: isUndefined,
337 isDate: isDate,
338 isFile: isFile,
339 isBlob: isBlob,
340 isFunction: isFunction,
341 isStream: isStream,
342 isURLSearchParams: isURLSearchParams,
343 isStandardBrowserEnv: isStandardBrowserEnv,
344 forEach: forEach,
345 merge: merge,
346 extend: extend,
347 trim: trim,
348 stripBOM: stripBOM
349 };
1 {
2 "_from": "axios@^0.26.0",
3 "_id": "axios@0.26.1",
4 "_inBundle": false,
5 "_integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==",
6 "_location": "/axios",
7 "_phantomChildren": {},
8 "_requested": {
9 "type": "range",
10 "registry": true,
11 "raw": "axios@^0.26.0",
12 "name": "axios",
13 "escapedName": "axios",
14 "rawSpec": "^0.26.0",
15 "saveSpec": null,
16 "fetchSpec": "^0.26.0"
17 },
18 "_requiredBy": [
19 "/openai"
20 ],
21 "_resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz",
22 "_shasum": "1ede41c51fcf51bbbd6fd43669caaa4f0495aaa9",
23 "_spec": "axios@^0.26.0",
24 "_where": "C:\\xampp\\htdocs\\chatgpt.ai-pro.org\\node_modules\\openai",
25 "author": {
26 "name": "Matt Zabriskie"
27 },
28 "browser": {
29 "./lib/adapters/http.js": "./lib/adapters/xhr.js"
30 },
31 "bugs": {
32 "url": "https://github.com/axios/axios/issues"
33 },
34 "bundleDependencies": false,
35 "bundlesize": [
36 {
37 "path": "./dist/axios.min.js",
38 "threshold": "5kB"
39 }
40 ],
41 "dependencies": {
42 "follow-redirects": "^1.14.8"
43 },
44 "deprecated": false,
45 "description": "Promise based HTTP client for the browser and node.js",
46 "devDependencies": {
47 "abortcontroller-polyfill": "^1.5.0",
48 "coveralls": "^3.0.0",
49 "dtslint": "^4.1.6",
50 "es6-promise": "^4.2.4",
51 "grunt": "^1.3.0",
52 "grunt-banner": "^0.6.0",
53 "grunt-cli": "^1.2.0",
54 "grunt-contrib-clean": "^1.1.0",
55 "grunt-contrib-watch": "^1.0.0",
56 "grunt-eslint": "^23.0.0",
57 "grunt-karma": "^4.0.0",
58 "grunt-mocha-test": "^0.13.3",
59 "grunt-webpack": "^4.0.2",
60 "istanbul-instrumenter-loader": "^1.0.0",
61 "jasmine-core": "^2.4.1",
62 "karma": "^6.3.2",
63 "karma-chrome-launcher": "^3.1.0",
64 "karma-firefox-launcher": "^2.1.0",
65 "karma-jasmine": "^1.1.1",
66 "karma-jasmine-ajax": "^0.1.13",
67 "karma-safari-launcher": "^1.0.0",
68 "karma-sauce-launcher": "^4.3.6",
69 "karma-sinon": "^1.0.5",
70 "karma-sourcemap-loader": "^0.3.8",
71 "karma-webpack": "^4.0.2",
72 "load-grunt-tasks": "^3.5.2",
73 "minimist": "^1.2.0",
74 "mocha": "^8.2.1",
75 "sinon": "^4.5.0",
76 "terser-webpack-plugin": "^4.2.3",
77 "typescript": "^4.0.5",
78 "url-search-params": "^0.10.0",
79 "webpack": "^4.44.2",
80 "webpack-dev-server": "^3.11.0"
81 },
82 "homepage": "https://axios-http.com",
83 "jsdelivr": "dist/axios.min.js",
84 "keywords": [
85 "xhr",
86 "http",
87 "ajax",
88 "promise",
89 "node"
90 ],
91 "license": "MIT",
92 "main": "index.js",
93 "name": "axios",
94 "repository": {
95 "type": "git",
96 "url": "git+https://github.com/axios/axios.git"
97 },
98 "scripts": {
99 "build": "NODE_ENV=production grunt build",
100 "coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
101 "examples": "node ./examples/server.js",
102 "fix": "eslint --fix lib/**/*.js",
103 "postversion": "git push && git push --tags",
104 "preversion": "grunt version && npm test",
105 "start": "node ./sandbox/server.js",
106 "test": "grunt test && dtslint",
107 "version": "npm run build && git add -A dist && git add CHANGELOG.md bower.json package.json"
108 },
109 "types": "index.d.ts",
110 "typings": "./index.d.ts",
111 "unpkg": "dist/axios.min.js",
112 "version": "0.26.1"
113 }
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 2.0.1 / 2018-09-19
2 ==================
3
4 * deps: safe-buffer@5.1.2
5
6 2.0.0 / 2017-09-12
7 ==================
8
9 * Drop support for Node.js below 0.8
10 * Remove `auth(ctx)` signature -- pass in header or `auth(ctx.req)`
11 * Use `safe-buffer` for improved Buffer API
12
13 1.1.0 / 2016-11-18
14 ==================
15
16 * Add `auth.parse` for low-level string parsing
17
18 1.0.4 / 2016-05-10
19 ==================
20
21 * Improve error message when `req` argument is not an object
22 * Improve error message when `req` missing `headers` property
23
24 1.0.3 / 2015-07-01
25 ==================
26
27 * Fix regression accepting a Koa context
28
29 1.0.2 / 2015-06-12
30 ==================
31
32 * Improve error message when `req` argument missing
33 * perf: enable strict mode
34 * perf: hoist regular expression
35 * perf: parse with regular expressions
36 * perf: remove argument reassignment
37
38 1.0.1 / 2015-05-04
39 ==================
40
41 * Update readme
42
43 1.0.0 / 2014-07-01
44 ==================
45
46 * Support empty password
47 * Support empty username
48
49 0.0.1 / 2013-11-30
50 ==================
51
52 * Initial release
1 (The MIT License)
2
3 Copyright (c) 2013 TJ Holowaychuk
4 Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
5 Copyright (c) 2015-2016 Douglas Christopher Wilson <doug@somethingdoug.com>
6
7 Permission is hereby granted, free of charge, to any person obtaining
8 a copy of this software and associated documentation files (the
9 'Software'), to deal in the Software without restriction, including
10 without limitation the rights to use, copy, modify, merge, publish,
11 distribute, sublicense, and/or sell copies of the Software, and to
12 permit persons to whom the Software is furnished to do so, subject to
13 the following conditions:
14
15 The above copyright notice and this permission notice shall be
16 included in all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
19 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 # basic-auth
2
3 [![NPM Version][npm-image]][npm-url]
4 [![NPM Downloads][downloads-image]][downloads-url]
5 [![Node.js Version][node-version-image]][node-version-url]
6 [![Build Status][travis-image]][travis-url]
7 [![Test Coverage][coveralls-image]][coveralls-url]
8
9 Generic basic auth Authorization header field parser for whatever.
10
11 ## Installation
12
13 This is a [Node.js](https://nodejs.org/en/) module available through the
14 [npm registry](https://www.npmjs.com/). Installation is done using the
15 [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
16
17 ```
18 $ npm install basic-auth
19 ```
20
21 ## API
22
23 <!-- eslint-disable no-unused-vars -->
24
25 ```js
26 var auth = require('basic-auth')
27 ```
28
29 ### auth(req)
30
31 Get the basic auth credentials from the given request. The `Authorization`
32 header is parsed and if the header is invalid, `undefined` is returned,
33 otherwise an object with `name` and `pass` properties.
34
35 ### auth.parse(string)
36
37 Parse a basic auth authorization header string. This will return an object
38 with `name` and `pass` properties, or `undefined` if the string is invalid.
39
40 ## Example
41
42 Pass a Node.js request object to the module export. If parsing fails
43 `undefined` is returned, otherwise an object with `.name` and `.pass`.
44
45 <!-- eslint-disable no-unused-vars, no-undef -->
46
47 ```js
48 var auth = require('basic-auth')
49 var user = auth(req)
50 // => { name: 'something', pass: 'whatever' }
51 ```
52
53 A header string from any other location can also be parsed with
54 `auth.parse`, for example a `Proxy-Authorization` header:
55
56 <!-- eslint-disable no-unused-vars, no-undef -->
57
58 ```js
59 var auth = require('basic-auth')
60 var user = auth.parse(req.getHeader('Proxy-Authorization'))
61 ```
62
63 ### With vanilla node.js http server
64
65 ```js
66 var http = require('http')
67 var auth = require('basic-auth')
68 var compare = require('tsscmp')
69
70 // Create server
71 var server = http.createServer(function (req, res) {
72 var credentials = auth(req)
73
74 // Check credentials
75 // The "check" function will typically be against your user store
76 if (!credentials || !check(credentials.name, credentials.pass)) {
77 res.statusCode = 401
78 res.setHeader('WWW-Authenticate', 'Basic realm="example"')
79 res.end('Access denied')
80 } else {
81 res.end('Access granted')
82 }
83 })
84
85 // Basic function to validate credentials for example
86 function check (name, pass) {
87 var valid = true
88
89 // Simple method to prevent short-circut and use timing-safe compare
90 valid = compare(name, 'john') && valid
91 valid = compare(pass, 'secret') && valid
92
93 return valid
94 }
95
96 // Listen
97 server.listen(3000)
98 ```
99
100 # License
101
102 [MIT](LICENSE)
103
104 [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/basic-auth/master
105 [coveralls-url]: https://coveralls.io/r/jshttp/basic-auth?branch=master
106 [downloads-image]: https://badgen.net/npm/dm/basic-auth
107 [downloads-url]: https://npmjs.org/package/basic-auth
108 [node-version-image]: https://badgen.net/npm/node/basic-auth
109 [node-version-url]: https://nodejs.org/en/download
110 [npm-image]: https://badgen.net/npm/v/basic-auth
111 [npm-url]: https://npmjs.org/package/basic-auth
112 [travis-image]: https://badgen.net/travis/jshttp/basic-auth/master
113 [travis-url]: https://travis-ci.org/jshttp/basic-auth
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.
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!